Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Move models to their own package

Roland Geider02279ee097ea
diff --git a/wger/config/models.py b/wger/config/models.py
deleted file mode 100644
index 1085589de..000000000
--- a/wger/config/models.py
+++ /dev/null
@@ -1,170 +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
-# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
-
-# Standard Library
-import logging
-
-# Django
-from django.core.cache import cache
-from django.db import models
-from django.utils.translation import gettext_lazy as _
-
-# wger
-from wger.core.models import (
- Language,
- UserProfile,
-)
-from wger.gym.helpers import is_any_gym_admin
-from wger.gym.models import (
- Gym,
- GymUserConfig,
-)
-from wger.utils.cache import (
- cache_mapper,
- delete_template_fragment_cache,
-)
-
-
-logger = logging.getLogger(__name__)
-
-
-class LanguageConfig(models.Model):
- """
- Configuration for languages
-
- Allows to specify what exercises and ingredients are shown for each language
- """
- SHOW_ITEM_EXERCISES = '1'
- SHOW_ITEM_INGREDIENTS = '2'
- SHOW_ITEM_LIST = (
- (SHOW_ITEM_EXERCISES, _('Exercises')),
- (SHOW_ITEM_INGREDIENTS, _('Ingredients')),
- )
-
- language = models.ForeignKey(
- Language,
- related_name='language_source',
- editable=False,
- on_delete=models.CASCADE,
- )
- language_target = models.ForeignKey(
- Language,
- related_name='language_target',
- editable=False,
- on_delete=models.CASCADE,
- )
- item = models.CharField(max_length=2, choices=SHOW_ITEM_LIST, editable=False)
- show = models.BooleanField(default=1)
-
- class Meta:
- """
- Set some other properties
- """
- ordering = [
- "item",
- "language_target",
- ]
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return "Config for language {0}".format(self.language)
-
- def save(self, *args, **kwargs):
- """
- Reset all cached infos
- """
-
- super(LanguageConfig, self).save(*args, **kwargs)
-
- # Cached objects
- cache.delete(cache_mapper.get_language_config_key(self.language, self.item))
-
- # Cached template fragments
- delete_template_fragment_cache('muscle-overview', self.language_id)
- delete_template_fragment_cache('exercise-overview', self.language_id)
-
- def delete(self, *args, **kwargs):
- """
- Reset all cached infos
- """
-
- # Cached objects
- cache.delete(cache_mapper.get_language_config_key(self.language, self.item))
-
- # Cached template fragments
- delete_template_fragment_cache('muscle-overview', self.language_id)
- delete_template_fragment_cache('exercise-overview', self.language_id)
-
- super(LanguageConfig, self).delete(*args, **kwargs)
-
-
-class GymConfig(models.Model):
- """
- System wide configuration for gyms
-
- At the moment this only allows to set one gym as the default
- TODO: close registration (users can only become members thorough an admin)
- """
-
- default_gym = models.ForeignKey(
- Gym,
- verbose_name=_('Default gym'),
- help_text=_(
- 'Select the default gym for this installation. '
- 'This will assign all new registered users to this '
- 'gym and update all existing users without a '
- 'gym.'
- ),
- null=True,
- blank=True,
- on_delete=models.CASCADE
- )
- """
- Default gym for the wger installation
- """
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return "Default gym {0}".format(self.default_gym)
-
- def save(self, *args, **kwargs):
- """
- Perform additional tasks
- """
- if self.default_gym:
-
- # All users that have no gym set in the profile are edited
- UserProfile.objects.filter(gym=None).update(gym=self.default_gym)
-
- # All users in the gym must have a gym config
- for profile in UserProfile.objects.filter(gym=self.default_gym):
- user = profile.user
- if not is_any_gym_admin(user):
- try:
- user.gymuserconfig
- except GymUserConfig.DoesNotExist:
- config = GymUserConfig()
- config.gym = self.default_gym
- config.user = user
- config.save()
- logger.debug('Creating GymUserConfig for user {0}'.format(user.username))
-
- return super(GymConfig, self).save(*args, **kwargs)
diff --git a/wger/config/models/__init__.py b/wger/config/models/__init__.py
new file mode 100644
index 000000000..f9c0f01f4
--- /dev/null
+++ b/wger/config/models/__init__.py
@@ -0,0 +1,19 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Local
+from .gym_config import GymConfig
+from .language_config import LanguageConfig
diff --git a/wger/config/models/gym_config.py b/wger/config/models/gym_config.py
new file mode 100644
index 000000000..babf57eaf
--- /dev/null
+++ b/wger/config/models/gym_config.py
@@ -0,0 +1,88 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Standard Library
+import logging
+
+# Django
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.core.models import UserProfile
+from wger.gym.helpers import is_any_gym_admin
+from wger.gym.models import (
+ Gym,
+ GymUserConfig,
+)
+
+logger = logging.getLogger(__name__)
+
+
+class GymConfig(models.Model):
+ """
+ System wide configuration for gyms
+
+ At the moment this only allows to set one gym as the default
+ TODO: close registration (users can only become members thorough an admin)
+ """
+
+ default_gym = models.ForeignKey(
+ Gym,
+ verbose_name=_('Default gym'),
+ help_text=_(
+ 'Select the default gym for this installation. '
+ 'This will assign all new registered users to this '
+ 'gym and update all existing users without a '
+ 'gym.'
+ ),
+ null=True,
+ blank=True,
+ on_delete=models.CASCADE
+ )
+ """
+ Default gym for the wger installation
+ """
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return "Default gym {0}".format(self.default_gym)
+
+ def save(self, *args, **kwargs):
+ """
+ Perform additional tasks
+ """
+ if self.default_gym:
+
+ # All users that have no gym set in the profile are edited
+ UserProfile.objects.filter(gym=None).update(gym=self.default_gym)
+
+ # All users in the gym must have a gym config
+ for profile in UserProfile.objects.filter(gym=self.default_gym):
+ user = profile.user
+ if not is_any_gym_admin(user):
+ try:
+ user.gymuserconfig
+ except GymUserConfig.DoesNotExist:
+ config = GymUserConfig()
+ config.gym = self.default_gym
+ config.user = user
+ config.save()
+ logger.debug('Creating GymUserConfig for user {0}'.format(user.username))
+
+ return super(GymConfig, self).save(*args, **kwargs)
diff --git a/wger/config/models/language_config.py b/wger/config/models/language_config.py
new file mode 100644
index 000000000..e41784447
--- /dev/null
+++ b/wger/config/models/language_config.py
@@ -0,0 +1,101 @@
+# 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
+
+# Django
+from django.core.cache import cache
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.core.models import Language
+from wger.utils.cache import (
+ cache_mapper,
+ delete_template_fragment_cache,
+)
+
+
+class LanguageConfig(models.Model):
+ """
+ Configuration for languages
+
+ Allows to specify what exercises and ingredients are shown for each language
+ """
+ SHOW_ITEM_EXERCISES = '1'
+ SHOW_ITEM_INGREDIENTS = '2'
+ SHOW_ITEM_LIST = (
+ (SHOW_ITEM_EXERCISES, _('Exercises')),
+ (SHOW_ITEM_INGREDIENTS, _('Ingredients')),
+ )
+
+ language = models.ForeignKey(
+ Language,
+ related_name='language_source',
+ editable=False,
+ on_delete=models.CASCADE,
+ )
+ language_target = models.ForeignKey(
+ Language,
+ related_name='language_target',
+ editable=False,
+ on_delete=models.CASCADE,
+ )
+ item = models.CharField(max_length=2, choices=SHOW_ITEM_LIST, editable=False)
+ show = models.BooleanField(default=1)
+
+ class Meta:
+ """
+ Set some other properties
+ """
+ ordering = [
+ "item",
+ "language_target",
+ ]
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return "Config for language {0}".format(self.language)
+
+ def save(self, *args, **kwargs):
+ """
+ Reset all cached infos
+ """
+
+ super(LanguageConfig, self).save(*args, **kwargs)
+
+ # Cached objects
+ cache.delete(cache_mapper.get_language_config_key(self.language, self.item))
+
+ # Cached template fragments
+ delete_template_fragment_cache('muscle-overview', self.language_id)
+ delete_template_fragment_cache('exercise-overview', self.language_id)
+
+ def delete(self, *args, **kwargs):
+ """
+ Reset all cached infos
+ """
+
+ # Cached objects
+ cache.delete(cache_mapper.get_language_config_key(self.language, self.item))
+
+ # Cached template fragments
+ delete_template_fragment_cache('muscle-overview', self.language_id)
+ delete_template_fragment_cache('exercise-overview', self.language_id)
+
+ super(LanguageConfig, self).delete(*args, **kwargs)
diff --git a/wger/core/management/commands/add-user-rest.py b/wger/core/management/commands/add-user-rest.py
index 6b339684d..121674982 100644
--- a/wger/core/management/commands/add-user-rest.py
+++ b/wger/core/management/commands/add-user-rest.py
@@ -1,10 +1,6 @@
# Django
+from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
-
-# wger
-from wger.core.models import User
-
-
"""
Custom command permitting users to create user accounts
"""
diff --git a/wger/core/migrations/0010_auto_20170403_0144.py b/wger/core/migrations/0010_auto_20170403_0144.py
index 2a4a7d7dd..729d81e14 100644
--- a/wger/core/migrations/0010_auto_20170403_0144.py
+++ b/wger/core/migrations/0010_auto_20170403_0144.py
@@ -17,7 +17,7 @@ class Migration(migrations.Migration):
name='birthdate',
field=models.DateField(
null=True,
- validators=[wger.core.models.birthdate_validator],
+ validators=[wger.core.models.profile.birthdate_validator],
verbose_name='Date of Birth'
),
),
diff --git a/wger/core/models/__init__.py b/wger/core/models/__init__.py
new file mode 100644
index 000000000..8b71cadd7
--- /dev/null
+++ b/wger/core/models/__init__.py
@@ -0,0 +1,24 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Local
+from .cache import UserCache
+from .days_of_week import DaysOfWeek
+from .language import Language
+from .license import License
+from .profile import UserProfile
+from .rep_unit import RepetitionUnit
+from .weight_unit import WeightUnit
diff --git a/wger/core/models/cache.py b/wger/core/models/cache.py
new file mode 100644
index 000000000..dd2639bc4
--- /dev/null
+++ b/wger/core/models/cache.py
@@ -0,0 +1,44 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.contrib.auth.models import User
+from django.db import models
+
+
+class UserCache(models.Model):
+ """
+ A table used to cache expensive queries or similar
+ """
+
+ user = models.OneToOneField(User, editable=False, on_delete=models.CASCADE)
+ """
+ The user
+ """
+
+ last_activity = models.DateField(null=True)
+ """
+ The user's last activity.
+
+ Values for this entry are saved by signals as calculated by the
+ get_user_last_activity helper function.
+ """
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return f"Cache for user {self.user}"
diff --git a/wger/core/models/days_of_week.py b/wger/core/models/days_of_week.py
new file mode 100644
index 000000000..2fb4b90d1
--- /dev/null
+++ b/wger/core/models/days_of_week.py
@@ -0,0 +1,43 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+
+class DaysOfWeek(models.Model):
+ """
+ Model for the days of the week
+
+ This model is needed so that 'Day' can have multiple days of the week selected
+ """
+
+ day_of_week = models.CharField(max_length=9, verbose_name=_('Day of the week'))
+
+ class Meta:
+ """
+ Order by day-ID, this is needed for some DBs
+ """
+ ordering = [
+ "pk",
+ ]
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return self.day_of_week
diff --git a/wger/core/models/language.py b/wger/core/models/language.py
new file mode 100644
index 000000000..14d2e1c40
--- /dev/null
+++ b/wger/core/models/language.py
@@ -0,0 +1,64 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.db import models
+from django.urls import reverse
+from django.utils.translation import gettext_lazy as _
+
+
+class Language(models.Model):
+ """
+ Language of an item (exercise, workout, etc.)
+ """
+
+ # e.g. 'de'
+ short_name = models.CharField(max_length=2, verbose_name=_('Language short name'))
+
+ # e.g. 'Deutsch'
+ full_name = models.CharField(max_length=30, verbose_name=_('Language full name'))
+
+ class Meta:
+ """
+ Set Meta options
+ """
+ ordering = [
+ "full_name",
+ ]
+
+ #
+ # Django methods
+ #
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return f"{self.full_name} ({self.short_name})"
+
+ def get_absolute_url(self):
+ """
+ Returns the canonical URL to view a language
+ """
+ return reverse('core:language:view', kwargs={'pk': self.id})
+
+ #
+ # Own methods
+ #
+ def get_owner_object(self):
+ """
+ Muscle has no owner information
+ """
+ return False
diff --git a/wger/core/models/license.py b/wger/core/models/license.py
new file mode 100644
index 000000000..01b78b53f
--- /dev/null
+++ b/wger/core/models/license.py
@@ -0,0 +1,73 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+
+class License(models.Model):
+ """
+ License for an item (exercise, ingredient, etc.)
+ """
+
+ full_name = models.CharField(
+ max_length=60,
+ verbose_name=_('Full name'),
+ help_text=_(
+ 'If a license has been localized, e.g. the Creative '
+ 'Commons licenses for the different countries, add '
+ 'them as separate entries here.'
+ )
+ )
+ """Full name"""
+
+ short_name = models.CharField(max_length=15, verbose_name=_('Short name, e.g. CC-BY-SA 3'))
+ """Short name, e.g. CC-BY-SA 3"""
+
+ url = models.URLField(
+ verbose_name=_('Link'),
+ help_text=_('Link to license text or other information'),
+ blank=True,
+ null=True
+ )
+ """URL to full license text or other information"""
+
+ class Meta:
+ """
+ Set Meta options
+ """
+ ordering = [
+ "full_name",
+ ]
+
+ #
+ # Django methods
+ #
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return f"{self.full_name} ({self.short_name})"
+
+ #
+ # Own methods
+ #
+ def get_owner_object(self):
+ """
+ License has no owner information
+ """
+ return None
diff --git a/wger/core/models.py b/wger/core/models/profile.py
similarity index 73%
rename from wger/core/models.py
rename to wger/core/models/profile.py
index 731d85a3c..407581f16 100644
--- a/wger/core/models.py
+++ b/wger/core/models/profile.py
@@ -1,18 +1,18 @@
-# -*- coding: utf-8 -*-
-
-# This file is part of wger Workout Manager.
+# 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 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.
+# 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
+# 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
@@ -27,7 +27,6 @@ from django.core.validators import (
)
from django.db import models
from django.db.models import IntegerField
-from django.urls import reverse
from django.utils.translation import gettext_lazy as _
# wger
@@ -36,49 +35,8 @@ from wger.utils.constants import TWOPLACES
from wger.utils.units import AbstractWeight
from wger.weight.models import WeightEntry
-
-class Language(models.Model):
- """
- Language of an item (exercise, workout, etc.)
- """
-
- # e.g. 'de'
- short_name = models.CharField(max_length=2, verbose_name=_('Language short name'))
-
- # e.g. 'Deutsch'
- full_name = models.CharField(max_length=30, verbose_name=_('Language full name'))
-
- class Meta:
- """
- Set Meta options
- """
- ordering = [
- "full_name",
- ]
-
- #
- # Django methods
- #
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return f"{self.full_name} ({self.short_name})"
-
- def get_absolute_url(self):
- """
- Returns the canonical URL to view a language
- """
- return reverse('core:language:view', kwargs={'pk': self.id})
-
- #
- # Own methods
- #
- def get_owner_object(self):
- """
- Muscle has no owner information
- """
- return False
+# Local
+from .language import Language
def birthdate_validator(birthdate):
@@ -577,186 +535,3 @@ by the US Department of Agriculture. It is extremely complete, with around
Returns the object that has owner information
"""
return self
-
-
-class UserCache(models.Model):
- """
- A table used to cache expensive queries or similar
- """
-
- user = models.OneToOneField(User, editable=False, on_delete=models.CASCADE)
- """
- The user
- """
-
- last_activity = models.DateField(null=True)
- """
- The user's last activity.
-
- Values for this entry are saved by signals as calculated by the
- get_user_last_activity helper function.
- """
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return f"Cache for user {self.user}"
-
-
-class DaysOfWeek(models.Model):
- """
- Model for the days of the week
-
- This model is needed so that 'Day' can have multiple days of the week selected
- """
-
- day_of_week = models.CharField(max_length=9, verbose_name=_('Day of the week'))
-
- class Meta:
- """
- Order by day-ID, this is needed for some DBs
- """
- ordering = [
- "pk",
- ]
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.day_of_week
-
-
-class License(models.Model):
- """
- License for an item (exercise, ingredient, etc.)
- """
-
- full_name = models.CharField(
- max_length=60,
- verbose_name=_('Full name'),
- help_text=_(
- 'If a license has been localized, e.g. the Creative '
- 'Commons licenses for the different countries, add '
- 'them as separate entries here.'
- )
- )
- """Full name"""
-
- short_name = models.CharField(max_length=15, verbose_name=_('Short name, e.g. CC-BY-SA 3'))
- """Short name, e.g. CC-BY-SA 3"""
-
- url = models.URLField(
- verbose_name=_('Link'),
- help_text=_('Link to license text or other information'),
- blank=True,
- null=True
- )
- """URL to full license text or other information"""
-
- class Meta:
- """
- Set Meta options
- """
- ordering = [
- "full_name",
- ]
-
- #
- # Django methods
- #
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return f"{self.full_name} ({self.short_name})"
-
- #
- # Own methods
- #
- def get_owner_object(self):
- """
- License has no owner information
- """
- return None
-
-
-class RepetitionUnit(models.Model):
- """
- Setting unit, used in combination with an amount such as '10 reps', '5 km'
- """
-
- class Meta:
- """
- Set Meta options
- """
- ordering = [
- "name",
- ]
-
- name = models.CharField(max_length=100, verbose_name=_('Name'))
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.name
-
- #
- # Own methods
- #
- def get_owner_object(self):
- """
- Unit has no owner information
- """
- return None
-
- @property
- def is_repetition(self):
- """
- Checks that the repetition unit is a repetition proper
-
- This is done basically to not litter the code with magic IDs
- """
- return self.id == 1
-
-
-class WeightUnit(models.Model):
- """
- Weight unit, used in combination with an amount such as '10 kg', '5 plates'
- """
-
- class Meta:
- """
- Set Meta options
- """
- ordering = [
- "name",
- ]
-
- name = models.CharField(max_length=100, verbose_name=_('Name'))
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.name
-
- #
- # Own methods
- #
- def get_owner_object(self):
- """
- Unit has no owner information
- """
- return None
-
- @property
- def is_weight(self):
- """
- Checks that the unit is a weight proper
-
- This is done basically to not litter the code with magic IDs
- """
- return self.id in (1, 2)
diff --git a/wger/core/models/rep_unit.py b/wger/core/models/rep_unit.py
new file mode 100644
index 000000000..0e2979799
--- /dev/null
+++ b/wger/core/models/rep_unit.py
@@ -0,0 +1,59 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+
+class RepetitionUnit(models.Model):
+ """
+ Setting unit, used in combination with an amount such as '10 reps', '5 km'
+ """
+
+ class Meta:
+ """
+ Set Meta options
+ """
+ ordering = [
+ "name",
+ ]
+
+ name = models.CharField(max_length=100, verbose_name=_('Name'))
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return self.name
+
+ #
+ # Own methods
+ #
+ def get_owner_object(self):
+ """
+ Unit has no owner information
+ """
+ return None
+
+ @property
+ def is_repetition(self):
+ """
+ Checks that the repetition unit is a repetition proper
+
+ This is done basically to not litter the code with magic IDs
+ """
+ return self.id == 1
diff --git a/wger/core/models/weight_unit.py b/wger/core/models/weight_unit.py
new file mode 100644
index 000000000..44f5e345b
--- /dev/null
+++ b/wger/core/models/weight_unit.py
@@ -0,0 +1,59 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+
+class WeightUnit(models.Model):
+ """
+ Weight unit, used in combination with an amount such as '10 kg', '5 plates'
+ """
+
+ class Meta:
+ """
+ Set Meta options
+ """
+ ordering = [
+ "name",
+ ]
+
+ name = models.CharField(max_length=100, verbose_name=_('Name'))
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return self.name
+
+ #
+ # Own methods
+ #
+ def get_owner_object(self):
+ """
+ Unit has no owner information
+ """
+ return None
+
+ @property
+ def is_weight(self):
+ """
+ Checks that the unit is a weight proper
+
+ This is done basically to not litter the code with magic IDs
+ """
+ return self.id in (1, 2)
diff --git a/wger/exercises/migrations/0001_initial.py b/wger/exercises/migrations/0001_initial.py
index 74429ad4a..616ab8ebe 100644
--- a/wger/exercises/migrations/0001_initial.py
+++ b/wger/exercises/migrations/0001_initial.py
@@ -156,7 +156,7 @@ class Migration(migrations.Migration):
'image',
models.ImageField(
help_text='Only PNG and JPEG formats are supported',
- upload_to=wger.exercises.models.exercise_image_upload_dir,
+ upload_to=wger.exercises.models.image.exercise_image_upload_dir,
verbose_name='Image'
)
),
diff --git a/wger/exercises/models.py b/wger/exercises/models.py
deleted file mode 100644
index e36af11fd..000000000
--- a/wger/exercises/models.py
+++ /dev/null
@@ -1,662 +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
-# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
-
-# Standard Library
-import logging
-import pathlib
-import uuid
-
-# Django
-from django.conf import settings
-from django.contrib.auth.models import User
-from django.contrib.sites.models import Site
-from django.core import mail
-from django.core.validators import MinLengthValidator
-from django.db import models
-from django.template.loader import render_to_string
-from django.templatetags.static import static
-from django.urls import reverse
-from django.utils import translation
-from django.utils.text import slugify
-from django.utils.translation import gettext_lazy as _
-
-# Third Party
-import bleach
-
-# wger
-from wger.core.models import Language
-from wger.utils.cache import (
- delete_template_fragment_cache,
- reset_workout_canonical_form,
-)
-from wger.utils.helpers import smart_capitalize
-from wger.utils.managers import SubmissionManager
-from wger.utils.models import (
- AbstractLicenseModel,
- AbstractSubmissionModel,
-)
-
-
-logger = logging.getLogger(__name__)
-
-
-class Muscle(models.Model):
- """
- Muscle an exercise works out
- """
-
- name = models.CharField(
- max_length=50,
- verbose_name=_('Name'),
- help_text=_('In latin, e.g. "Pectoralis major"'),
- )
-
- # Whether to use the front or the back image for background
- is_front = models.BooleanField(default=1)
-
- # Metaclass to set some other properties
- class Meta:
- ordering = [
- "name",
- ]
-
- # Image to use when displaying this as a main muscle in an exercise
- @property
- def image_url_main(self):
- return static(f"images/muscles/main/muscle-{self.id}.svg")
-
- # Image to use when displaying this as a secondary muscle in an exercise
- @property
- def image_url_secondary(self):
- return static(f"images/muscles/secondary/muscle-{self.id}.svg")
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.name
-
- def get_owner_object(self):
- """
- Muscle has no owner information
- """
- return False
-
-
-class Equipment(models.Model):
- """
- Equipment used or needed by an exercise
- """
-
- name = models.CharField(
- max_length=50,
- verbose_name=_('Name'),
- )
-
- class Meta:
- """
- Set default ordering
- """
- ordering = [
- "name",
- ]
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.name
-
- def get_owner_object(self):
- """
- Equipment has no owner information
- """
- return False
-
-
-class ExerciseCategory(models.Model):
- """
- Model for an exercise category
- """
- name = models.CharField(
- max_length=100,
- verbose_name=_('Name'),
- )
-
- # Metaclass to set some other properties
- class Meta:
- verbose_name_plural = _("Exercise Categories")
- ordering = [
- "name",
- ]
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.name
-
- def get_owner_object(self):
- """
- Category has no owner information
- """
- return False
-
- def save(self, *args, **kwargs):
- """
- Reset all cached infos
- """
-
- super(ExerciseCategory, self).save(*args, **kwargs)
-
- # Cached template fragments
- for language in Language.objects.all():
- delete_template_fragment_cache('exercise-overview', language.id)
-
- def delete(self, *args, **kwargs):
- """
- Reset all cached infos
- """
- for language in Language.objects.all():
- delete_template_fragment_cache('exercise-overview', language.id)
-
- super(ExerciseCategory, self).delete(*args, **kwargs)
-
-
-class Variation(models.Model):
- """
- Variation ids for exercises
- """
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return f'Variation {self.id}'
-
- def get_owner_object(self):
- """
- Variation has no owner information
- """
- return False
-
-
-class ExerciseBase(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
- """
- Model for an exercise base
- """
-
- objects = SubmissionManager()
- """Custom manager"""
-
- uuid = models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='UUID')
- """Globally unique ID, to identify the base across installations"""
-
- category = models.ForeignKey(
- ExerciseCategory,
- verbose_name=_('Category'),
- on_delete=models.CASCADE,
- )
-
- muscles = models.ManyToManyField(
- Muscle,
- blank=True,
- verbose_name=_('Primary muscles'),
- )
- """Main muscles trained by the exercise"""
-
- muscles_secondary = models.ManyToManyField(
- Muscle,
- verbose_name=_('Secondary muscles'),
- related_name='secondary_muscles_base',
- blank=True,
- )
- """Secondary muscles trained by the exercise"""
-
- equipment = models.ManyToManyField(
- Equipment,
- verbose_name=_('Equipment'),
- blank=True,
- )
- """Equipment needed by this exercise"""
-
- variations = models.ForeignKey(
- Variation,
- verbose_name=_('Variations'),
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- )
- """Variations of this exercise"""
-
- #
- # Own methods
- #
-
- @property
- def get_languages(self):
- """
- Returns the languages from the exercises that use this base
- """
- return [exercise.language for exercise in self.exercises.all()]
-
-
-class Exercise(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
- """
- Model for an exercise
- """
-
- objects = SubmissionManager()
- """Custom manager"""
-
- description = models.TextField(
- max_length=2000,
- verbose_name=_('Description'),
- validators=[MinLengthValidator(40)],
- )
- """Description on how to perform the exercise"""
-
- name = models.CharField(max_length=200, verbose_name=_('Name'))
- """The exercise's name, with correct uppercase"""
-
- name_original = models.CharField(
- max_length=200,
- verbose_name=_('Name'),
- default='',
- )
- """The exercise's name, as entered by the user"""
-
- creation_date = models.DateField(
- _('Date'),
- auto_now_add=True,
- null=True,
- blank=True,
- )
- """The submission date"""
-
- language = models.ForeignKey(
- Language,
- verbose_name=_('Language'),
- on_delete=models.CASCADE,
- )
- """The exercise's language"""
-
- uuid = models.UUIDField(
- default=uuid.uuid4,
- editable=False,
- verbose_name='UUID',
- )
- """Globally unique ID, to identify the exercise across installations"""
-
- exercise_base = models.ForeignKey(
- ExerciseBase,
- verbose_name='ExerciseBase',
- on_delete=models.CASCADE,
- default=None,
- null=True,
- related_name='exercises',
- )
- """ Refers to the base exercise with non translated information """
-
- #
- # Django methods
- #
- class Meta:
- base_manager_name = 'objects'
- ordering = [
- "name",
- ]
-
- def get_absolute_url(self):
- """
- Returns the canonical URL to view an exercise
- """
- return reverse('exercise:exercise:view', kwargs={'id': self.id, 'slug': slugify(self.name)})
-
- def save(self, *args, **kwargs):
- """
- Reset all cached infos
- """
- self.name = smart_capitalize(self.name_original)
- super(Exercise, self).save(*args, **kwargs)
-
- # Cached template fragments
- for language in Language.objects.all():
- delete_template_fragment_cache('muscle-overview', language.id)
- delete_template_fragment_cache('exercise-overview', language.id)
- delete_template_fragment_cache('equipment-overview', language.id)
-
- # Cached workouts
- for setting in self.setting_set.all():
- reset_workout_canonical_form(setting.set.exerciseday.training_id)
-
- def delete(self, *args, **kwargs):
- """
- Reset all cached infos
- """
-
- # Cached template fragments
- for language in Language.objects.all():
- delete_template_fragment_cache('muscle-overview', language.id)
- delete_template_fragment_cache('exercise-overview', language.id)
- delete_template_fragment_cache('equipment-overview', language.id)
-
- # Cached workouts
- for setting in self.setting_set.all():
- reset_workout_canonical_form(setting.set.exerciseday.training.pk)
-
- super(Exercise, self).delete(*args, **kwargs)
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.name
-
- #
- # Properties to expose the info from the exercise base
- #
- @property
- def category(self):
- return self.exercise_base.category
-
- @property
- def muscles(self):
- return self.exercise_base.muscles
-
- @property
- def muscles_secondary(self):
- return self.exercise_base.muscles_secondary
-
- @property
- def equipment(self):
- return self.exercise_base.equipment
-
- @property
- def images(self):
- return self.exercise_base.exerciseimage_set
-
- @property
- def variations(self):
- """
- Returns the variations for this exercise in the same language
- """
- out = []
- if self.exercise_base.variations:
- for variation in self.exercise_base.variations.exercisebase_set.all():
- for exercise in variation.exercises.filter(language=self.language).accepted():
- out.append(exercise)
- return out
-
- #
- # Own methods
- #
- @property
- def main_image(self):
- """
- Return the main image for the exercise or None if nothing is found
- """
- return self.images.accepted().filter(is_main=True).first()
-
- @property
- def description_clean(self):
- """
- Return the exercise description with all markup removed
- """
- return bleach.clean(self.description, strip=True)
-
- def get_owner_object(self):
- """
- Exercise has no owner information
- """
- return False
-
- def send_email(self, request):
- """
- Sends an email after being successfully added to the database (for user
- submitted exercises only)
- """
- try:
- user = User.objects.get(username=self.license_author)
- except User.DoesNotExist:
- return
- if self.license_author and user.email:
- translation.activate(user.userprofile.notification_language.short_name)
- url = request.build_absolute_uri(self.get_absolute_url())
- subject = _('Exercise was successfully added to the general database')
- context = {
- 'exercise': self.name,
- 'url': url,
- 'site': Site.objects.get_current().domain,
- }
- message = render_to_string('exercise/email_new.tpl', context)
- mail.send_mail(
- subject,
- message,
- settings.WGER_SETTINGS['EMAIL_FROM'], [user.email],
- fail_silently=True
- )
-
- def set_author(self, request):
- """
- Set author and status
- This is only used when creating exercises (via web or API)
- """
-
- if request.user.has_perm('exercises.add_exercise'):
- self.status = self.STATUS_ACCEPTED
- if not self.license_author:
- self.license_author = request.get_host().split(':')[0]
- else:
- if not self.license_author:
- self.license_author = request.user.username
-
- subject = _('New user submitted exercise')
-
- message = _('The user {0} submitted a new exercise "{1}".'
- ).format(request.user.username, self.name_original)
- mail.mail_admins(
- str(subject),
- str(message),
- fail_silently=True,
- )
-
-
-def exercise_image_upload_dir(instance, filename):
- """
- Returns the upload target for exercise images
- """
- ext = pathlib.Path(filename).suffix
- return "exercise-images/{0}/{1}{2}".format(instance.exercise_base.id, instance.uuid, ext)
-
-
-class ExerciseImage(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
- """
- Model for an exercise image
- """
-
- objects = SubmissionManager()
- """Custom manager"""
-
- uuid = models.UUIDField(
- default=uuid.uuid4,
- editable=False,
- verbose_name='UUID',
- )
- """Globally unique ID, to identify the image across installations"""
-
- exercise_base = models.ForeignKey(
- ExerciseBase,
- verbose_name=_('Exercise'),
- on_delete=models.CASCADE,
- )
- """The exercise the image belongs to"""
-
- image = models.ImageField(
- verbose_name=_('Image'),
- help_text=_('Only PNG and JPEG formats are supported'),
- upload_to=exercise_image_upload_dir,
- )
- """Uploaded image"""
-
- is_main = models.BooleanField(
- verbose_name=_('Main picture'),
- default=False,
- help_text=_(
- "Tick the box if you want to set this image as the "
- "main one for the exercise (will be shown e.g. in "
- "the search). The first image is automatically "
- "marked by the system."
- )
- )
- """A flag indicating whether the image is the exercise's main image"""
-
- class Meta:
- """
- Set default ordering
- """
- ordering = ['-is_main', 'id']
- base_manager_name = 'objects'
-
- def save(self, *args, **kwargs):
- """
- Only one image can be marked as main picture at a time
- """
- if self.is_main:
- ExerciseImage.objects.filter(exercise_base=self.exercise_base).update(is_main=False)
- self.is_main = True
- else:
- if ExerciseImage.objects.accepted()\
- .filter(exercise_base=self.exercise_base).count() == 0 \
- or not ExerciseImage.objects.accepted() \
- .filter(exercise_base=self.exercise_base, is_main=True)\
- .count():
-
- self.is_main = True
-
- #
- # Reset all cached infos
- #
- for language in Language.objects.all():
- delete_template_fragment_cache('muscle-overview', language.id)
- delete_template_fragment_cache('exercise-overview', language.id)
- delete_template_fragment_cache('exercise-overview-mobile', language.id)
- delete_template_fragment_cache('equipment-overview', language.id)
-
- # And go on
- super(ExerciseImage, self).save(*args, **kwargs)
-
- def delete(self, *args, **kwargs):
- """
- Reset all cached infos
- """
- super(ExerciseImage, self).delete(*args, **kwargs)
-
- for language in Language.objects.all():
- delete_template_fragment_cache('muscle-overview', language.id)
- delete_template_fragment_cache('exercise-overview', language.id)
- delete_template_fragment_cache('exercise-overview-mobile', language.id)
- delete_template_fragment_cache('equipment-overview', language.id)
-
- # Make sure there is always a main image
- if not ExerciseImage.objects.accepted() \
- .filter(exercise_base=self.exercise_base, is_main=True).count() \
- and ExerciseImage.objects.accepted() \
- .filter(exercise_base=self.exercise_base) \
- .filter(is_main=False) \
- .count():
-
- image = ExerciseImage.objects.accepted() \
- .filter(exercise_base=self.exercise_base, is_main=False)[0]
- image.is_main = True
- image.save()
-
- def get_owner_object(self):
- """
- Image has no owner information
- """
- return False
-
- def set_author(self, request):
- """
- Set author and status
- This is only used when creating images (via web or API)
- """
- if request.user.has_perm('exercises.add_exerciseimage'):
- self.status = self.STATUS_ACCEPTED
- if not self.license_author:
- self.license_author = request.get_host().split(':')[0]
-
- else:
- if not self.license_author:
- self.license_author = request.user.username
-
- subject = _('New user submitted image')
- message = _('The user {0} submitted a new image "{1}" for exercise {2}.'
- ).format(request.user.username, self.name, self.exercise)
- mail.mail_admins(
- str(subject),
- str(message),
- fail_silently=True,
- )
-
-
-class ExerciseComment(models.Model):
- """
- Model for an exercise comment
- """
- exercise = models.ForeignKey(
- Exercise,
- verbose_name=_('Exercise'),
- editable=False,
- on_delete=models.CASCADE,
- )
- comment = models.CharField(
- max_length=200,
- verbose_name=_('Comment'),
- help_text=_('A comment about how to correctly do this exercise.')
- )
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.comment
-
- def save(self, *args, **kwargs):
- """
- Reset cached workouts
- """
- for setting in self.exercise.setting_set.all():
- reset_workout_canonical_form(setting.set.exerciseday.training_id)
-
- super(ExerciseComment, self).save(*args, **kwargs)
-
- def delete(self, *args, **kwargs):
- """
- Reset cached workouts
- """
- for setting in self.exercise.setting_set.all():
- reset_workout_canonical_form(setting.set.exerciseday.training.pk)
-
- super(ExerciseComment, self).delete(*args, **kwargs)
-
- def get_owner_object(self):
- """
- Comment has no owner information
- """
- return False
diff --git a/wger/exercises/models/__init__.py b/wger/exercises/models/__init__.py
new file mode 100644
index 000000000..490907068
--- /dev/null
+++ b/wger/exercises/models/__init__.py
@@ -0,0 +1,25 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Local
+from .base import ExerciseBase
+from .category import ExerciseCategory
+from .comment import ExerciseComment
+from .equipment import Equipment
+from .exercise import Exercise
+from .image import ExerciseImage
+from .muscle import Muscle
+from .variation import Variation
diff --git a/wger/exercises/models/base.py b/wger/exercises/models/base.py
new file mode 100644
index 000000000..6427f6b63
--- /dev/null
+++ b/wger/exercises/models/base.py
@@ -0,0 +1,95 @@
+# 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 uuid
+
+# Django
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.utils.managers import SubmissionManager
+from wger.utils.models import (
+ AbstractLicenseModel,
+ AbstractSubmissionModel,
+)
+
+# Local
+from .category import ExerciseCategory
+from .equipment import Equipment
+from .muscle import Muscle
+from .variation import Variation
+
+
+class ExerciseBase(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
+ """
+ Model for an exercise base
+ """
+
+ objects = SubmissionManager()
+ """Custom manager"""
+
+ uuid = models.UUIDField(default=uuid.uuid4, editable=False, verbose_name='UUID')
+ """Globally unique ID, to identify the base across installations"""
+
+ category = models.ForeignKey(
+ ExerciseCategory,
+ verbose_name=_('Category'),
+ on_delete=models.CASCADE,
+ )
+
+ muscles = models.ManyToManyField(
+ Muscle,
+ blank=True,
+ verbose_name=_('Primary muscles'),
+ )
+ """Main muscles trained by the exercise"""
+
+ muscles_secondary = models.ManyToManyField(
+ Muscle,
+ verbose_name=_('Secondary muscles'),
+ related_name='secondary_muscles_base',
+ blank=True,
+ )
+ """Secondary muscles trained by the exercise"""
+
+ equipment = models.ManyToManyField(
+ Equipment,
+ verbose_name=_('Equipment'),
+ blank=True,
+ )
+ """Equipment needed by this exercise"""
+
+ variations = models.ForeignKey(
+ Variation,
+ verbose_name=_('Variations'),
+ on_delete=models.CASCADE,
+ null=True,
+ blank=True,
+ )
+ """Variations of this exercise"""
+
+ #
+ # Own methods
+ #
+
+ @property
+ def get_languages(self):
+ """
+ Returns the languages from the exercises that use this base
+ """
+ return [exercise.language for exercise in self.exercises.all()]
diff --git a/wger/exercises/models/category.py b/wger/exercises/models/category.py
new file mode 100644
index 000000000..890c69912
--- /dev/null
+++ b/wger/exercises/models/category.py
@@ -0,0 +1,72 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.core.models import Language
+from wger.utils.cache import delete_template_fragment_cache
+
+
+class ExerciseCategory(models.Model):
+ """
+ Model for an exercise category
+ """
+ name = models.CharField(
+ max_length=100,
+ verbose_name=_('Name'),
+ )
+
+ # Metaclass to set some other properties
+ class Meta:
+ verbose_name_plural = _("Exercise Categories")
+ ordering = [
+ "name",
+ ]
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return self.name
+
+ def get_owner_object(self):
+ """
+ Category has no owner information
+ """
+ return False
+
+ def save(self, *args, **kwargs):
+ """
+ Reset all cached infos
+ """
+
+ super(ExerciseCategory, self).save(*args, **kwargs)
+
+ # Cached template fragments
+ for language in Language.objects.all():
+ delete_template_fragment_cache('exercise-overview', language.id)
+
+ def delete(self, *args, **kwargs):
+ """
+ Reset all cached infos
+ """
+ for language in Language.objects.all():
+ delete_template_fragment_cache('exercise-overview', language.id)
+
+ super(ExerciseCategory, self).delete(*args, **kwargs)
diff --git a/wger/exercises/models/comment.py b/wger/exercises/models/comment.py
new file mode 100644
index 000000000..2fa0179fb
--- /dev/null
+++ b/wger/exercises/models/comment.py
@@ -0,0 +1,72 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.utils.cache import reset_workout_canonical_form
+
+# Local
+from .exercise import Exercise
+
+
+class ExerciseComment(models.Model):
+ """
+ Model for an exercise comment
+ """
+ exercise = models.ForeignKey(
+ Exercise,
+ verbose_name=_('Exercise'),
+ editable=False,
+ on_delete=models.CASCADE,
+ )
+ comment = models.CharField(
+ max_length=200,
+ verbose_name=_('Comment'),
+ help_text=_('A comment about how to correctly do this exercise.')
+ )
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return self.comment
+
+ def save(self, *args, **kwargs):
+ """
+ Reset cached workouts
+ """
+ for setting in self.exercise.setting_set.all():
+ reset_workout_canonical_form(setting.set.exerciseday.training_id)
+
+ super(ExerciseComment, self).save(*args, **kwargs)
+
+ def delete(self, *args, **kwargs):
+ """
+ Reset cached workouts
+ """
+ for setting in self.exercise.setting_set.all():
+ reset_workout_canonical_form(setting.set.exerciseday.training.pk)
+
+ super(ExerciseComment, self).delete(*args, **kwargs)
+
+ def get_owner_object(self):
+ """
+ Comment has no owner information
+ """
+ return False
diff --git a/wger/exercises/models/equipment.py b/wger/exercises/models/equipment.py
new file mode 100644
index 000000000..141457096
--- /dev/null
+++ b/wger/exercises/models/equipment.py
@@ -0,0 +1,50 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+
+class Equipment(models.Model):
+ """
+ Equipment used or needed by an exercise
+ """
+
+ name = models.CharField(
+ max_length=50,
+ verbose_name=_('Name'),
+ )
+
+ class Meta:
+ """
+ Set default ordering
+ """
+ ordering = [
+ "name",
+ ]
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return self.name
+
+ def get_owner_object(self):
+ """
+ Equipment has no owner information
+ """
+ return False
diff --git a/wger/exercises/models/exercise.py b/wger/exercises/models/exercise.py
new file mode 100644
index 000000000..8b3302017
--- /dev/null
+++ b/wger/exercises/models/exercise.py
@@ -0,0 +1,269 @@
+# 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 uuid
+
+# Django
+from django.conf import settings
+from django.contrib.auth.models import User
+from django.contrib.sites.models import Site
+from django.core import mail
+from django.core.validators import MinLengthValidator
+from django.db import models
+from django.template.loader import render_to_string
+from django.urls import reverse
+from django.utils import translation
+from django.utils.text import slugify
+from django.utils.translation import gettext_lazy as _
+
+# Third Party
+import bleach
+
+# wger
+from wger.core.models import Language
+from wger.exercises.models import ExerciseBase
+from wger.utils.cache import (
+ delete_template_fragment_cache,
+ reset_workout_canonical_form,
+)
+from wger.utils.helpers import smart_capitalize
+from wger.utils.managers import SubmissionManager
+from wger.utils.models import (
+ AbstractLicenseModel,
+ AbstractSubmissionModel,
+)
+
+
+class Exercise(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
+ """
+ Model for an exercise
+ """
+
+ objects = SubmissionManager()
+ """Custom manager"""
+
+ description = models.TextField(
+ max_length=2000,
+ verbose_name=_('Description'),
+ validators=[MinLengthValidator(40)],
+ )
+ """Description on how to perform the exercise"""
+
+ name = models.CharField(max_length=200, verbose_name=_('Name'))
+ """The exercise's name, with correct uppercase"""
+
+ name_original = models.CharField(
+ max_length=200,
+ verbose_name=_('Name'),
+ default='',
+ )
+ """The exercise's name, as entered by the user"""
+
+ creation_date = models.DateField(
+ _('Date'),
+ auto_now_add=True,
+ null=True,
+ blank=True,
+ )
+ """The submission date"""
+
+ language = models.ForeignKey(
+ Language,
+ verbose_name=_('Language'),
+ on_delete=models.CASCADE,
+ )
+ """The exercise's language"""
+
+ uuid = models.UUIDField(
+ default=uuid.uuid4,
+ editable=False,
+ verbose_name='UUID',
+ )
+ """Globally unique ID, to identify the exercise across installations"""
+
+ exercise_base = models.ForeignKey(
+ ExerciseBase,
+ verbose_name='ExerciseBase',
+ on_delete=models.CASCADE,
+ default=None,
+ null=True,
+ related_name='exercises',
+ )
+ """ Refers to the base exercise with non translated information """
+
+ #
+ # Django methods
+ #
+ class Meta:
+ base_manager_name = 'objects'
+ ordering = [
+ "name",
+ ]
+
+ def get_absolute_url(self):
+ """
+ Returns the canonical URL to view an exercise
+ """
+ return reverse('exercise:exercise:view', kwargs={'id': self.id, 'slug': slugify(self.name)})
+
+ def save(self, *args, **kwargs):
+ """
+ Reset all cached infos
+ """
+ self.name = smart_capitalize(self.name_original)
+ super(Exercise, self).save(*args, **kwargs)
+
+ # Cached template fragments
+ for language in Language.objects.all():
+ delete_template_fragment_cache('muscle-overview', language.id)
+ delete_template_fragment_cache('exercise-overview', language.id)
+ delete_template_fragment_cache('equipment-overview', language.id)
+
+ # Cached workouts
+ for setting in self.setting_set.all():
+ reset_workout_canonical_form(setting.set.exerciseday.training_id)
+
+ def delete(self, *args, **kwargs):
+ """
+ Reset all cached infos
+ """
+
+ # Cached template fragments
+ for language in Language.objects.all():
+ delete_template_fragment_cache('muscle-overview', language.id)
+ delete_template_fragment_cache('exercise-overview', language.id)
+ delete_template_fragment_cache('equipment-overview', language.id)
+
+ # Cached workouts
+ for setting in self.setting_set.all():
+ reset_workout_canonical_form(setting.set.exerciseday.training.pk)
+
+ super(Exercise, self).delete(*args, **kwargs)
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return self.name
+
+ #
+ # Properties to expose the info from the exercise base
+ #
+ @property
+ def category(self):
+ return self.exercise_base.category
+
+ @property
+ def muscles(self):
+ return self.exercise_base.muscles
+
+ @property
+ def muscles_secondary(self):
+ return self.exercise_base.muscles_secondary
+
+ @property
+ def equipment(self):
+ return self.exercise_base.equipment
+
+ @property
+ def images(self):
+ return self.exercise_base.exerciseimage_set
+
+ @property
+ def variations(self):
+ """
+ Returns the variations for this exercise in the same language
+ """
+ out = []
+ if self.exercise_base.variations:
+ for variation in self.exercise_base.variations.exercisebase_set.all():
+ for exercise in variation.exercises.filter(language=self.language).accepted():
+ out.append(exercise)
+ return out
+
+ #
+ # Own methods
+ #
+ @property
+ def main_image(self):
+ """
+ Return the main image for the exercise or None if nothing is found
+ """
+ return self.images.accepted().filter(is_main=True).first()
+
+ @property
+ def description_clean(self):
+ """
+ Return the exercise description with all markup removed
+ """
+ return bleach.clean(self.description, strip=True)
+
+ def get_owner_object(self):
+ """
+ Exercise has no owner information
+ """
+ return False
+
+ def send_email(self, request):
+ """
+ Sends an email after being successfully added to the database (for user
+ submitted exercises only)
+ """
+ try:
+ user = User.objects.get(username=self.license_author)
+ except User.DoesNotExist:
+ return
+ if self.license_author and user.email:
+ translation.activate(user.userprofile.notification_language.short_name)
+ url = request.build_absolute_uri(self.get_absolute_url())
+ subject = _('Exercise was successfully added to the general database')
+ context = {
+ 'exercise': self.name,
+ 'url': url,
+ 'site': Site.objects.get_current().domain,
+ }
+ message = render_to_string('exercise/email_new.tpl', context)
+ mail.send_mail(
+ subject,
+ message,
+ settings.WGER_SETTINGS['EMAIL_FROM'], [user.email],
+ fail_silently=True
+ )
+
+ def set_author(self, request):
+ """
+ Set author and status
+ This is only used when creating exercises (via web or API)
+ """
+
+ if request.user.has_perm('exercises.add_exercise'):
+ self.status = self.STATUS_ACCEPTED
+ if not self.license_author:
+ self.license_author = request.get_host().split(':')[0]
+ else:
+ if not self.license_author:
+ self.license_author = request.user.username
+
+ subject = _('New user submitted exercise')
+
+ message = _('The user {0} submitted a new exercise "{1}".'
+ ).format(request.user.username, self.name_original)
+ mail.mail_admins(
+ str(subject),
+ str(message),
+ fail_silently=True,
+ )
diff --git a/wger/exercises/models/image.py b/wger/exercises/models/image.py
new file mode 100644
index 000000000..18c4115f2
--- /dev/null
+++ b/wger/exercises/models/image.py
@@ -0,0 +1,173 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Standard Library
+import pathlib
+import uuid
+
+# Django
+from django.core import mail
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.core.models import Language
+from wger.exercises.models import ExerciseBase
+from wger.utils.cache import delete_template_fragment_cache
+from wger.utils.managers import SubmissionManager
+from wger.utils.models import (
+ AbstractLicenseModel,
+ AbstractSubmissionModel,
+)
+
+
+def exercise_image_upload_dir(instance, filename):
+ """
+ Returns the upload target for exercise images
+ """
+ ext = pathlib.Path(filename).suffix
+ return "exercise-images/{0}/{1}{2}".format(instance.exercise_base.id, instance.uuid, ext)
+
+
+class ExerciseImage(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
+ """
+ Model for an exercise image
+ """
+
+ objects = SubmissionManager()
+ """Custom manager"""
+
+ uuid = models.UUIDField(
+ default=uuid.uuid4,
+ editable=False,
+ verbose_name='UUID',
+ )
+ """Globally unique ID, to identify the image across installations"""
+
+ exercise_base = models.ForeignKey(
+ ExerciseBase,
+ verbose_name=_('Exercise'),
+ on_delete=models.CASCADE,
+ )
+ """The exercise the image belongs to"""
+
+ image = models.ImageField(
+ verbose_name=_('Image'),
+ help_text=_('Only PNG and JPEG formats are supported'),
+ upload_to=exercise_image_upload_dir,
+ )
+ """Uploaded image"""
+
+ is_main = models.BooleanField(
+ verbose_name=_('Main picture'),
+ default=False,
+ help_text=_(
+ "Tick the box if you want to set this image as the "
+ "main one for the exercise (will be shown e.g. in "
+ "the search). The first image is automatically "
+ "marked by the system."
+ )
+ )
+ """A flag indicating whether the image is the exercise's main image"""
+
+ class Meta:
+ """
+ Set default ordering
+ """
+ ordering = ['-is_main', 'id']
+ base_manager_name = 'objects'
+
+ def save(self, *args, **kwargs):
+ """
+ Only one image can be marked as main picture at a time
+ """
+ if self.is_main:
+ ExerciseImage.objects.filter(exercise_base=self.exercise_base).update(is_main=False)
+ self.is_main = True
+ else:
+ if ExerciseImage.objects.accepted()\
+ .filter(exercise_base=self.exercise_base).count() == 0 \
+ or not ExerciseImage.objects.accepted() \
+ .filter(exercise_base=self.exercise_base, is_main=True)\
+ .count():
+
+ self.is_main = True
+
+ #
+ # Reset all cached infos
+ #
+ for language in Language.objects.all():
+ delete_template_fragment_cache('muscle-overview', language.id)
+ delete_template_fragment_cache('exercise-overview', language.id)
+ delete_template_fragment_cache('exercise-overview-mobile', language.id)
+ delete_template_fragment_cache('equipment-overview', language.id)
+
+ # And go on
+ super(ExerciseImage, self).save(*args, **kwargs)
+
+ def delete(self, *args, **kwargs):
+ """
+ Reset all cached infos
+ """
+ super(ExerciseImage, self).delete(*args, **kwargs)
+
+ for language in Language.objects.all():
+ delete_template_fragment_cache('muscle-overview', language.id)
+ delete_template_fragment_cache('exercise-overview', language.id)
+ delete_template_fragment_cache('exercise-overview-mobile', language.id)
+ delete_template_fragment_cache('equipment-overview', language.id)
+
+ # Make sure there is always a main image
+ if not ExerciseImage.objects.accepted() \
+ .filter(exercise_base=self.exercise_base, is_main=True).count() \
+ and ExerciseImage.objects.accepted() \
+ .filter(exercise_base=self.exercise_base) \
+ .filter(is_main=False) \
+ .count():
+
+ image = ExerciseImage.objects.accepted() \
+ .filter(exercise_base=self.exercise_base, is_main=False)[0]
+ image.is_main = True
+ image.save()
+
+ def get_owner_object(self):
+ """
+ Image has no owner information
+ """
+ return False
+
+ def set_author(self, request):
+ """
+ Set author and status
+ This is only used when creating images (via web or API)
+ """
+ if request.user.has_perm('exercises.add_exerciseimage'):
+ self.status = self.STATUS_ACCEPTED
+ if not self.license_author:
+ self.license_author = request.get_host().split(':')[0]
+
+ else:
+ if not self.license_author:
+ self.license_author = request.user.username
+
+ subject = _('New user submitted image')
+ message = _('The user {0} submitted a new image "{1}" for exercise {2}.'
+ ).format(request.user.username, self.name, self.exercise)
+ mail.mail_admins(
+ str(subject),
+ str(message),
+ fail_silently=True,
+ )
diff --git a/wger/exercises/models/muscle.py b/wger/exercises/models/muscle.py
new file mode 100644
index 000000000..c15b02378
--- /dev/null
+++ b/wger/exercises/models/muscle.py
@@ -0,0 +1,68 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Standard Library
+import logging
+
+# Django
+from django.db import models
+from django.templatetags.static import static
+from django.utils.translation import gettext_lazy as _
+
+logger = logging.getLogger(__name__)
+
+
+class Muscle(models.Model):
+ """
+ Muscle an exercise works out
+ """
+
+ name = models.CharField(
+ max_length=50,
+ verbose_name=_('Name'),
+ help_text=_('In latin, e.g. "Pectoralis major"'),
+ )
+
+ # Whether to use the front or the back image for background
+ is_front = models.BooleanField(default=1)
+
+ # Metaclass to set some other properties
+ class Meta:
+ ordering = [
+ "name",
+ ]
+
+ # Image to use when displaying this as a main muscle in an exercise
+ @property
+ def image_url_main(self):
+ return static(f"images/muscles/main/muscle-{self.id}.svg")
+
+ # Image to use when displaying this as a secondary muscle in an exercise
+ @property
+ def image_url_secondary(self):
+ return static(f"images/muscles/secondary/muscle-{self.id}.svg")
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return self.name
+
+ def get_owner_object(self):
+ """
+ Muscle has no owner information
+ """
+ return False
diff --git a/wger/exercises/models/variation.py b/wger/exercises/models/variation.py
new file mode 100644
index 000000000..1c302b99a
--- /dev/null
+++ b/wger/exercises/models/variation.py
@@ -0,0 +1,36 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.db import models
+
+
+class Variation(models.Model):
+ """
+ Variation ids for exercises
+ """
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return f'Variation {self.id}'
+
+ def get_owner_object(self):
+ """
+ Variation has no owner information
+ """
+ return False
diff --git a/wger/gallery/views/images.py b/wger/gallery/views/images.py
index b8b7be6b2..7a489cd47 100644
--- a/wger/gallery/views/images.py
+++ b/wger/gallery/views/images.py
@@ -25,10 +25,7 @@ from django.urls import (
reverse,
reverse_lazy,
)
-from django.utils.translation import (
- gettext_lazy,
- gettext_lazy as _,
-)
+from django.utils.translation import gettext_lazy as _
from django.views.generic import (
CreateView,
DeleteView,
diff --git a/wger/gym/migrations/0001_initial.py b/wger/gym/migrations/0001_initial.py
index 98f213367..18abb98cb 100644
--- a/wger/gym/migrations/0001_initial.py
+++ b/wger/gym/migrations/0001_initial.py
@@ -197,7 +197,8 @@ class Migration(migrations.Migration):
(
'document',
models.FileField(
- upload_to=wger.gym.models.gym_document_upload_dir, verbose_name='Document'
+ upload_to=wger.gym.models.user_document.gym_document_upload_dir,
+ verbose_name='Document'
)
),
('original_name', models.CharField(max_length=128, editable=False)),
diff --git a/wger/gym/models.py b/wger/gym/models.py
deleted file mode 100644
index 62209bebc..000000000
--- a/wger/gym/models.py
+++ /dev/null
@@ -1,703 +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 uuid
-
-# Django
-from django.contrib.auth.models import User
-from django.db import models as m
-from django.urls import reverse
-from django.utils.translation import (
- gettext,
- gettext_lazy as _,
-)
-
-# wger
-from wger.gym.managers import GymManager
-
-
-class Gym(m.Model):
- """
- Model for a gym
- """
-
- class Meta:
- permissions = (
- ("gym_trainer", _("Trainer: can see the users for a gym")),
- ("manage_gym", _("Admin: can manage users for a gym")),
- ("manage_gyms", _("Admin: can administrate the different gyms")),
- )
- ordering = [
- "name",
- ]
-
- objects = GymManager()
- """
- Custom Gym Query Manager
- """
-
- name = m.CharField(max_length=60, verbose_name=_('Name'))
- """Gym name"""
-
- phone = m.CharField(
- verbose_name=_('Phone'),
- max_length=20,
- blank=True,
- null=True,
- )
- """Phone number"""
-
- email = m.EmailField(
- verbose_name=_('Email'),
- blank=True,
- null=True,
- )
- """Email"""
-
- owner = m.CharField(
- verbose_name=_('Owner'),
- max_length=100,
- blank=True,
- null=True,
- )
- """Gym owner"""
-
- zip_code = m.CharField(
- _('ZIP code'),
- max_length=10,
- blank=True,
- null=True,
- )
- """ZIP code"""
-
- city = m.CharField(
- _('City'),
- max_length=30,
- blank=True,
- null=True,
- )
- """City"""
-
- street = m.CharField(
- _('Street'),
- max_length=30,
- blank=True,
- null=True,
- )
- """Street"""
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.name
-
- def get_absolute_url(self):
- """
- Return the URL for this object
- """
- return reverse('gym:gym:user-list', kwargs={'pk': self.pk})
-
- def get_owner_object(self):
- """
- Gym has no owner information
- """
- return None
-
-
-class GymConfig(m.Model):
- """
- Configuration options for a gym
- """
-
- gym = m.OneToOneField(
- Gym,
- related_name='config',
- editable=False,
- on_delete=m.CASCADE,
- )
- """
- Gym this configuration belongs to
- """
-
- weeks_inactive = m.PositiveIntegerField(
- verbose_name=_('Reminder of inactive members'),
- help_text=_(
- 'Number of weeks since the last time a '
- 'user logged his presence to be considered inactive'
- ),
- default=4
- )
- """
- Reminder of inactive members
- """
-
- show_name = m.BooleanField(
- verbose_name=_('Show name in header'),
- help_text=_('Show the name of the gym in the site header'),
- default=False,
- )
- """
- Show name of the current user's gym in the header, instead of 'wger'
- """
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return gettext('Configuration for {}'.format(self.gym.name))
-
- def get_owner_object(self):
- """
- Config has no user owner
- """
- return None
-
-
-class AbstractGymUserConfigModel(m.Model):
- """
- Abstract class for member and admin gym configuration models
- """
-
- class Meta:
- abstract = True
-
- gym = m.ForeignKey(
- Gym,
- editable=False,
- on_delete=m.CASCADE,
- )
- """
- Gym this configuration belongs to
- """
-
- user = m.OneToOneField(
- User,
- editable=False,
- on_delete=m.CASCADE,
- )
- """
- User this configuration belongs to
- """
-
-
-class GymAdminConfig(AbstractGymUserConfigModel, m.Model):
- """
- Administrator/trainer configuration options for a specific gym
- """
-
- class Meta:
- unique_together = ('gym', 'user')
- """
- Only one entry per user and gym
- """
-
- overview_inactive = m.BooleanField(
- verbose_name=_('Overview of inactive members'),
- help_text=_('Receive email overviews of inactive members'),
- default=True,
- )
- """
- Reminder of inactive members
- """
-
- def get_owner_object(self):
- """
- Returns the object that has owner information
- """
- return self
-
-
-class GymUserConfig(AbstractGymUserConfigModel, m.Model):
- """
- Gym member configuration options for a specific gym
- """
-
- class Meta:
- unique_together = ('gym', 'user')
- """
- Only one entry per user and gym
- """
-
- include_inactive = m.BooleanField(
- verbose_name=_('Include in inactive overview'),
- help_text=_('Include this user in the email list with '
- 'inactive members'),
- default=True,
- )
- """
- Include user in inactive overview
- """
-
- def get_owner_object(self):
- """
- While the model has a user foreign key, this is editable by all
- trainers in the gym.
- """
- return None
-
-
-class AdminUserNote(m.Model):
- """
- Administrator notes about a member
- """
-
- class Meta:
- """
- Order by time
- """
- ordering = [
- "-timestamp_created",
- ]
-
- user = m.ForeignKey(
- User,
- editable=False,
- related_name='adminusernote_user',
- on_delete=m.CASCADE,
- )
- """
- User this note belongs to
- """
-
- member = m.ForeignKey(
- User,
- editable=False,
- related_name='adminusernote_member',
- on_delete=m.CASCADE,
- )
- """
- Gym member this note refers to
- """
-
- timestamp_created = m.DateTimeField(auto_now_add=True)
- """
- Time when this note was created
- """
-
- timestamp_edited = m.DateTimeField(auto_now=True)
- """
- Last time when this note was edited
- """
-
- note = m.TextField(verbose_name=_('Note'))
- """
- Actual note
- """
-
- def get_owner_object(self):
- """
- While the model has a user foreign key, this is editable by all
- trainers in the gym.
- """
- return None
-
-
-def gym_document_upload_dir(instance, filename):
- """
- Returns the upload target for documents
- """
- return "gym/documents/{0}/{1}/{2}".format(
- instance.member.userprofile.gym.id,
- instance.member.id,
- uuid.uuid4(),
- )
-
-
-class UserDocument(m.Model):
- """
- Model for a document
- """
-
- class Meta:
- """
- Order by time
- """
- ordering = [
- "-timestamp_created",
- ]
-
- user = m.ForeignKey(User, editable=False, related_name='userdocument_user', on_delete=m.CASCADE)
- """
- User this note belongs to
- """
-
- member = m.ForeignKey(
- User,
- editable=False,
- related_name='userdocument_member',
- on_delete=m.CASCADE,
- )
- """
- Gym member this note refers to
- """
-
- timestamp_created = m.DateTimeField(auto_now_add=True)
- """
- Time when this document was created
- """
-
- timestamp_edited = m.DateTimeField(auto_now=True)
- """
- Last time when this document was edited
- """
-
- document = m.FileField(verbose_name=_('Document'), upload_to=gym_document_upload_dir)
- """
- Uploaded document
- """
-
- original_name = m.CharField(max_length=128, editable=False)
- """
- Original document name when uploaded
- """
-
- name = m.CharField(
- max_length=60,
- verbose_name=_('Name'),
- help_text=_('Will use file name if nothing provided'),
- blank=True,
- )
- """
- Name or description
- """
-
- note = m.TextField(
- verbose_name=_('Note'),
- blank=True,
- null=True,
- )
- """
- Note with additional information
- """
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- if self.name != self.original_name:
- return "{} ({})".format(self.name, self.original_name)
- else:
- return "{}".format(self.name)
-
- def get_owner_object(self):
- """
- While the model has a user foreign key, this is editable by all
- trainers in the gym.
- """
- return None
-
-
-class ContractType(m.Model):
- """
- Model for a contract's type
-
- A contract type is a user-editable way of enhancing the contract to
- specify types, such as e.g. 'with personal trainer', 'regular', etc.
- """
-
- class Meta:
- """
- Order by name
- """
- ordering = [
- "name",
- ]
-
- gym = m.ForeignKey(Gym, editable=False, on_delete=m.CASCADE)
- """
- The gym this contract type belongs to
- """
-
- name = m.CharField(verbose_name=_('Name'), max_length=25)
- """
- The contract type's short name
- """
-
- description = m.TextField(
- verbose_name=_('Description'),
- blank=True,
- null=True,
- )
- """
- Free text field for additional information
- """
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return "{}".format(self.name)
-
- def get_owner_object(self):
- """
- Contract type has no owner information
- """
- return None
-
-
-class ContractOption(m.Model):
- """
- Model for a contract Option
-
- A contract option is a user-editable way of enhancing the contract to
- specify options, such as e.g. 'cash', 'bank withdrawal', etc. The
- difference with a contract type is that a contract can only be of one
- type but can have different options.
- """
-
- class Meta:
- """
- Order by name
- """
- ordering = [
- "name",
- ]
-
- gym = m.ForeignKey(Gym, editable=False, on_delete=m.CASCADE)
- """
- The gym this contract option belongs to
- """
-
- name = m.CharField(verbose_name=_('Name'), max_length=25)
- """
- The contract options short name
- """
-
- description = m.TextField(
- verbose_name=_('Description'),
- blank=True,
- null=True,
- )
- """
- Free text field for additional information
- """
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return "{}".format(self.name)
-
- def get_owner_object(self):
- """
- Contract type has no owner information
- """
- return None
-
-
-class Contract(m.Model):
- """
- Model for a member's contract in a gym
- """
-
- AMOUNT_TYPE_YEARLY = '1'
- AMOUNT_TYPE_HALFYEARLY = '2'
- AMOUNT_TYPE_MONTHLY = '3'
- AMOUNT_TYPE_BIWEEKLY = '4'
- AMOUNT_TYPE_WEEKLY = '5'
- AMOUNT_TYPE_DAILY = '6'
-
- AMOUNT_TYPE = (
- (AMOUNT_TYPE_YEARLY, _("Yearly")),
- (AMOUNT_TYPE_HALFYEARLY, _('Half yearly')),
- (AMOUNT_TYPE_MONTHLY, _('Monthly')),
- (AMOUNT_TYPE_BIWEEKLY, _('Biweekly')),
- (AMOUNT_TYPE_WEEKLY, _('Weekly')),
- (AMOUNT_TYPE_DAILY, _('Daily')),
- )
-
- class Meta:
- """
- Order by time
- """
- ordering = [
- "-date_start",
- ]
-
- user = m.ForeignKey(
- User,
- editable=False,
- related_name='contract_user',
- on_delete=m.CASCADE,
- )
- """
- User that originally created the contract
- """
-
- member = m.ForeignKey(
- User,
- editable=False,
- related_name='contract_member',
- on_delete=m.CASCADE,
- )
- """
- Gym member this contract refers to
- """
-
- timestamp_created = m.DateTimeField(auto_now_add=True)
- """
- Time when the contract was created
- """
-
- timestamp_edited = m.DateTimeField(auto_now=True)
- """
- Last time when the contract was edited
- """
-
- contract_type = m.ForeignKey(
- ContractType,
- blank=True,
- null=True,
- verbose_name=_('Contract type'),
- on_delete=m.CASCADE,
- )
- """
- Optional type of contract
- """
-
- options = m.ManyToManyField(
- ContractOption,
- verbose_name=_('Options'),
- blank=True,
- )
- """
- Options for the contract
- """
-
- amount = m.DecimalField(
- verbose_name=_('Amount'),
- decimal_places=2,
- max_digits=12,
- default=0,
- )
- """
- The amount to pay
- """
-
- payment = m.CharField(
- verbose_name=_('Payment type'),
- max_length=2,
- choices=AMOUNT_TYPE,
- default=AMOUNT_TYPE_MONTHLY,
- help_text=_('How often the amount will be charged to the member')
- )
- """
- How often the amount will be charged to the member
- """
-
- is_active = m.BooleanField(verbose_name=_('Contract is active'), default=True)
- """
- Flag showing whether the contract is currently active
- """
-
- date_start = m.DateField(
- verbose_name=_('Start date'),
- default=datetime.date.today,
- blank=True,
- null=True,
- )
- """
- The date when the contract starts
- """
-
- date_end = m.DateField(
- verbose_name=_('End date'),
- blank=True,
- null=True,
- )
- """
- The date when the contract ends
- """
-
- email = m.EmailField(
- verbose_name=_('Email'),
- blank=True,
- null=True,
- )
- """The member's email"""
-
- zip_code = m.CharField(
- _('ZIP code'),
- max_length=10,
- blank=True,
- null=True,
- )
- """ZIP code"""
-
- city = m.CharField(
- _('City'),
- max_length=30,
- blank=True,
- null=True,
- )
- """City"""
-
- street = m.CharField(
- _('Street'),
- max_length=30,
- blank=True,
- null=True,
- )
- """Street"""
-
- phone = m.CharField(
- verbose_name=_('Phone'),
- max_length=20,
- blank=True,
- null=True,
- )
- """Phone number"""
-
- profession = m.CharField(
- verbose_name=_('Profession'),
- max_length=50,
- blank=True,
- null=True,
- )
- """
- The member's profession
- """
-
- note = m.TextField(
- verbose_name=_('Note'),
- blank=True,
- null=True,
- )
- """
- Free text note with additional information
- """
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return "#{}".format(self.id)
-
- def get_absolute_url(self):
- """
- Return the URL for this object
- """
- return reverse('gym:contract:view', kwargs={'pk': self.pk})
-
- def get_owner_object(self):
- """
- While the model has a user foreign key, this is editable by all
- managers in the gym.
- """
- return None
diff --git a/wger/gym/models/__init__.py b/wger/gym/models/__init__.py
new file mode 100644
index 000000000..0e0f63ab3
--- /dev/null
+++ b/wger/gym/models/__init__.py
@@ -0,0 +1,30 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Local
+from .admin_user_note import AdminUserNote
+from .contract import (
+ Contract,
+ ContractOption,
+ ContractType,
+)
+from .gym import Gym
+from .gym_config import GymConfig
+from .user_config import (
+ GymAdminConfig,
+ GymUserConfig,
+)
+from .user_document import UserDocument
diff --git a/wger/gym/models/admin_user_note.py b/wger/gym/models/admin_user_note.py
new file mode 100644
index 000000000..dd60bdd75
--- /dev/null
+++ b/wger/gym/models/admin_user_note.py
@@ -0,0 +1,76 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.contrib.auth.models import User
+from django.db import models as m
+from django.utils.translation import gettext_lazy as _
+
+
+class AdminUserNote(m.Model):
+ """
+ Administrator notes about a member
+ """
+
+ class Meta:
+ """
+ Order by time
+ """
+ ordering = [
+ "-timestamp_created",
+ ]
+
+ user = m.ForeignKey(
+ User,
+ editable=False,
+ related_name='adminusernote_user',
+ on_delete=m.CASCADE,
+ )
+ """
+ User this note belongs to
+ """
+
+ member = m.ForeignKey(
+ User,
+ editable=False,
+ related_name='adminusernote_member',
+ on_delete=m.CASCADE,
+ )
+ """
+ Gym member this note refers to
+ """
+
+ timestamp_created = m.DateTimeField(auto_now_add=True)
+ """
+ Time when this note was created
+ """
+
+ timestamp_edited = m.DateTimeField(auto_now=True)
+ """
+ Last time when this note was edited
+ """
+
+ note = m.TextField(verbose_name=_('Note'))
+ """
+ Actual note
+ """
+
+ def get_owner_object(self):
+ """
+ While the model has a user foreign key, this is editable by all
+ trainers in the gym.
+ """
+ return None
diff --git a/wger/gym/models/contract.py b/wger/gym/models/contract.py
new file mode 100644
index 000000000..37ee3df7f
--- /dev/null
+++ b/wger/gym/models/contract.py
@@ -0,0 +1,327 @@
+# 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 as m
+from django.urls import reverse
+from django.utils.translation import gettext_lazy as _
+
+# Local
+from .gym import Gym
+
+
+class ContractType(m.Model):
+ """
+ Model for a contract's type
+
+ A contract type is a user-editable way of enhancing the contract to
+ specify types, such as e.g. 'with personal trainer', 'regular', etc.
+ """
+
+ class Meta:
+ """
+ Order by name
+ """
+ ordering = [
+ "name",
+ ]
+
+ gym = m.ForeignKey(Gym, editable=False, on_delete=m.CASCADE)
+ """
+ The gym this contract type belongs to
+ """
+
+ name = m.CharField(verbose_name=_('Name'), max_length=25)
+ """
+ The contract type's short name
+ """
+
+ description = m.TextField(
+ verbose_name=_('Description'),
+ blank=True,
+ null=True,
+ )
+ """
+ Free text field for additional information
+ """
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return "{}".format(self.name)
+
+ def get_owner_object(self):
+ """
+ Contract type has no owner information
+ """
+ return None
+
+
+class ContractOption(m.Model):
+ """
+ Model for a contract Option
+
+ A contract option is a user-editable way of enhancing the contract to
+ specify options, such as e.g. 'cash', 'bank withdrawal', etc. The
+ difference with a contract type is that a contract can only be of one
+ type but can have different options.
+ """
+
+ class Meta:
+ """
+ Order by name
+ """
+ ordering = [
+ "name",
+ ]
+
+ gym = m.ForeignKey(Gym, editable=False, on_delete=m.CASCADE)
+ """
+ The gym this contract option belongs to
+ """
+
+ name = m.CharField(verbose_name=_('Name'), max_length=25)
+ """
+ The contract options short name
+ """
+
+ description = m.TextField(
+ verbose_name=_('Description'),
+ blank=True,
+ null=True,
+ )
+ """
+ Free text field for additional information
+ """
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return "{}".format(self.name)
+
+ def get_owner_object(self):
+ """
+ Contract type has no owner information
+ """
+ return None
+
+
+class Contract(m.Model):
+ """
+ Model for a member's contract in a gym
+ """
+
+ AMOUNT_TYPE_YEARLY = '1'
+ AMOUNT_TYPE_HALFYEARLY = '2'
+ AMOUNT_TYPE_MONTHLY = '3'
+ AMOUNT_TYPE_BIWEEKLY = '4'
+ AMOUNT_TYPE_WEEKLY = '5'
+ AMOUNT_TYPE_DAILY = '6'
+
+ AMOUNT_TYPE = (
+ (AMOUNT_TYPE_YEARLY, _("Yearly")),
+ (AMOUNT_TYPE_HALFYEARLY, _('Half yearly')),
+ (AMOUNT_TYPE_MONTHLY, _('Monthly')),
+ (AMOUNT_TYPE_BIWEEKLY, _('Biweekly')),
+ (AMOUNT_TYPE_WEEKLY, _('Weekly')),
+ (AMOUNT_TYPE_DAILY, _('Daily')),
+ )
+
+ class Meta:
+ """
+ Order by time
+ """
+ ordering = [
+ "-date_start",
+ ]
+
+ user = m.ForeignKey(
+ User,
+ editable=False,
+ related_name='contract_user',
+ on_delete=m.CASCADE,
+ )
+ """
+ User that originally created the contract
+ """
+
+ member = m.ForeignKey(
+ User,
+ editable=False,
+ related_name='contract_member',
+ on_delete=m.CASCADE,
+ )
+ """
+ Gym member this contract refers to
+ """
+
+ timestamp_created = m.DateTimeField(auto_now_add=True)
+ """
+ Time when the contract was created
+ """
+
+ timestamp_edited = m.DateTimeField(auto_now=True)
+ """
+ Last time when the contract was edited
+ """
+
+ contract_type = m.ForeignKey(
+ ContractType,
+ blank=True,
+ null=True,
+ verbose_name=_('Contract type'),
+ on_delete=m.CASCADE,
+ )
+ """
+ Optional type of contract
+ """
+
+ options = m.ManyToManyField(
+ ContractOption,
+ verbose_name=_('Options'),
+ blank=True,
+ )
+ """
+ Options for the contract
+ """
+
+ amount = m.DecimalField(
+ verbose_name=_('Amount'),
+ decimal_places=2,
+ max_digits=12,
+ default=0,
+ )
+ """
+ The amount to pay
+ """
+
+ payment = m.CharField(
+ verbose_name=_('Payment type'),
+ max_length=2,
+ choices=AMOUNT_TYPE,
+ default=AMOUNT_TYPE_MONTHLY,
+ help_text=_('How often the amount will be charged to the member')
+ )
+ """
+ How often the amount will be charged to the member
+ """
+
+ is_active = m.BooleanField(verbose_name=_('Contract is active'), default=True)
+ """
+ Flag showing whether the contract is currently active
+ """
+
+ date_start = m.DateField(
+ verbose_name=_('Start date'),
+ default=datetime.date.today,
+ blank=True,
+ null=True,
+ )
+ """
+ The date when the contract starts
+ """
+
+ date_end = m.DateField(
+ verbose_name=_('End date'),
+ blank=True,
+ null=True,
+ )
+ """
+ The date when the contract ends
+ """
+
+ email = m.EmailField(
+ verbose_name=_('Email'),
+ blank=True,
+ null=True,
+ )
+ """The member's email"""
+
+ zip_code = m.CharField(
+ _('ZIP code'),
+ max_length=10,
+ blank=True,
+ null=True,
+ )
+ """ZIP code"""
+
+ city = m.CharField(
+ _('City'),
+ max_length=30,
+ blank=True,
+ null=True,
+ )
+ """City"""
+
+ street = m.CharField(
+ _('Street'),
+ max_length=30,
+ blank=True,
+ null=True,
+ )
+ """Street"""
+
+ phone = m.CharField(
+ verbose_name=_('Phone'),
+ max_length=20,
+ blank=True,
+ null=True,
+ )
+ """Phone number"""
+
+ profession = m.CharField(
+ verbose_name=_('Profession'),
+ max_length=50,
+ blank=True,
+ null=True,
+ )
+ """
+ The member's profession
+ """
+
+ note = m.TextField(
+ verbose_name=_('Note'),
+ blank=True,
+ null=True,
+ )
+ """
+ Free text note with additional information
+ """
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return "#{}".format(self.id)
+
+ def get_absolute_url(self):
+ """
+ Return the URL for this object
+ """
+ return reverse('gym:contract:view', kwargs={'pk': self.pk})
+
+ def get_owner_object(self):
+ """
+ While the model has a user foreign key, this is editable by all
+ managers in the gym.
+ """
+ return None
diff --git a/wger/gym/models/gym.py b/wger/gym/models/gym.py
new file mode 100644
index 000000000..cf95e92da
--- /dev/null
+++ b/wger/gym/models/gym.py
@@ -0,0 +1,112 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.db import models as m
+from django.urls import reverse
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.gym.managers import GymManager
+
+
+class Gym(m.Model):
+ """
+ Model for a gym
+ """
+
+ class Meta:
+ permissions = (
+ ("gym_trainer", _("Trainer: can see the users for a gym")),
+ ("manage_gym", _("Admin: can manage users for a gym")),
+ ("manage_gyms", _("Admin: can administrate the different gyms")),
+ )
+ ordering = [
+ "name",
+ ]
+
+ objects = GymManager()
+ """
+ Custom Gym Query Manager
+ """
+
+ name = m.CharField(max_length=60, verbose_name=_('Name'))
+ """Gym name"""
+
+ phone = m.CharField(
+ verbose_name=_('Phone'),
+ max_length=20,
+ blank=True,
+ null=True,
+ )
+ """Phone number"""
+
+ email = m.EmailField(
+ verbose_name=_('Email'),
+ blank=True,
+ null=True,
+ )
+ """Email"""
+
+ owner = m.CharField(
+ verbose_name=_('Owner'),
+ max_length=100,
+ blank=True,
+ null=True,
+ )
+ """Gym owner"""
+
+ zip_code = m.CharField(
+ _('ZIP code'),
+ max_length=10,
+ blank=True,
+ null=True,
+ )
+ """ZIP code"""
+
+ city = m.CharField(
+ _('City'),
+ max_length=30,
+ blank=True,
+ null=True,
+ )
+ """City"""
+
+ street = m.CharField(
+ _('Street'),
+ max_length=30,
+ blank=True,
+ null=True,
+ )
+ """Street"""
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return self.name
+
+ def get_absolute_url(self):
+ """
+ Return the URL for this object
+ """
+ return reverse('gym:gym:user-list', kwargs={'pk': self.pk})
+
+ def get_owner_object(self):
+ """
+ Gym has no owner information
+ """
+ return None
diff --git a/wger/gym/models/gym_config.py b/wger/gym/models/gym_config.py
new file mode 100644
index 000000000..333c9f5a4
--- /dev/null
+++ b/wger/gym/models/gym_config.py
@@ -0,0 +1,74 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.db import models as m
+from django.utils.translation import (
+ gettext,
+ gettext_lazy as _,
+)
+
+# wger
+from wger.gym.models import Gym
+
+
+class GymConfig(m.Model):
+ """
+ Configuration options for a gym
+ """
+
+ gym = m.OneToOneField(
+ Gym,
+ related_name='config',
+ editable=False,
+ on_delete=m.CASCADE,
+ )
+ """
+ Gym this configuration belongs to
+ """
+
+ weeks_inactive = m.PositiveIntegerField(
+ verbose_name=_('Reminder of inactive members'),
+ help_text=_(
+ 'Number of weeks since the last time a '
+ 'user logged his presence to be considered inactive'
+ ),
+ default=4
+ )
+ """
+ Reminder of inactive members
+ """
+
+ show_name = m.BooleanField(
+ verbose_name=_('Show name in header'),
+ help_text=_('Show the name of the gym in the site header'),
+ default=False,
+ )
+ """
+ Show name of the current user's gym in the header, instead of 'wger'
+ """
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return gettext('Configuration for {}'.format(self.gym.name))
+
+ def get_owner_object(self):
+ """
+ Config has no user owner
+ """
+ return None
diff --git a/wger/gym/models/user_config.py b/wger/gym/models/user_config.py
new file mode 100644
index 000000000..850b46fde
--- /dev/null
+++ b/wger/gym/models/user_config.py
@@ -0,0 +1,106 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.contrib.auth.models import User
+from django.db import models as m
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.gym.models import Gym
+
+
+class AbstractGymUserConfigModel(m.Model):
+ """
+ Abstract class for member and admin gym configuration models
+ """
+
+ class Meta:
+ abstract = True
+
+ gym = m.ForeignKey(
+ Gym,
+ editable=False,
+ on_delete=m.CASCADE,
+ )
+ """
+ Gym this configuration belongs to
+ """
+
+ user = m.OneToOneField(
+ User,
+ editable=False,
+ on_delete=m.CASCADE,
+ )
+ """
+ User this configuration belongs to
+ """
+
+
+class GymAdminConfig(AbstractGymUserConfigModel, m.Model):
+ """
+ Administrator/trainer configuration options for a specific gym
+ """
+
+ class Meta:
+ unique_together = ('gym', 'user')
+ """
+ Only one entry per user and gym
+ """
+
+ overview_inactive = m.BooleanField(
+ verbose_name=_('Overview of inactive members'),
+ help_text=_('Receive email overviews of inactive members'),
+ default=True,
+ )
+ """
+ Reminder of inactive members
+ """
+
+ def get_owner_object(self):
+ """
+ Returns the object that has owner information
+ """
+ return self
+
+
+class GymUserConfig(AbstractGymUserConfigModel, m.Model):
+ """
+ Gym member configuration options for a specific gym
+ """
+
+ class Meta:
+ unique_together = ('gym', 'user')
+ """
+ Only one entry per user and gym
+ """
+
+ include_inactive = m.BooleanField(
+ verbose_name=_('Include in inactive overview'),
+ help_text=_('Include this user in the email list with '
+ 'inactive members'),
+ default=True,
+ )
+ """
+ Include user in inactive overview
+ """
+
+ def get_owner_object(self):
+ """
+ While the model has a user foreign key, this is editable by all
+ trainers in the gym.
+ """
+ return None
diff --git a/wger/gym/models/user_document.py b/wger/gym/models/user_document.py
new file mode 100644
index 000000000..9383d0ad3
--- /dev/null
+++ b/wger/gym/models/user_document.py
@@ -0,0 +1,118 @@
+# 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 uuid
+
+# Django
+from django.contrib.auth.models import User
+from django.db import models as m
+from django.utils.translation import gettext_lazy as _
+
+
+def gym_document_upload_dir(instance, filename):
+ """
+ Returns the upload target for documents
+ """
+ return "gym/documents/{0}/{1}/{2}".format(
+ instance.member.userprofile.gym.id,
+ instance.member.id,
+ uuid.uuid4(),
+ )
+
+
+class UserDocument(m.Model):
+ """
+ Model for a document
+ """
+
+ class Meta:
+ """
+ Order by time
+ """
+ ordering = [
+ "-timestamp_created",
+ ]
+
+ user = m.ForeignKey(User, editable=False, related_name='userdocument_user', on_delete=m.CASCADE)
+ """
+ User this note belongs to
+ """
+
+ member = m.ForeignKey(
+ User,
+ editable=False,
+ related_name='userdocument_member',
+ on_delete=m.CASCADE,
+ )
+ """
+ Gym member this note refers to
+ """
+
+ timestamp_created = m.DateTimeField(auto_now_add=True)
+ """
+ Time when this document was created
+ """
+
+ timestamp_edited = m.DateTimeField(auto_now=True)
+ """
+ Last time when this document was edited
+ """
+
+ document = m.FileField(verbose_name=_('Document'), upload_to=gym_document_upload_dir)
+ """
+ Uploaded document
+ """
+
+ original_name = m.CharField(max_length=128, editable=False)
+ """
+ Original document name when uploaded
+ """
+
+ name = m.CharField(
+ max_length=60,
+ verbose_name=_('Name'),
+ help_text=_('Will use file name if nothing provided'),
+ blank=True,
+ )
+ """
+ Name or description
+ """
+
+ note = m.TextField(
+ verbose_name=_('Note'),
+ blank=True,
+ null=True,
+ )
+ """
+ Note with additional information
+ """
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ if self.name != self.original_name:
+ return "{} ({})".format(self.name, self.original_name)
+ else:
+ return "{}".format(self.name)
+
+ def get_owner_object(self):
+ """
+ While the model has a user foreign key, this is editable by all
+ trainers in the gym.
+ """
+ return None
diff --git a/wger/mailer/models.py b/wger/mailer/models.py
deleted file mode 100644
index 850ec3870..000000000
--- a/wger/mailer/models.py
+++ /dev/null
@@ -1,95 +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
-
-# Django
-from django.contrib.auth.models import User
-from django.db import models
-
-# wger
-from wger.gym.models import Gym
-
-
-class Log(models.Model):
- """
- A log of a sent email
- """
-
- class Meta:
- ordering = [
- "-date",
- ]
-
- date = models.DateField(auto_now=True)
- """
- Date when the log was created
- """
-
- user = models.ForeignKey(
- User,
- editable=False,
- on_delete=models.CASCADE,
- )
- """
- The user that created the email
- """
-
- gym = models.ForeignKey(
- Gym,
- editable=False,
- related_name='email_log',
- on_delete=models.CASCADE,
- )
- """
- Gym this log belongs to
- """
-
- subject = models.CharField(max_length=100)
- """
- The email subject
- """
-
- body = models.TextField()
- """
- The email body
- """
-
- def __unicode__(self):
- """
- Return a more human-readable representation
- """
- return self.subject
-
-
-class CronEntry(models.Model):
- """
- Simple list of emails to be sent by a cron job
- """
-
- log = models.ForeignKey(Log, editable=False, on_delete=models.CASCADE)
- """
- Foreign key to email log with subject and body
- """
-
- email = models.EmailField()
- """
- The email address
- """
-
- def __unicode__(self):
- """
- Return a more human-readable representation
- """
- return self.email
diff --git a/wger/mailer/models/__init__.py b/wger/mailer/models/__init__.py
new file mode 100644
index 000000000..d036ec80c
--- /dev/null
+++ b/wger/mailer/models/__init__.py
@@ -0,0 +1,19 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Local
+from .cron import CronEntry
+from .log import Log
diff --git a/wger/mailer/models/cron.py b/wger/mailer/models/cron.py
new file mode 100644
index 000000000..5b7fce12f
--- /dev/null
+++ b/wger/mailer/models/cron.py
@@ -0,0 +1,43 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.db import models
+
+# Local
+from .log import Log
+
+
+class CronEntry(models.Model):
+ """
+ Simple list of emails to be sent by a cron job
+ """
+
+ log = models.ForeignKey(Log, editable=False, on_delete=models.CASCADE)
+ """
+ Foreign key to email log with subject and body
+ """
+
+ email = models.EmailField()
+ """
+ The email address
+ """
+
+ def __unicode__(self):
+ """
+ Return a more human-readable representation
+ """
+ return self.email
diff --git a/wger/mailer/models/log.py b/wger/mailer/models/log.py
new file mode 100644
index 000000000..b85983d72
--- /dev/null
+++ b/wger/mailer/models/log.py
@@ -0,0 +1,73 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.contrib.auth.models import User
+from django.db import models
+
+# wger
+from wger.gym.models import Gym
+
+
+class Log(models.Model):
+ """
+ A log of a sent email
+ """
+
+ class Meta:
+ ordering = [
+ "-date",
+ ]
+
+ date = models.DateField(auto_now=True)
+ """
+ Date when the log was created
+ """
+
+ user = models.ForeignKey(
+ User,
+ editable=False,
+ on_delete=models.CASCADE,
+ )
+ """
+ The user that created the email
+ """
+
+ gym = models.ForeignKey(
+ Gym,
+ editable=False,
+ related_name='email_log',
+ on_delete=models.CASCADE,
+ )
+ """
+ Gym this log belongs to
+ """
+
+ subject = models.CharField(max_length=100)
+ """
+ The email subject
+ """
+
+ body = models.TextField()
+ """
+ The email body
+ """
+
+ def __unicode__(self):
+ """
+ Return a more human-readable representation
+ """
+ return self.subject
diff --git a/wger/manager/consts.py b/wger/manager/consts.py
new file mode 100644
index 000000000..048dd8b9c
--- /dev/null
+++ b/wger/manager/consts.py
@@ -0,0 +1,28 @@
+# 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/>.
+
+RIR_OPTIONS = [
+ (None, '------'),
+ ('0', 0),
+ ('0.5', 0.5),
+ ('1', 1),
+ ('1.5', 1.5),
+ ('2', 2),
+ ('2.5', 2.5),
+ ('3', 3),
+ ('3.5', 3.5),
+ ('4', 4),
+]
diff --git a/wger/manager/forms.py b/wger/manager/forms.py
index d322f5bf5..c23da1409 100644
--- a/wger/manager/forms.py
+++ b/wger/manager/forms.py
@@ -50,8 +50,8 @@ from wger.core.models import (
WeightUnit,
)
from wger.exercises.models import Exercise
+from wger.manager.consts import RIR_OPTIONS
from wger.manager.models import (
- RIR_OPTIONS,
Day,
Set,
Setting,
diff --git a/wger/manager/managers.py b/wger/manager/managers.py
new file mode 100644
index 000000000..eb9ca48fb
--- /dev/null
+++ b/wger/manager/managers.py
@@ -0,0 +1,66 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.core.exceptions import ObjectDoesNotExist
+from django.db import models
+
+
+
+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)
diff --git a/wger/manager/models.py b/wger/manager/models.py
index 07e8c92ab..6cf6ddc87 100644
--- a/wger/manager/models.py
+++ b/wger/manager/models.py
@@ -51,981 +51,6 @@ from wger.utils.fields import Html5DateField
from wger.utils.helpers import normalize_decimal
-logger = logging.getLogger(__name__)
-
-RIR_OPTIONS = [
- (None, '------'),
- ('0', 0),
- ('0.5', 0.5),
- ('1', 1),
- ('1.5', 1.5),
- ('2', 2),
- ('2.5', 2.5),
- ('3', 3),
- ('3.5', 3.5),
- ('4', 4),
-]
-
-
-#
-# Classes
-#
-class Workout(models.Model):
- """
- Model for a training schedule
- """
-
- class Meta:
- """
- Meta class to set some other properties
- """
- ordering = [
- "-creation_date",
- ]
-
- creation_date = models.DateField(_('Creation date'), auto_now_add=True)
- name = models.CharField(
- verbose_name=_('Name'),
- max_length=100,
- blank=True,
- help_text=_("The name of the workout"),
- )
- description = models.TextField(
- verbose_name=_('Description'),
- max_length=1000,
- blank=True,
- help_text=_(
- "A short description or goal of the workout. For "
- "example 'Focus on back' or 'Week 1 of program "
- "xy'."
- ),
- )
-
- user = models.ForeignKey(User, verbose_name=_('User'), on_delete=models.CASCADE)
-
- def get_absolute_url(self):
- """
- Returns the canonical URL to view a workout
- """
- return reverse('manager:workout:view', kwargs={'pk': self.id})
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- if self.name:
- return self.name
- else:
- return "{0} ({1})".format(_('Workout'), self.creation_date)
-
- def save(self, *args, **kwargs):
- """
- Reset all cached infos
- """
- reset_workout_canonical_form(self.id)
- super(Workout, self).save(*args, **kwargs)
-
- def delete(self, *args, **kwargs):
- """
- Reset all cached infos
- """
- reset_workout_canonical_form(self.id)
- super(Workout, self).delete(*args, **kwargs)
-
- def get_owner_object(self):
- """
- Returns the object that has owner information
- """
- return self
-
- @property
- def canonical_representation(self):
- """
- Returns a canonical representation of the workout
-
- This form makes it easier to cache and use everywhere where all or part
- of a workout structure is needed. As an additional benefit, the template
- caches are not needed anymore.
- """
- workout_canonical_form = cache.get(cache_mapper.get_workout_canonical(self.pk))
- if not workout_canonical_form:
- day_canonical_repr = []
- muscles_front = []
- muscles_back = []
- muscles_front_secondary = []
- muscles_back_secondary = []
-
- # Sort list by weekday
- day_list = [i for i in self.day_set.select_related()]
- day_list.sort(key=lambda day: day.get_first_day_id)
-
- for day in day_list:
- canonical_repr_day = day.get_canonical_representation()
-
- # Collect all muscles
- for i in canonical_repr_day['muscles']['front']:
- if i not in muscles_front:
- muscles_front.append(i)
- for i in canonical_repr_day['muscles']['back']:
- if i not in muscles_back:
- muscles_back.append(i)
- for i in canonical_repr_day['muscles']['frontsecondary']:
- if i not in muscles_front_secondary:
- muscles_front_secondary.append(i)
- for i in canonical_repr_day['muscles']['backsecondary']:
- if i not in muscles_back_secondary:
- muscles_back_secondary.append(i)
-
- day_canonical_repr.append(canonical_repr_day)
-
- workout_canonical_form = {
- 'obj': self,
- 'muscles': {
- 'front': muscles_front,
- 'back': muscles_back,
- 'frontsecondary': muscles_front_secondary,
- 'backsecondary': muscles_back_secondary
- },
- 'day_list': day_canonical_repr
- }
- # Save to cache
- cache.set(cache_mapper.get_workout_canonical(self.pk), workout_canonical_form)
-
- return workout_canonical_form
-
-
-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
- """
-
- # 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 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
-
-
-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
-
-
-class Day(models.Model):
- """
- Model for a training day
- """
-
- training = models.ForeignKey(Workout, verbose_name=_('Workout'), on_delete=models.CASCADE)
- description = models.CharField(
- max_length=100,
- verbose_name=_('Description'),
- help_text=_(
- 'A description of what is done on this day (e.g. '
- '"Pull day") or what body parts are trained (e.g. '
- '"Arms and abs")'
- ),
- )
- day = models.ManyToManyField(DaysOfWeek, verbose_name=_('Day'))
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.description
-
- def get_owner_object(self):
- """
- Returns the object that has owner information
- """
- return self.training
-
- @property
- def get_first_day_id(self):
- """
- Return the PK of the first day of the week, this is used in the template
- to order the days in the template
- """
- return self.day.all()[0].pk
-
- def save(self, *args, **kwargs):
- """
- Reset all cached infos
- """
-
- reset_workout_canonical_form(self.training_id)
- super(Day, self).save(*args, **kwargs)
-
- def delete(self, *args, **kwargs):
- """
- Reset all cached infos
- """
-
- reset_workout_canonical_form(self.training_id)
- super(Day, self).delete(*args, **kwargs)
-
- @property
- def canonical_representation(self):
- """
- Return the canonical representation for this day
-
- This is extracted from the workout representation because that one is cached
- and this isn't.
- """
- for i in self.training.canonical_representation['day_list']:
- if int(i['obj'].pk) == int(self.pk):
- return i
-
- def get_canonical_representation(self):
- """
- Creates a canonical representation for this day
- """
- canonical_repr = []
- muscles_front = []
- muscles_back = []
- muscles_front_secondary = []
- muscles_back_secondary = []
-
- for set_obj in self.set_set.select_related():
- exercise_tmp = []
-
- for exercise in set_obj.exercises:
- setting_tmp = []
- exercise_images_tmp = []
-
- # Muscles for this set
- for muscle in exercise.muscles.all():
- if muscle.is_front and muscle not in muscles_front:
- muscles_front.append(muscle)
- elif not muscle.is_front and muscle not in muscles_back:
- muscles_back.append(muscle)
-
- for muscle in exercise.muscles_secondary.all():
- if muscle.is_front and muscle not in muscles_front:
- muscles_front_secondary.append(muscle)
- elif not muscle.is_front and muscle.id not in muscles_back:
- muscles_back_secondary.append(muscle)
-
- for setting in Setting.objects.filter(set=set_obj,
- exercise=exercise).order_by('order', 'id'):
- setting_tmp.append(setting)
-
- # "Smart" textual representation
- setting_text = set_obj.reps_smart_text(exercise)
-
- # Exercise comments
- comment_list = []
- for i in exercise.exercisecomment_set.all():
- comment_list.append(i.comment)
-
- # Flag indicating whether any of the settings has saved weight
- has_weight = False
- for i in setting_tmp:
- if i.weight:
- has_weight = True
- break
-
- # Collect exercise images
- for image in exercise.images.all():
- exercise_images_tmp.append(
- {
- 'image': image.image.url,
- 'is_main': image.is_main,
- }
- )
-
- # Put it all together
- exercise_tmp.append(
- {
- 'obj': exercise,
- 'setting_obj_list': setting_tmp,
- 'setting_text': setting_text,
- 'has_weight': has_weight,
- 'comment_list': comment_list,
- 'image_list': exercise_images_tmp
- }
- )
-
- # If it's a superset, check that all exercises have the same repetitions.
- # If not, just take the smallest number and drop the rest, because otherwise
- # it doesn't make sense
-
- # if len(exercise_tmp) > 1:
- # common_reps = 100
- # for exercise in exercise_tmp:
- # if len(exercise['setting_list']) < common_reps:
- # common_reps = len(exercise['setting_list'])
-
- # for exercise in exercise_tmp:
- # if len(exercise['setting_list']) > common_reps:
- # exercise['setting_list'].pop(-1)
- # exercise['setting_obj_list'].pop(-1)
- # setting_text, setting_list = set_obj.reps_smart_text(exercise)
- # exercise['setting_text'] = setting_text
-
- canonical_repr.append(
- {
- 'obj': set_obj,
- 'exercise_list': exercise_tmp,
- 'is_superset': True if len(exercise_tmp) > 1 else False,
- 'settings_computed': set_obj.compute_settings,
- 'muscles': {
- 'back': muscles_back,
- 'front': muscles_front,
- 'frontsecondary': muscles_front_secondary,
- 'backsecondary': muscles_front_secondary
- }
- }
- )
-
- # Days of the week
- tmp_days_of_week = []
- for day_of_week in self.day.select_related():
- tmp_days_of_week.append(day_of_week)
-
- return {
- 'obj': self,
- 'days_of_week': {
- 'text': ', '.join([str(_(i.day_of_week)) for i in tmp_days_of_week]),
- 'day_list': tmp_days_of_week
- },
- 'muscles': {
- 'back': muscles_back,
- 'front': muscles_front,
- 'frontsecondary': muscles_front_secondary,
- 'backsecondary': muscles_front_secondary
- },
- 'set_list': canonical_repr
- }
-
-
-class Set(models.Model):
- """
- Model for a set of exercises
- """
- DEFAULT_SETS = 4
- MAX_SETS = 10
-
- exerciseday = models.ForeignKey(
- Day,
- verbose_name=_('Exercise day'),
- on_delete=models.CASCADE,
- )
- order = models.IntegerField(
- blank=True,
- null=True,
- verbose_name=_('Order'),
- )
- sets = models.IntegerField(
- validators=[MinValueValidator(0), MaxValueValidator(MAX_SETS)],
- verbose_name=_('Number of sets'),
- default=DEFAULT_SETS,
- )
-
- # Metaclass to set some other properties
- class Meta:
- ordering = [
- "order",
- ]
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return "Set-ID {0}".format(self.id)
-
- def get_owner_object(self):
- """
- Returns the object that has owner information
- """
- return self.exerciseday.training
-
- def save(self, *args, **kwargs):
- """
- Reset all cached infos
- """
-
- reset_workout_canonical_form(self.exerciseday.training_id)
- super(Set, self).save(*args, **kwargs)
-
- def delete(self, *args, **kwargs):
- """
- Reset all cached infos
- """
-
- reset_workout_canonical_form(self.exerciseday.training_id)
- super(Set, self).delete(*args, **kwargs)
-
- @property
- def exercises(self) -> typing.List[Exercise]:
- """Returns the exercises for this set"""
- return list(dict.fromkeys([s.exercise for s in self.setting_set.all()]))
-
- @property
- def compute_settings(self): # -> typing.List[Setting]:
- """
- Compute the synthetic settings for this set.
-
- If we have super sets the result will be an interleaved list of
- settings so the result are the exercises that have to be done, in
- order, e.g.:
-
- * Exercise 1, 10 reps, 50 kg
- * Exercise 2, 8 reps, 10 kg
- * Exercise 1, 10 reps, 50 kg
- * Exercise 2, 8 reps, 10 kg
- """
- setting_lists = []
- for exercise in self.exercises:
- setting_lists.append(self.computed_settings_exercise(exercise))
-
- # Interleave all lists
- return [val for tup in zip(*setting_lists) for val in tup]
-
- def computed_settings_exercise(self, exercise: Exercise): # -> typing.List[Setting]
- """
- Returns a computed list of settings
-
- If a set has only one set
- """
- settings = self.setting_set.filter(exercise=exercise)
-
- if settings.count() == 0:
- return []
- elif settings.count() == 1:
- setting = settings.first()
- return [setting] * self.sets
- else:
- return list(settings.all())
-
- def reps_smart_text(self, exercise: Exercise):
- """
- "Smart" textual representation
-
- This is a human representation of the settings, in a way that humans
- would also write: e.g. "8 8 10 10" but "4 x 10" and not "10 10 10 10".
- This helper also takes care to process, hide or show the different repetition
- and weight units as appropriate, e.g. "8 x 2 Plates", "10, 20, 30, ∞"
-
- :param exercise:
- :return setting_text, setting_list:
- """
-
- def get_rir_representation(setting):
- """
- Returns the representation for the Reps-In-Reserve for a setting
- """
-
- if setting.rir:
- rir = f"{setting.rir} RiR"
- else:
- rir = ""
- return rir
-
- def get_reps_reprentation(setting, rep_unit):
- """
- Returns the representation for the repetitions for a setting
-
- This is basically just to allow for a special representation for the
- "Until Failure" unit
- """
- if setting.repetition_unit_id != 2:
- reps = "{0} {1}".format(setting.reps, rep_unit).strip()
- else:
- reps = '∞'
- return reps
-
- def get_weight_unit_reprentation(setting):
- """
- Returns the representation for the weight unit for a setting
-
- This is basically just to allow for a special representation for the
- "Repetition" and "Until Failure" unit
- """
- if setting.repetition_unit.id not in (1, 2):
- rep_unit = _(setting.repetition_unit.name)
- else:
- rep_unit = ''
- return rep_unit
-
- def normalize_weight(setting):
- """
- The weight can be None, or a decimal. In that case, normalize so
- that we don't return e.g. '15.00', but always '15', independently of
- the database used.
- """
- if setting.weight:
- weight = normalize_decimal(setting.weight)
- else:
- weight = setting.weight
- return weight
-
- def get_setting_text(current_setting, multi=False):
- """Gets the repetition text for a complete setting"""
- rep_unit = get_weight_unit_reprentation(current_setting)
- reps = get_reps_reprentation(current_setting, rep_unit)
- weight_unit = settings[0].weight_unit.name
- weight = normalize_weight(current_setting)
- rir = get_rir_representation(current_setting)
- out = '{0} × {1}'.format(self.sets, reps).strip() if not multi else reps
- if weight:
- rir_text = f', {rir}' if rir else ''
- out += f' ({weight} {weight_unit}{rir_text})'
- else:
- out += ' ({0})'.format(rir) if rir else ''
-
- return out
-
- settings = self.setting_set.filter(exercise=exercise)
- setting_text = ''
-
- # Only one setting entry, this is a "compact" representation such as e.g.
- # 4x10 or similar
- if len(settings) == 1:
- setting = settings[0]
- setting_text = get_setting_text(setting)
-
- # There's more than one setting, each set can have a different combination
- # of repetitions, weight, etc. e.g. 10, 8, 8, 12
- elif len(settings) > 1:
- tmp_reps_text = []
- for setting in settings:
- tmp_reps_text.append(get_setting_text(setting, multi=True))
-
- setting_text = ' – '.join(tmp_reps_text)
-
- return setting_text
-
-
-class Setting(models.Model):
- """
- Settings for an exercise (weight, reps, etc.)
- """
-
- set = models.ForeignKey(Set, verbose_name=_('Sets'), on_delete=models.CASCADE)
- exercise = models.ForeignKey(Exercise, verbose_name=_('Exercises'), on_delete=models.CASCADE)
- repetition_unit = models.ForeignKey(
- RepetitionUnit,
- verbose_name=_('Unit'),
- default=1,
- on_delete=models.CASCADE,
- )
- """
- The repetition unit of a set. This can be e.g. a repetition, a minute, etc.
- """
-
- reps = models.IntegerField(
- validators=[MinValueValidator(0), MaxValueValidator(600)],
- verbose_name=_('Reps'),
- )
- """
- Amount of repetitions, minutes, etc. for a set.
-
- Note that since adding the unit field, the name is no longer correct, but is
- kept for compatibility reasons (specially for the REST API).
- """
-
- weight = models.DecimalField(
- verbose_name=_('Weight'),
- max_digits=6,
- decimal_places=2,
- blank=True,
- null=True,
- validators=[MinValueValidator(0), MaxValueValidator(1500)]
- )
- """Planed weight for the repetitions"""
-
- weight_unit = models.ForeignKey(
- WeightUnit,
- verbose_name=_('Unit'),
- default=1,
- on_delete=models.CASCADE,
- )
- """
- The weight unit of a set. This can be e.g. kg, lb, km/h, etc.
- """
-
- rir = models.CharField(
- verbose_name=_('RiR'),
- max_length=3,
- blank=True,
- null=True,
- choices=RIR_OPTIONS,
- )
- """
- Reps in reserve, RiR. The amount of reps that could realistically still be
- done in the set.
- """
-
- order = models.IntegerField(blank=True, verbose_name=_('Order'))
- comment = models.CharField(max_length=100, blank=True, verbose_name=_('Comment'))
-
- # Metaclass to set some other properties
- class Meta:
- ordering = ["order", "id"]
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return f"setting {self.id} for exercise {self.exercise_id} in set {self.set_id}"
-
- def save(self, *args, **kwargs):
- """
- Reset cache
- """
- reset_workout_canonical_form(self.set.exerciseday.training_id)
-
- # If the user selected "Until Failure", do only 1 "repetition",
- # everythin else doesn't make sense.
- if self.repetition_unit == 2:
- self.reps = 1
- super(Setting, self).save(*args, **kwargs)
-
- def delete(self, *args, **kwargs):
- """
- Reset cache
- """
-
- reset_workout_canonical_form(self.set.exerciseday.training_id)
- super(Setting, self).delete(*args, **kwargs)
-
- def get_owner_object(self):
- """
- Returns the object that has owner information
- """
- return self.set.exerciseday.training
-
-
-class WorkoutLog(models.Model):
- """
- A log entry for an exercise
- """
-
- user = models.ForeignKey(
- User,
- verbose_name=_('User'),
- editable=False,
- on_delete=models.CASCADE,
- )
- exercise = models.ForeignKey(
- Exercise,
- verbose_name=_('Exercise'),
- on_delete=models.CASCADE,
- )
- workout = models.ForeignKey(
- Workout,
- verbose_name=_('Workout'),
- on_delete=models.CASCADE,
- )
-
- repetition_unit = models.ForeignKey(
- RepetitionUnit,
- verbose_name=_('Unit'),
- default=1,
- on_delete=models.CASCADE,
- )
- """
- The unit of the log. This can be e.g. a repetition, a minute, etc.
- """
-
- reps = models.IntegerField(
- verbose_name=_('Repetitions'),
- validators=[MinValueValidator(0)],
- )
- """
- Amount of repetitions, minutes, etc.
-
- Note that since adding the unit field, the name is no longer correct, but is
- kept for compatibility reasons (specially for the REST API).
- """
-
- weight = models.DecimalField(
- decimal_places=2,
- max_digits=5,
- verbose_name=_('Weight'),
- validators=[MinValueValidator(0)],
- )
-
- weight_unit = models.ForeignKey(
- WeightUnit,
- verbose_name=_('Unit'),
- default=1,
- on_delete=models.CASCADE,
- )
- """
- The weight unit of the log. This can be e.g. kg, lb, km/h, etc.
- """
-
- date = Html5DateField(verbose_name=_('Date'))
-
- rir = models.CharField(
- verbose_name=_('RiR'),
- max_length=3,
- blank=True,
- null=True,
- choices=RIR_OPTIONS,
- )
- """
- Reps in reserve, RiR. The amount of reps that could realistically still be
- done in the set.
- """
-
- # Metaclass to set some other properties
- class Meta:
- ordering = ["date", "reps"]
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return "Log entry: {0} - {1} kg on {2}".format(self.reps, self.weight, self.date)
-
- def get_owner_object(self):
- """
- Returns the object that has owner information
- """
- return self
-
- def get_workout_session(self, date=None):
- """
- Returns the corresponding workout session
-
- :return the WorkoutSession object or None if nothing was found
- """
- if not date:
- date = self.date
-
- try:
- return WorkoutSession.objects.filter(user=self.user).get(date=date)
- except WorkoutSession.DoesNotExist:
- return None
-
- def save(self, *args, **kwargs):
- """
- Reset cache
- """
- reset_workout_log(self.user_id, self.date.year, self.date.month, self.date.day)
-
- # If the user selected "Until Failure", do only 1 "repetition",
- # everythin else doesn't make sense.
- if self.repetition_unit == 2:
- self.reps = 1
- super(WorkoutLog, self).save(*args, **kwargs)
-
- def delete(self, *args, **kwargs):
- """
- Reset cache
- """
- reset_workout_log(self.user_id, self.date.year, self.date.month, self.date.day)
- super(WorkoutLog, self).delete(*args, **kwargs)
-
-
class WorkoutSession(models.Model):
"""
Model for a workout session
diff --git a/wger/manager/models/__init__.py b/wger/manager/models/__init__.py
new file mode 100644
index 000000000..fea4e1270
--- /dev/null
+++ b/wger/manager/models/__init__.py
@@ -0,0 +1,25 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Local
+from .day import Day
+from .log import WorkoutLog
+from .schedule import Schedule
+from .schedule_step import ScheduleStep
+from .session import WorkoutSession
+from .set import Set
+from .setting import Setting
+from .workout import Workout
diff --git a/wger/manager/models/day.py b/wger/manager/models/day.py
new file mode 100644
index 000000000..a69bc27c4
--- /dev/null
+++ b/wger/manager/models/day.py
@@ -0,0 +1,217 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.core.models import DaysOfWeek
+from wger.utils.cache import reset_workout_canonical_form
+
+# Local
+from .workout import Workout
+
+
+class Day(models.Model):
+ """
+ Model for a training day
+ """
+
+ training = models.ForeignKey(Workout, verbose_name=_('Workout'), on_delete=models.CASCADE)
+ description = models.CharField(
+ max_length=100,
+ verbose_name=_('Description'),
+ help_text=_(
+ 'A description of what is done on this day (e.g. '
+ '"Pull day") or what body parts are trained (e.g. '
+ '"Arms and abs")'
+ ),
+ )
+ day = models.ManyToManyField(DaysOfWeek, verbose_name=_('Day'))
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return self.description
+
+ def get_owner_object(self):
+ """
+ Returns the object that has owner information
+ """
+ return self.training
+
+ @property
+ def get_first_day_id(self):
+ """
+ Return the PK of the first day of the week, this is used in the template
+ to order the days in the template
+ """
+ return self.day.all()[0].pk
+
+ def save(self, *args, **kwargs):
+ """
+ Reset all cached infos
+ """
+
+ reset_workout_canonical_form(self.training_id)
+ super(Day, self).save(*args, **kwargs)
+
+ def delete(self, *args, **kwargs):
+ """
+ Reset all cached infos
+ """
+
+ reset_workout_canonical_form(self.training_id)
+ super(Day, self).delete(*args, **kwargs)
+
+ @property
+ def canonical_representation(self):
+ """
+ Return the canonical representation for this day
+
+ This is extracted from the workout representation because that one is cached
+ and this isn't.
+ """
+ for i in self.training.canonical_representation['day_list']:
+ if int(i['obj'].pk) == int(self.pk):
+ return i
+
+ def get_canonical_representation(self):
+ """
+ Creates a canonical representation for this day
+ """
+ # Local
+ from .setting import Setting
+
+ canonical_repr = []
+ muscles_front = []
+ muscles_back = []
+ muscles_front_secondary = []
+ muscles_back_secondary = []
+
+ for set_obj in self.set_set.select_related():
+ exercise_tmp = []
+
+ for exercise in set_obj.exercises:
+ setting_tmp = []
+ exercise_images_tmp = []
+
+ # Muscles for this set
+ for muscle in exercise.muscles.all():
+ if muscle.is_front and muscle not in muscles_front:
+ muscles_front.append(muscle)
+ elif not muscle.is_front and muscle not in muscles_back:
+ muscles_back.append(muscle)
+
+ for muscle in exercise.muscles_secondary.all():
+ if muscle.is_front and muscle not in muscles_front:
+ muscles_front_secondary.append(muscle)
+ elif not muscle.is_front and muscle.id not in muscles_back:
+ muscles_back_secondary.append(muscle)
+
+ for setting in Setting.objects.filter(set=set_obj,
+ exercise=exercise).order_by('order', 'id'):
+ setting_tmp.append(setting)
+
+ # "Smart" textual representation
+ setting_text = set_obj.reps_smart_text(exercise)
+
+ # Exercise comments
+ comment_list = []
+ for i in exercise.exercisecomment_set.all():
+ comment_list.append(i.comment)
+
+ # Flag indicating whether any of the settings has saved weight
+ has_weight = False
+ for i in setting_tmp:
+ if i.weight:
+ has_weight = True
+ break
+
+ # Collect exercise images
+ for image in exercise.images.all():
+ exercise_images_tmp.append(
+ {
+ 'image': image.image.url,
+ 'is_main': image.is_main,
+ }
+ )
+
+ # Put it all together
+ exercise_tmp.append(
+ {
+ 'obj': exercise,
+ 'setting_obj_list': setting_tmp,
+ 'setting_text': setting_text,
+ 'has_weight': has_weight,
+ 'comment_list': comment_list,
+ 'image_list': exercise_images_tmp
+ }
+ )
+
+ # If it's a superset, check that all exercises have the same repetitions.
+ # If not, just take the smallest number and drop the rest, because otherwise
+ # it doesn't make sense
+
+ # if len(exercise_tmp) > 1:
+ # common_reps = 100
+ # for exercise in exercise_tmp:
+ # if len(exercise['setting_list']) < common_reps:
+ # common_reps = len(exercise['setting_list'])
+
+ # for exercise in exercise_tmp:
+ # if len(exercise['setting_list']) > common_reps:
+ # exercise['setting_list'].pop(-1)
+ # exercise['setting_obj_list'].pop(-1)
+ # setting_text, setting_list = set_obj.reps_smart_text(exercise)
+ # exercise['setting_text'] = setting_text
+
+ canonical_repr.append(
+ {
+ 'obj': set_obj,
+ 'exercise_list': exercise_tmp,
+ 'is_superset': True if len(exercise_tmp) > 1 else False,
+ 'settings_computed': set_obj.compute_settings,
+ 'muscles': {
+ 'back': muscles_back,
+ 'front': muscles_front,
+ 'frontsecondary': muscles_front_secondary,
+ 'backsecondary': muscles_front_secondary
+ }
+ }
+ )
+
+ # Days of the week
+ tmp_days_of_week = []
+ for day_of_week in self.day.select_related():
+ tmp_days_of_week.append(day_of_week)
+
+ return {
+ 'obj': self,
+ 'days_of_week': {
+ 'text': ', '.join([str(_(i.day_of_week)) for i in tmp_days_of_week]),
+ 'day_list': tmp_days_of_week
+ },
+ 'muscles': {
+ 'back': muscles_back,
+ 'front': muscles_front,
+ 'frontsecondary': muscles_front_secondary,
+ 'backsecondary': muscles_front_secondary
+ },
+ 'set_list': canonical_repr
+ }
diff --git a/wger/manager/models/log.py b/wger/manager/models/log.py
new file mode 100644
index 000000000..4e1e4ad0d
--- /dev/null
+++ b/wger/manager/models/log.py
@@ -0,0 +1,159 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.contrib.auth.models import User
+from django.core.validators import MinValueValidator
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.core.models import (
+ RepetitionUnit,
+ WeightUnit,
+)
+from wger.exercises.models import Exercise
+from wger.utils.cache import reset_workout_log
+from wger.utils.fields import Html5DateField
+
+# Local
+from ..consts import RIR_OPTIONS
+from .session import WorkoutSession
+from .workout import Workout
+
+
+class WorkoutLog(models.Model):
+ """
+ A log entry for an exercise
+ """
+
+ user = models.ForeignKey(
+ User,
+ verbose_name=_('User'),
+ editable=False,
+ on_delete=models.CASCADE,
+ )
+ exercise = models.ForeignKey(
+ Exercise,
+ verbose_name=_('Exercise'),
+ on_delete=models.CASCADE,
+ )
+ workout = models.ForeignKey(
+ Workout,
+ verbose_name=_('Workout'),
+ on_delete=models.CASCADE,
+ )
+
+ repetition_unit = models.ForeignKey(
+ RepetitionUnit,
+ verbose_name=_('Unit'),
+ default=1,
+ on_delete=models.CASCADE,
+ )
+ """
+ The unit of the log. This can be e.g. a repetition, a minute, etc.
+ """
+
+ reps = models.IntegerField(
+ verbose_name=_('Repetitions'),
+ validators=[MinValueValidator(0)],
+ )
+ """
+ Amount of repetitions, minutes, etc.
+
+ Note that since adding the unit field, the name is no longer correct, but is
+ kept for compatibility reasons (specially for the REST API).
+ """
+
+ weight = models.DecimalField(
+ decimal_places=2,
+ max_digits=5,
+ verbose_name=_('Weight'),
+ validators=[MinValueValidator(0)],
+ )
+
+ weight_unit = models.ForeignKey(
+ WeightUnit,
+ verbose_name=_('Unit'),
+ default=1,
+ on_delete=models.CASCADE,
+ )
+ """
+ The weight unit of the log. This can be e.g. kg, lb, km/h, etc.
+ """
+
+ date = Html5DateField(verbose_name=_('Date'))
+
+ rir = models.CharField(
+ verbose_name=_('RiR'),
+ max_length=3,
+ blank=True,
+ null=True,
+ choices=RIR_OPTIONS,
+ )
+ """
+ Reps in reserve, RiR. The amount of reps that could realistically still be
+ done in the set.
+ """
+
+ # Metaclass to set some other properties
+ class Meta:
+ ordering = ["date", "reps"]
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return "Log entry: {0} - {1} kg on {2}".format(self.reps, self.weight, self.date)
+
+ def get_owner_object(self):
+ """
+ Returns the object that has owner information
+ """
+ return self
+
+ def get_workout_session(self, date=None):
+ """
+ Returns the corresponding workout session
+
+ :return the WorkoutSession object or None if nothing was found
+ """
+ if not date:
+ date = self.date
+
+ try:
+ return WorkoutSession.objects.filter(user=self.user).get(date=date)
+ except WorkoutSession.DoesNotExist:
+ return None
+
+ def save(self, *args, **kwargs):
+ """
+ Reset cache
+ """
+ reset_workout_log(self.user_id, self.date.year, self.date.month, self.date.day)
+
+ # If the user selected "Until Failure", do only 1 "repetition",
+ # everythin else doesn't make sense.
+ if self.repetition_unit == 2:
+ self.reps = 1
+ super(WorkoutLog, self).save(*args, **kwargs)
+
+ def delete(self, *args, **kwargs):
+ """
+ Reset cache
+ """
+ reset_workout_log(self.user_id, self.date.year, self.date.month, self.date.day)
+ super(WorkoutLog, self).delete(*args, **kwargs)
diff --git a/wger/manager/models/schedule.py b/wger/manager/models/schedule.py
new file mode 100644
index 000000000..0cdbcbba4
--- /dev/null
+++ b/wger/manager/models/schedule.py
@@ -0,0 +1,144 @@
+# 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
new file mode 100644
index 000000000..c95b00392
--- /dev/null
+++ b/wger/manager/models/schedule_step.py
@@ -0,0 +1,95 @@
+# 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/models/session.py b/wger/manager/models/session.py
new file mode 100644
index 000000000..bb18e1a94
--- /dev/null
+++ b/wger/manager/models/session.py
@@ -0,0 +1,151 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.contrib.auth.models import User
+from django.core.exceptions import ValidationError
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.utils.cache import reset_workout_log
+from wger.utils.fields import Html5DateField
+
+# Local
+from .workout import Workout
+
+
+class WorkoutSession(models.Model):
+ """
+ Model for a workout session
+ """
+
+ # Note: values hardcoded in manager.helpers.WorkoutCalendar
+ IMPRESSION_BAD = '1'
+ IMPRESSION_NEUTRAL = '2'
+ IMPRESSION_GOOD = '3'
+
+ IMPRESSION = (
+ (IMPRESSION_BAD, _("Bad")),
+ (IMPRESSION_NEUTRAL, _('Neutral')),
+ (IMPRESSION_GOOD, _('Good')),
+ )
+
+ user = models.ForeignKey(
+ User,
+ verbose_name=_('User'),
+ on_delete=models.CASCADE,
+ )
+ """
+ The user the workout session belongs to
+
+ See note in weight.models.WeightEntry about why this is not editable=False
+ """
+
+ workout = models.ForeignKey(
+ Workout,
+ verbose_name=_('Workout'),
+ on_delete=models.CASCADE,
+ )
+ """
+ The workout the session belongs to
+ """
+
+ date = Html5DateField(verbose_name=_('Date'))
+ """
+ The date the workout session was performed
+ """
+
+ notes = models.TextField(
+ verbose_name=_('Notes'),
+ null=True,
+ blank=True,
+ help_text=_('Any notes you might want to save about this workout '
+ 'session.')
+ )
+ """
+ User notes about the workout
+ """
+
+ impression = models.CharField(
+ verbose_name=_('General impression'),
+ max_length=2,
+ choices=IMPRESSION,
+ default=IMPRESSION_NEUTRAL,
+ help_text=_(
+ 'Your impression about this workout session. '
+ 'Did you exercise as well as you could?'
+ )
+ )
+ """
+ The user's general impression of workout
+ """
+
+ time_start = models.TimeField(verbose_name=_('Start time'), blank=True, null=True)
+ """
+ Time the workout session started
+ """
+
+ time_end = models.TimeField(verbose_name=_('Finish time'), blank=True, null=True)
+ """
+ Time the workout session ended
+ """
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return "{0} - {1}".format(self.workout, self.date)
+
+ class Meta:
+ """
+ Set other properties
+ """
+ ordering = [
+ "date",
+ ]
+ unique_together = ("date", "user")
+
+ def clean(self):
+ """
+ Perform some additional validations
+ """
+
+ if (not self.time_end and self.time_start) or (self.time_end and not self.time_start):
+ raise ValidationError(_("If you enter a time, you must enter both start and end time."))
+
+ if self.time_end and self.time_start and self.time_start > self.time_end:
+ raise ValidationError(_("The start time cannot be after the end time."))
+
+ def get_owner_object(self):
+ """
+ Returns the object that has owner information
+ """
+ return self
+
+ def save(self, *args, **kwargs):
+ """
+ Reset cache
+ """
+ reset_workout_log(self.user_id, self.date.year, self.date.month)
+ super(WorkoutSession, self).save(*args, **kwargs)
+
+ def delete(self, *args, **kwargs):
+ """
+ Reset cache
+ """
+ reset_workout_log(self.user_id, self.date.year, self.date.month)
+ super(WorkoutSession, self).delete(*args, **kwargs)
diff --git a/wger/manager/models/set.py b/wger/manager/models/set.py
new file mode 100644
index 000000000..37890f853
--- /dev/null
+++ b/wger/manager/models/set.py
@@ -0,0 +1,232 @@
+# 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 typing
+
+# Django
+from django.core.validators import (
+ MaxValueValidator,
+ MinValueValidator,
+)
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.exercises.models import Exercise
+from wger.utils.cache import reset_workout_canonical_form
+from wger.utils.helpers import normalize_decimal
+
+# Local
+from .day import Day
+
+
+class Set(models.Model):
+ """
+ Model for a set of exercises
+ """
+ DEFAULT_SETS = 4
+ MAX_SETS = 10
+
+ exerciseday = models.ForeignKey(
+ Day,
+ verbose_name=_('Exercise day'),
+ on_delete=models.CASCADE,
+ )
+ order = models.IntegerField(
+ blank=True,
+ null=True,
+ verbose_name=_('Order'),
+ )
+ sets = models.IntegerField(
+ validators=[MinValueValidator(0), MaxValueValidator(MAX_SETS)],
+ verbose_name=_('Number of sets'),
+ default=DEFAULT_SETS,
+ )
+
+ # Metaclass to set some other properties
+ class Meta:
+ ordering = [
+ "order",
+ ]
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return "Set-ID {0}".format(self.id)
+
+ def get_owner_object(self):
+ """
+ Returns the object that has owner information
+ """
+ return self.exerciseday.training
+
+ def save(self, *args, **kwargs):
+ """
+ Reset all cached infos
+ """
+
+ reset_workout_canonical_form(self.exerciseday.training_id)
+ super(Set, self).save(*args, **kwargs)
+
+ def delete(self, *args, **kwargs):
+ """
+ Reset all cached infos
+ """
+
+ reset_workout_canonical_form(self.exerciseday.training_id)
+ super(Set, self).delete(*args, **kwargs)
+
+ @property
+ def exercises(self) -> typing.List[Exercise]:
+ """Returns the exercises for this set"""
+ return list(dict.fromkeys([s.exercise for s in self.setting_set.all()]))
+
+ @property
+ def compute_settings(self): # -> typing.List[Setting]:
+ """
+ Compute the synthetic settings for this set.
+
+ If we have super sets the result will be an interleaved list of
+ settings so the result are the exercises that have to be done, in
+ order, e.g.:
+
+ * Exercise 1, 10 reps, 50 kg
+ * Exercise 2, 8 reps, 10 kg
+ * Exercise 1, 10 reps, 50 kg
+ * Exercise 2, 8 reps, 10 kg
+ """
+ setting_lists = []
+ for exercise in self.exercises:
+ setting_lists.append(self.computed_settings_exercise(exercise))
+
+ # Interleave all lists
+ return [val for tup in zip(*setting_lists) for val in tup]
+
+ def computed_settings_exercise(self, exercise: Exercise): # -> typing.List[Setting]
+ """
+ Returns a computed list of settings
+
+ If a set has only one set
+ """
+ settings = self.setting_set.filter(exercise=exercise)
+
+ if settings.count() == 0:
+ return []
+ elif settings.count() == 1:
+ setting = settings.first()
+ return [setting] * self.sets
+ else:
+ return list(settings.all())
+
+ def reps_smart_text(self, exercise: Exercise):
+ """
+ "Smart" textual representation
+
+ This is a human representation of the settings, in a way that humans
+ would also write: e.g. "8 8 10 10" but "4 x 10" and not "10 10 10 10".
+ This helper also takes care to process, hide or show the different repetition
+ and weight units as appropriate, e.g. "8 x 2 Plates", "10, 20, 30, ∞"
+
+ :param exercise:
+ :return setting_text, setting_list:
+ """
+
+ def get_rir_representation(setting):
+ """
+ Returns the representation for the Reps-In-Reserve for a setting
+ """
+
+ if setting.rir:
+ rir = f"{setting.rir} RiR"
+ else:
+ rir = ""
+ return rir
+
+ def get_reps_reprentation(setting, rep_unit):
+ """
+ Returns the representation for the repetitions for a setting
+
+ This is basically just to allow for a special representation for the
+ "Until Failure" unit
+ """
+ if setting.repetition_unit_id != 2:
+ reps = "{0} {1}".format(setting.reps, rep_unit).strip()
+ else:
+ reps = '∞'
+ return reps
+
+ def get_weight_unit_reprentation(setting):
+ """
+ Returns the representation for the weight unit for a setting
+
+ This is basically just to allow for a special representation for the
+ "Repetition" and "Until Failure" unit
+ """
+ if setting.repetition_unit.id not in (1, 2):
+ rep_unit = _(setting.repetition_unit.name)
+ else:
+ rep_unit = ''
+ return rep_unit
+
+ def normalize_weight(setting):
+ """
+ The weight can be None, or a decimal. In that case, normalize so
+ that we don't return e.g. '15.00', but always '15', independently of
+ the database used.
+ """
+ if setting.weight:
+ weight = normalize_decimal(setting.weight)
+ else:
+ weight = setting.weight
+ return weight
+
+ def get_setting_text(current_setting, multi=False):
+ """Gets the repetition text for a complete setting"""
+ rep_unit = get_weight_unit_reprentation(current_setting)
+ reps = get_reps_reprentation(current_setting, rep_unit)
+ weight_unit = settings[0].weight_unit.name
+ weight = normalize_weight(current_setting)
+ rir = get_rir_representation(current_setting)
+ out = '{0} × {1}'.format(self.sets, reps).strip() if not multi else reps
+ if weight:
+ rir_text = f', {rir}' if rir else ''
+ out += f' ({weight} {weight_unit}{rir_text})'
+ else:
+ out += ' ({0})'.format(rir) if rir else ''
+
+ return out
+
+ settings = self.setting_set.filter(exercise=exercise)
+ setting_text = ''
+
+ # Only one setting entry, this is a "compact" representation such as e.g.
+ # 4x10 or similar
+ if len(settings) == 1:
+ setting = settings[0]
+ setting_text = get_setting_text(setting)
+
+ # There's more than one setting, each set can have a different combination
+ # of repetitions, weight, etc. e.g. 10, 8, 8, 12
+ elif len(settings) > 1:
+ tmp_reps_text = []
+ for setting in settings:
+ tmp_reps_text.append(get_setting_text(setting, multi=True))
+
+ setting_text = ' – '.join(tmp_reps_text)
+
+ return setting_text
diff --git a/wger/manager/models/setting.py b/wger/manager/models/setting.py
new file mode 100644
index 000000000..d9da49c34
--- /dev/null
+++ b/wger/manager/models/setting.py
@@ -0,0 +1,135 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.core.validators import (
+ MaxValueValidator,
+ MinValueValidator,
+)
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.core.models import (
+ RepetitionUnit,
+ WeightUnit,
+)
+from wger.exercises.models import Exercise
+from wger.utils.cache import reset_workout_canonical_form
+
+# Local
+from ..consts import RIR_OPTIONS
+from .set import Set
+
+
+class Setting(models.Model):
+ """
+ Settings for an exercise (weight, reps, etc.)
+ """
+
+ set = models.ForeignKey(Set, verbose_name=_('Sets'), on_delete=models.CASCADE)
+ exercise = models.ForeignKey(Exercise, verbose_name=_('Exercises'), on_delete=models.CASCADE)
+ repetition_unit = models.ForeignKey(
+ RepetitionUnit,
+ verbose_name=_('Unit'),
+ default=1,
+ on_delete=models.CASCADE,
+ )
+ """
+ The repetition unit of a set. This can be e.g. a repetition, a minute, etc.
+ """
+
+ reps = models.IntegerField(
+ validators=[MinValueValidator(0), MaxValueValidator(600)],
+ verbose_name=_('Reps'),
+ )
+ """
+ Amount of repetitions, minutes, etc. for a set.
+
+ Note that since adding the unit field, the name is no longer correct, but is
+ kept for compatibility reasons (specially for the REST API).
+ """
+
+ weight = models.DecimalField(
+ verbose_name=_('Weight'),
+ max_digits=6,
+ decimal_places=2,
+ blank=True,
+ null=True,
+ validators=[MinValueValidator(0), MaxValueValidator(1500)]
+ )
+ """Planed weight for the repetitions"""
+
+ weight_unit = models.ForeignKey(
+ WeightUnit,
+ verbose_name=_('Unit'),
+ default=1,
+ on_delete=models.CASCADE,
+ )
+ """
+ The weight unit of a set. This can be e.g. kg, lb, km/h, etc.
+ """
+
+ rir = models.CharField(
+ verbose_name=_('RiR'),
+ max_length=3,
+ blank=True,
+ null=True,
+ choices=RIR_OPTIONS,
+ )
+ """
+ Reps in reserve, RiR. The amount of reps that could realistically still be
+ done in the set.
+ """
+
+ order = models.IntegerField(blank=True, verbose_name=_('Order'))
+ comment = models.CharField(max_length=100, blank=True, verbose_name=_('Comment'))
+
+ # Metaclass to set some other properties
+ class Meta:
+ ordering = ["order", "id"]
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return f"setting {self.id} for exercise {self.exercise_id} in set {self.set_id}"
+
+ def save(self, *args, **kwargs):
+ """
+ Reset cache
+ """
+ reset_workout_canonical_form(self.set.exerciseday.training_id)
+
+ # If the user selected "Until Failure", do only 1 "repetition",
+ # everythin else doesn't make sense.
+ if self.repetition_unit == 2:
+ self.reps = 1
+ super(Setting, self).save(*args, **kwargs)
+
+ def delete(self, *args, **kwargs):
+ """
+ Reset cache
+ """
+
+ reset_workout_canonical_form(self.set.exerciseday.training_id)
+ super(Setting, self).delete(*args, **kwargs)
+
+ def get_owner_object(self):
+ """
+ Returns the object that has owner information
+ """
+ return self.set.exerciseday.training
diff --git a/wger/manager/models/workout.py b/wger/manager/models/workout.py
new file mode 100644
index 000000000..ba384624c
--- /dev/null
+++ b/wger/manager/models/workout.py
@@ -0,0 +1,152 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.contrib.auth.models import User
+from django.core.cache import cache
+from django.db import models
+from django.urls import reverse
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.utils.cache import (
+ cache_mapper,
+ reset_workout_canonical_form,
+)
+
+
+class Workout(models.Model):
+ """
+ Model for a training schedule
+ """
+
+ class Meta:
+ """
+ Meta class to set some other properties
+ """
+ ordering = [
+ "-creation_date",
+ ]
+
+ creation_date = models.DateField(_('Creation date'), auto_now_add=True)
+ name = models.CharField(
+ verbose_name=_('Name'),
+ max_length=100,
+ blank=True,
+ help_text=_("The name of the workout"),
+ )
+ description = models.TextField(
+ verbose_name=_('Description'),
+ max_length=1000,
+ blank=True,
+ help_text=_(
+ "A short description or goal of the workout. For "
+ "example 'Focus on back' or 'Week 1 of program "
+ "xy'."
+ ),
+ )
+
+ user = models.ForeignKey(User, verbose_name=_('User'), on_delete=models.CASCADE)
+
+ def get_absolute_url(self):
+ """
+ Returns the canonical URL to view a workout
+ """
+ return reverse('manager:workout:view', kwargs={'pk': self.id})
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ if self.name:
+ return self.name
+ else:
+ return "{0} ({1})".format(_('Workout'), self.creation_date)
+
+ def save(self, *args, **kwargs):
+ """
+ Reset all cached infos
+ """
+ reset_workout_canonical_form(self.id)
+ super(Workout, self).save(*args, **kwargs)
+
+ def delete(self, *args, **kwargs):
+ """
+ Reset all cached infos
+ """
+ reset_workout_canonical_form(self.id)
+ super(Workout, self).delete(*args, **kwargs)
+
+ def get_owner_object(self):
+ """
+ Returns the object that has owner information
+ """
+ return self
+
+ @property
+ def canonical_representation(self):
+ """
+ Returns a canonical representation of the workout
+
+ This form makes it easier to cache and use everywhere where all or part
+ of a workout structure is needed. As an additional benefit, the template
+ caches are not needed anymore.
+ """
+ workout_canonical_form = cache.get(cache_mapper.get_workout_canonical(self.pk))
+ if not workout_canonical_form:
+ day_canonical_repr = []
+ muscles_front = []
+ muscles_back = []
+ muscles_front_secondary = []
+ muscles_back_secondary = []
+
+ # Sort list by weekday
+ day_list = [i for i in self.day_set.select_related()]
+ day_list.sort(key=lambda day: day.get_first_day_id)
+
+ for day in day_list:
+ canonical_repr_day = day.get_canonical_representation()
+
+ # Collect all muscles
+ for i in canonical_repr_day['muscles']['front']:
+ if i not in muscles_front:
+ muscles_front.append(i)
+ for i in canonical_repr_day['muscles']['back']:
+ if i not in muscles_back:
+ muscles_back.append(i)
+ for i in canonical_repr_day['muscles']['frontsecondary']:
+ if i not in muscles_front_secondary:
+ muscles_front_secondary.append(i)
+ for i in canonical_repr_day['muscles']['backsecondary']:
+ if i not in muscles_back_secondary:
+ muscles_back_secondary.append(i)
+
+ day_canonical_repr.append(canonical_repr_day)
+
+ workout_canonical_form = {
+ 'obj': self,
+ 'muscles': {
+ 'front': muscles_front,
+ 'back': muscles_back,
+ 'frontsecondary': muscles_front_secondary,
+ 'backsecondary': muscles_back_secondary
+ },
+ 'day_list': day_canonical_repr
+ }
+ # Save to cache
+ cache.set(cache_mapper.get_workout_canonical(self.pk), workout_canonical_form)
+
+ return workout_canonical_form
diff --git a/wger/nutrition/consts.py b/wger/nutrition/consts.py
new file mode 100644
index 000000000..0088236c5
--- /dev/null
+++ b/wger/nutrition/consts.py
@@ -0,0 +1,36 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+MEALITEM_WEIGHT_GRAM = '1'
+MEALITEM_WEIGHT_UNIT = '2'
+
+ENERGY_FACTOR = {
+ 'protein': {
+ 'kg': 4,
+ 'lb': 113
+ },
+ 'carbohydrates': {
+ 'kg': 4,
+ 'lb': 113
+ },
+ 'fat': {
+ 'kg': 9,
+ 'lb': 225
+ }
+}
+"""
+Simple approximation of energy (kcal) provided per gram or ounce
+"""
diff --git a/wger/nutrition/helpers.py b/wger/nutrition/helpers.py
new file mode 100644
index 000000000..d663c13e8
--- /dev/null
+++ b/wger/nutrition/helpers.py
@@ -0,0 +1,105 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Standard Library
+from decimal import Decimal
+
+# wger
+from wger.nutrition.consts import (
+ MEALITEM_WEIGHT_GRAM,
+ MEALITEM_WEIGHT_UNIT,
+)
+from wger.utils.constants import TWOPLACES
+from wger.utils.units import AbstractWeight
+
+
+class BaseMealItem(object):
+ """
+ Base class for an item (component) of a meal or log
+
+ This just provides some common helper functions
+ """
+
+ def get_unit_type(self):
+ """
+ Returns the type of unit used:
+ - a value in grams
+ - a 'human' unit like 'a cup' or 'a slice'
+ """
+
+ if self.weight_unit:
+ return MEALITEM_WEIGHT_UNIT
+ else:
+ return MEALITEM_WEIGHT_GRAM
+
+ def get_nutritional_values(self, use_metric=True):
+ """
+ Sums the nutritional info for the ingredient in the MealItem
+
+ :param use_metric Flag that controls the units used
+ """
+ nutritional_info = {
+ 'energy': 0,
+ 'protein': 0,
+ 'carbohydrates': 0,
+ 'carbohydrates_sugar': 0,
+ 'fat': 0,
+ 'fat_saturated': 0,
+ 'fibres': 0,
+ 'sodium': 0
+ }
+ # Calculate the base weight of the item
+ if self.get_unit_type() == MEALITEM_WEIGHT_GRAM:
+ item_weight = self.amount
+ else:
+ item_weight = (self.amount * self.weight_unit.amount * self.weight_unit.gram)
+
+ nutritional_info['energy'] += self.ingredient.energy * item_weight / 100
+ nutritional_info['protein'] += self.ingredient.protein * item_weight / 100
+ nutritional_info['carbohydrates'] += self.ingredient.carbohydrates * item_weight / 100
+ nutritional_info['fat'] += self.ingredient.fat * item_weight / 100
+
+ if self.ingredient.carbohydrates_sugar:
+ nutritional_info['carbohydrates_sugar'] += \
+ self.ingredient.carbohydrates_sugar * item_weight / 100
+
+ if self.ingredient.fat_saturated:
+ nutritional_info['fat_saturated'] += self.ingredient.fat_saturated * item_weight / 100
+
+ if self.ingredient.fibres:
+ nutritional_info['fibres'] += self.ingredient.fibres * item_weight / 100
+
+ if self.ingredient.sodium:
+ nutritional_info['sodium'] += self.ingredient.sodium * item_weight / 100
+
+ # If necessary, convert weight units
+ if not use_metric:
+ for key, value in nutritional_info.items():
+
+ # Energy is not a weight!
+ if key == 'energy':
+ continue
+
+ # Everything else, to ounces
+ nutritional_info[key] = AbstractWeight(value, 'g').oz
+
+ nutritional_info['energy_kilojoule'] = Decimal(nutritional_info['energy']) * Decimal(4.184)
+
+ # Only 2 decimal places, anything else doesn't make sense
+ for i in nutritional_info:
+ nutritional_info[i] = Decimal(nutritional_info[i]).quantize(TWOPLACES)
+
+ return nutritional_info
diff --git a/wger/nutrition/migrations/0005_logitem.py b/wger/nutrition/migrations/0005_logitem.py
index 6f8ac8836..efce826d6 100644
--- a/wger/nutrition/migrations/0005_logitem.py
+++ b/wger/nutrition/migrations/0005_logitem.py
@@ -67,6 +67,6 @@ class Migration(migrations.Migration):
options={
'ordering': ['datetime'],
},
- bases=(wger.nutrition.models.BaseMealItem, models.Model),
+ bases=(wger.nutrition.helpers.BaseMealItem, models.Model),
),
]
diff --git a/wger/nutrition/models.py b/wger/nutrition/models.py
deleted file mode 100644
index 30ee96588..000000000
--- a/wger/nutrition/models.py
+++ /dev/null
@@ -1,1024 +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
-# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
-
-# Standard Library
-import datetime
-import logging
-from decimal import Decimal
-
-# Django
-from django.conf import settings
-from django.contrib.auth.models import User
-from django.contrib.sites.models import Site
-from django.core import mail
-from django.core.cache import cache
-from django.core.exceptions import ValidationError
-from django.core.validators import (
- MaxValueValidator,
- MinLengthValidator,
- MinValueValidator,
-)
-from django.db import models
-from django.template.loader import render_to_string
-from django.urls import reverse
-from django.utils import (
- timezone,
- translation,
-)
-from django.utils.text import slugify
-from django.utils.translation import gettext_lazy as _
-
-# wger
-from wger.core.models import Language
-from wger.utils.cache import cache_mapper
-from wger.utils.constants import TWOPLACES
-from wger.utils.fields import Html5TimeField
-from wger.utils.managers import SubmissionManager
-from wger.utils.models import (
- AbstractLicenseModel,
- AbstractSubmissionModel,
-)
-from wger.utils.units import AbstractWeight
-from wger.weight.models import WeightEntry
-
-
-MEALITEM_WEIGHT_GRAM = '1'
-MEALITEM_WEIGHT_UNIT = '2'
-
-ENERGY_FACTOR = {
- 'protein': {
- 'kg': 4,
- 'lb': 113
- },
- 'carbohydrates': {
- 'kg': 4,
- 'lb': 113
- },
- 'fat': {
- 'kg': 9,
- 'lb': 225
- }
-}
-"""
-Simple approximation of energy (kcal) provided per gram or ounce
-"""
-
-logger = logging.getLogger(__name__)
-
-
-class NutritionPlan(models.Model):
- """
- A nutrition plan
- """
-
- # Metaclass to set some other properties
- class Meta:
-
- # Order by creation_date, descending (oldest first)
- ordering = [
- "-creation_date",
- ]
-
- user = models.ForeignKey(
- User,
- verbose_name=_('User'),
- editable=False,
- on_delete=models.CASCADE,
- )
- language = models.ForeignKey(
- Language,
- verbose_name=_('Language'),
- editable=False,
- on_delete=models.CASCADE,
- )
- creation_date = models.DateField(_('Creation date'), auto_now_add=True)
- description = models.CharField(
- max_length=80,
- blank=True,
- verbose_name=_('Description'),
- help_text=_(
- 'A description of the goal of the plan, e.g. '
- '"Gain mass" or "Prepare for summer"'
- ),
- )
- has_goal_calories = models.BooleanField(
- verbose_name=_('Use daily calories'),
- default=False,
- help_text=_(
- "Tick the box if you want to mark this "
- "plan as having a goal amount of calories. "
- "You can use the calculator or enter the "
- "value yourself."
- ),
- )
- """A flag indicating whether the plan has a goal amount of calories"""
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- if self.description:
- return "{0}".format(self.description)
- else:
- return "{0}".format(_("Nutrition plan"))
-
- def get_absolute_url(self):
- """
- Returns the canonical URL to view this object
- """
- return reverse('nutrition:plan:view', kwargs={'id': self.id})
-
- def get_nutritional_values(self):
- """
- Sums the nutritional info of all items in the plan
- """
- nutritional_representation = cache.get(cache_mapper.get_nutrition_cache_by_key(self.pk))
- if not nutritional_representation:
- use_metric = self.user.userprofile.use_metric
- unit = 'kg' if use_metric else 'lb'
- result = {
- 'total': {
- 'energy': 0,
- 'protein': 0,
- 'carbohydrates': 0,
- 'carbohydrates_sugar': 0,
- 'fat': 0,
- 'fat_saturated': 0,
- 'fibres': 0,
- 'sodium': 0
- },
- 'percent': {
- 'protein': 0,
- 'carbohydrates': 0,
- 'fat': 0
- },
- 'per_kg': {
- 'protein': 0,
- 'carbohydrates': 0,
- 'fat': 0
- },
- }
-
- # Energy
- for meal in self.meal_set.select_related():
- values = meal.get_nutritional_values(use_metric=use_metric)
- for key in result['total'].keys():
- result['total'][key] += values[key]
-
- energy = result['total']['energy']
- result['total']['energy_kilojoule'] = result['total']['energy'] * Decimal(4.184)
-
- # In percent
- if energy:
- for key in result['percent'].keys():
- result['percent'][key] = \
- result['total'][key] * ENERGY_FACTOR[key][unit] / energy * 100
-
- # Per body weight
- weight_entry = self.get_closest_weight_entry()
- if weight_entry:
- for key in result['per_kg'].keys():
- result['per_kg'][key] = result['total'][key] / weight_entry.weight
-
- # Only 2 decimal places, anything else doesn't make sense
- for key in result.keys():
- for i in result[key]:
- result[key][i] = Decimal(result[key][i]).quantize(TWOPLACES)
- nutritional_representation = result
- cache.set(cache_mapper.get_nutrition_cache_by_key(self.pk), nutritional_representation)
- return nutritional_representation
-
- def get_closest_weight_entry(self):
- """
- Returns the closest weight entry for the nutrition plan.
- Returns None if there are no entries.
- """
- target = self.creation_date
- closest_entry_gte = WeightEntry.objects.filter(user=self.user) \
- .filter(date__gte=target).order_by('date').first()
- closest_entry_lte = WeightEntry.objects.filter(user=self.user) \
- .filter(date__lte=target).order_by('-date').first()
- if closest_entry_gte is None or closest_entry_lte is None:
- return closest_entry_gte or closest_entry_lte
- if abs(closest_entry_gte.date - target) < abs(closest_entry_lte.date - target):
- return closest_entry_gte
- else:
- return closest_entry_lte
-
- def get_owner_object(self):
- """
- Returns the object that has owner information
- """
- return self
-
- def get_calories_approximation(self):
- """
- Calculates the deviation from the goal calories and the actual
- amount of the current plan
- """
-
- goal_calories = self.user.userprofile.calories
- actual_calories = self.get_nutritional_values()['total']['energy']
-
- # Within 3%
- if (actual_calories < goal_calories * 1.03) and (actual_calories > goal_calories * 0.97):
- return 1
- # within 7%
- elif (actual_calories < goal_calories * 1.07) and (actual_calories > goal_calories * 0.93):
- return 2
- # within 10%
- elif (actual_calories < goal_calories * 1.10) and (actual_calories > goal_calories * 0.9):
- return 3
- # even more
- else:
- return 4
-
- def get_log_overview(self):
- """
- Returns an overview for all logs available for this plan
- """
- result = []
- for date in self.logitem_set.datetimes('datetime', 'day', order='DESC'):
- # TODO: in python 3.5 this can be simplified as z = {**x, **y}
- tmp = self.get_log_summary(date=date).copy()
- tmp.update({'date': date.date()})
- result.append(tmp)
-
- return result
-
- def get_log_entries(self, date=None):
- """
- Convenience function that returns the log entries for a given date
- """
- if not date:
- date = datetime.date.today()
-
- return self.logitem_set.filter(datetime__date=date).select_related()
-
- def get_log_summary(self, date=None):
- """
- Sums the nutritional info of the items logged for the given date
- """
- use_metric = self.user.userprofile.use_metric
- result = {
- 'energy': 0,
- 'protein': 0,
- 'carbohydrates': 0,
- 'carbohydrates_sugar': 0,
- 'fat': 0,
- 'fat_saturated': 0,
- 'fibres': 0,
- 'sodium': 0
- }
-
- # Perform the sums
- for item in self.get_log_entries(date):
- values = item.get_nutritional_values(use_metric=use_metric)
- for key in result.keys():
- result[key] += values[key]
- return result
-
-
-class IngredientCategory(models.Model):
- """
- Model for an Ingredient category
- """
- name = models.CharField(max_length=100, verbose_name=_('Name'))
-
- # Metaclass to set some other properties
- class Meta:
- verbose_name_plural = _("Ingredient Categories")
- ordering = [
- "name",
- ]
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.name
-
- def get_owner_object(self):
- """
- Category has no owner information
- """
- return False
-
-
-class Ingredient(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
- """
- An ingredient, with some approximate nutrition values
- """
- objects = SubmissionManager()
- """Custom manager"""
-
- ENERGY_APPROXIMATION = 15
- """
- How much the calculated energy from protein, etc. can deviate from the
- energy amount given (in percent).
- """
-
- # Metaclass to set some other properties
- class Meta:
- ordering = [
- "name",
- ]
-
- # Meta data
- language = models.ForeignKey(
- Language,
- verbose_name=_('Language'),
- editable=False,
- on_delete=models.CASCADE,
- )
-
- creation_date = models.DateField(_('Date'), auto_now_add=True)
- update_date = models.DateField(
- _('Date'),
- auto_now=True,
- blank=True,
- editable=False,
- )
-
- # Product infos
- name = models.CharField(
- max_length=200,
- verbose_name=_('Name'),
- validators=[MinLengthValidator(3)],
- )
-
- energy = models.IntegerField(verbose_name=_('Energy'), help_text=_('In kcal per 100g'))
-
- protein = models.DecimalField(
- decimal_places=3,
- max_digits=6,
- verbose_name=_('Protein'),
- help_text=_('In g per 100g of product'),
- validators=[MinValueValidator(0), MaxValueValidator(100)],
- )
-
- carbohydrates = models.DecimalField(
- decimal_places=3,
- max_digits=6,
- verbose_name=_('Carbohydrates'),
- help_text=_('In g per 100g of product'),
- validators=[MinValueValidator(0), MaxValueValidator(100)],
- )
-
- carbohydrates_sugar = models.DecimalField(
- decimal_places=3,
- max_digits=6,
- blank=True,
- null=True,
- verbose_name=_('Sugar content in carbohydrates'),
- help_text=_('In g per 100g of product'),
- validators=[MinValueValidator(0), MaxValueValidator(100)],
- )
-
- fat = models.DecimalField(
- decimal_places=3,
- max_digits=6,
- verbose_name=_('Fat'),
- help_text=_('In g per 100g of product'),
- validators=[MinValueValidator(0), MaxValueValidator(100)],
- )
-
- fat_saturated = models.DecimalField(
- decimal_places=3,
- max_digits=6,
- blank=True,
- null=True,
- verbose_name=_('Saturated fat content in fats'),
- help_text=_('In g per 100g of product'),
- validators=[MinValueValidator(0), MaxValueValidator(100)],
- )
-
- fibres = models.DecimalField(
- decimal_places=3,
- max_digits=6,
- blank=True,
- null=True,
- verbose_name=_('Fibres'),
- help_text=_('In g per 100g of product'),
- validators=[MinValueValidator(0), MaxValueValidator(100)],
- )
-
- sodium = models.DecimalField(
- decimal_places=3,
- max_digits=6,
- blank=True,
- null=True,
- verbose_name=_('Sodium'),
- help_text=_('In g per 100g of product'),
- validators=[MinValueValidator(0), MaxValueValidator(100)],
- )
-
- code = models.CharField(
- max_length=200,
- null=True,
- blank=True,
- db_index=True,
- )
- """Internal ID of the source database, e.g. a barcode or similar"""
-
- source_name = models.CharField(
- max_length=200,
- null=True,
- blank=True,
- )
- """Name of the source, such as Open Food Facts"""
-
- source_url = models.URLField(
- verbose_name=_('Link'),
- help_text=_('Link to product'),
- blank=True,
- null=True,
- )
- """URL of the product at the source"""
-
- last_imported = models.DateTimeField(
- _('Date'),
- auto_now_add=True,
- null=True,
- blank=True,
- )
-
- common_name = models.CharField(
- max_length=200,
- null=True,
- blank=True,
- )
-
- category = models.ForeignKey(
- IngredientCategory,
- verbose_name=_('Category'),
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- )
-
- brand = models.CharField(
- max_length=200,
- verbose_name=_('Brand name of product'),
- null=True,
- blank=True,
- )
-
- #
- # Django methods
- #
-
- def get_absolute_url(self):
- """
- Returns the canonical URL to view this object.
-
- Since some names consist of only non-ascii characters (e.g. 감자깡), the
- resulting slug would be empty and no URL would match. In that case, use
- the regular URL with only the ID.
- """
- slug = slugify(self.name)
- if not slug:
- return reverse('nutrition:ingredient:view', kwargs={'id': self.id})
- else:
- return reverse('nutrition:ingredient:view', kwargs={'id': self.id, 'slug': slug})
-
- def clean(self):
- """
- Do a very broad sanity check on the nutritional values according to
- the following rules:
- - 1g of protein: 4kcal
- - 1g of carbohydrates: 4kcal
- - 1g of fat: 9kcal
-
- The sum is then compared to the given total energy, with ENERGY_APPROXIMATION
- percent tolerance.
- """
-
- # Note: calculations in 100 grams, to save us the '/100' everywhere
- energy_protein = 0
- if self.protein:
- energy_protein = self.protein * ENERGY_FACTOR['protein']['kg']
-
- energy_carbohydrates = 0
- if self.carbohydrates:
- energy_carbohydrates = self.carbohydrates * ENERGY_FACTOR['carbohydrates']['kg']
-
- energy_fat = 0
- if self.fat:
- # TODO: for some reason, during the tests the fat value is not
- # converted to decimal (django 1.9)
- energy_fat = Decimal(self.fat * ENERGY_FACTOR['fat']['kg'])
-
- energy_calculated = energy_protein + energy_carbohydrates + energy_fat
-
- # Compare the values, but be generous
- if self.energy:
- energy_upper = self.energy * (1 + (self.ENERGY_APPROXIMATION / Decimal(100.0)))
- energy_lower = self.energy * (1 - (self.ENERGY_APPROXIMATION / Decimal(100.0)))
-
- if not ((energy_upper > energy_calculated) and (energy_calculated > energy_lower)):
- raise ValidationError(
- _(
- 'The total energy ({energy}kcal) is not the approximate sum of the '
- 'energy provided by protein, carbohydrates and fat ({energy_calculated}kcal '
- '+/-{energy_approx}%)'.format(
- energy=self.energy,
- energy_calculated=energy_calculated,
- energy_approx=self.ENERGY_APPROXIMATION
- )
- )
- )
-
- def save(self, *args, **kwargs):
- """
- Reset the cache
- """
-
- super(Ingredient, self).save(*args, **kwargs)
- cache.delete(cache_mapper.get_ingredient_key(self.id))
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.name
-
- def __eq__(self, other):
- """
- Compare ingredients based on their values, not like django on their PKs
- """
-
- logger.debug('Overwritten behaviour: comparing ingredients on values, not PK.')
- equal = True
- if isinstance(other, self.__class__):
- for i in self._meta.fields:
- if (
- hasattr(self, i.name) and hasattr(other, i.name)
- and (getattr(self, i.name, None) != getattr(other, i.name, None))
- ):
- equal = False
- else:
- equal = False
- return equal
-
- def __hash__(self):
- """
- Define a hash function
-
- This is rather unnecessary, but it seems that newer versions of django
- have a problem when the __eq__ function is implemented, but not the
- __hash__ one. Returning hash(pk) is also django's default.
-
- :return: hash(pk)
- """
- return hash(self.pk)
-
- #
- # Own methods
- #
- def compare_with_database(self):
- """
- Compares the current ingredient with the version saved in the database.
-
- If the current object has no PK, returns false
- """
- if not self.pk:
- return False
-
- ingredient = Ingredient.objects.get(pk=self.pk)
- if self != ingredient:
- return False
- else:
- return True
-
- def send_email(self, request):
- """
- Sends an email after being successfully added to the database (for user
- submitted ingredients only)
- """
- try:
- user = User.objects.get(username=self.license_author)
- except User.DoesNotExist:
- return
-
- if self.license_author and user.email:
- translation.activate(user.userprofile.notification_language.short_name)
- url = request.build_absolute_uri(self.get_absolute_url())
- subject = _('Ingredient was successfully added to the general database')
- context = {
- 'ingredient': self.name,
- 'url': url,
- 'site': Site.objects.get_current().domain
- }
- message = render_to_string('ingredient/email_new.tpl', context)
- mail.send_mail(
- subject,
- message,
- settings.WGER_SETTINGS['EMAIL_FROM'], [user.email],
- fail_silently=True
- )
-
- def set_author(self, request):
- if request.user.has_perm('nutrition.add_ingredient'):
- self.status = Ingredient.STATUS_ACCEPTED
- if not self.license_author:
- self.license_author = request.get_host().split(':')[0]
- else:
- if not self.license_author:
- self.license_author = request.user.username
-
- # Send email to administrator
- subject = _('New user submitted ingredient')
- message = _(
- """The user {0} submitted a new ingredient "{1}".""".format(
- request.user.username, self.name
- )
- )
- mail.mail_admins(subject, message, fail_silently=True)
-
- def get_owner_object(self):
- """
- Ingredient has no owner information
- """
- return False
-
- @property
- def energy_kilojoule(self):
- """
- returns kilojoules for current ingredient, 0 if energy is uninitialized
- """
- if self.energy:
- return Decimal(self.energy * 4.184).quantize(TWOPLACES)
- else:
- return 0
-
-
-class WeightUnit(models.Model):
- """
- A more human usable weight unit (spoon, table, slice...)
- """
-
- language = models.ForeignKey(
- Language,
- verbose_name=_('Language'),
- editable=False,
- on_delete=models.CASCADE,
- )
- name = models.CharField(
- max_length=200,
- verbose_name=_('Name'),
- )
-
- # Metaclass to set some other properties
- class Meta:
- ordering = [
- "name",
- ]
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return self.name
-
- def get_owner_object(self):
- """
- Weight unit has no owner information
- """
- return None
-
-
-class IngredientWeightUnit(models.Model):
- """
- A specific human usable weight unit for an ingredient
- """
-
- ingredient = models.ForeignKey(
- Ingredient,
- verbose_name=_('Ingredient'),
- editable=False,
- on_delete=models.CASCADE,
- )
- unit = models.ForeignKey(
- WeightUnit,
- verbose_name=_('Weight unit'),
- on_delete=models.CASCADE,
- )
-
- gram = models.IntegerField(verbose_name=_('Amount in grams'))
- amount = models.DecimalField(
- decimal_places=2,
- max_digits=5,
- default=1,
- verbose_name=_('Amount'),
- help_text=_('Unit amount, e.g. "1 Cup" or "1/2 spoon"'),
- )
-
- def get_owner_object(self):
- """
- Weight unit has no owner information
- """
- return None
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
-
- return "{0}{1} ({2}g)".format(
- self.amount if self.amount > 1 else '',
- self.unit.name,
- self.gram,
- )
-
-
-class Meal(models.Model):
- """
- A meal
- """
-
- # Metaclass to set some other properties
- class Meta:
- ordering = [
- "time",
- ]
-
- plan = models.ForeignKey(
- NutritionPlan,
- verbose_name=_('Nutrition plan'),
- editable=False,
- on_delete=models.CASCADE,
- )
- order = models.IntegerField(
- verbose_name=_('Order'),
- blank=True,
- editable=False,
- )
- time = Html5TimeField(
- null=True,
- blank=True,
- verbose_name=_('Time (approx)'),
- )
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return "{0} Meal".format(self.order)
-
- def get_owner_object(self):
- """
- Returns the object that has owner information
- """
- return self.plan
-
- def get_nutritional_values(self, use_metric=True):
- """
- Sums the nutrional info of all items in the meal
-
- :param use_metric Flag that controls the units used
- """
- nutritional_info = {
- 'energy': 0,
- 'protein': 0,
- 'carbohydrates': 0,
- 'carbohydrates_sugar': 0,
- 'fat': 0,
- 'fat_saturated': 0,
- 'fibres': 0,
- 'sodium': 0
- }
-
- # Get the calculated values from the meal item and add them
- for item in self.mealitem_set.select_related():
-
- values = item.get_nutritional_values(use_metric=use_metric)
- for key in nutritional_info.keys():
- nutritional_info[key] += values[key]
-
- nutritional_info['energy_kilojoule'] = Decimal(nutritional_info['energy']) * Decimal(4.184)
-
- # Only 2 decimal places, anything else doesn't make sense
- for i in nutritional_info:
- nutritional_info[i] = Decimal(nutritional_info[i]).quantize(TWOPLACES)
-
- return nutritional_info
-
-
-class BaseMealItem(object):
- """
- Base class for an item (component) of a meal or log
-
- This just provides some common helper functions
- """
-
- def get_unit_type(self):
- """
- Returns the type of unit used:
- - a value in grams
- - a 'human' unit like 'a cup' or 'a slice'
- """
-
- if self.weight_unit:
- return MEALITEM_WEIGHT_UNIT
- else:
- return MEALITEM_WEIGHT_GRAM
-
- def get_nutritional_values(self, use_metric=True):
- """
- Sums the nutritional info for the ingredient in the MealItem
-
- :param use_metric Flag that controls the units used
- """
- nutritional_info = {
- 'energy': 0,
- 'protein': 0,
- 'carbohydrates': 0,
- 'carbohydrates_sugar': 0,
- 'fat': 0,
- 'fat_saturated': 0,
- 'fibres': 0,
- 'sodium': 0
- }
- # Calculate the base weight of the item
- if self.get_unit_type() == MEALITEM_WEIGHT_GRAM:
- item_weight = self.amount
- else:
- item_weight = (self.amount * self.weight_unit.amount * self.weight_unit.gram)
-
- nutritional_info['energy'] += self.ingredient.energy * item_weight / 100
- nutritional_info['protein'] += self.ingredient.protein * item_weight / 100
- nutritional_info['carbohydrates'] += self.ingredient.carbohydrates * item_weight / 100
- nutritional_info['fat'] += self.ingredient.fat * item_weight / 100
-
- if self.ingredient.carbohydrates_sugar:
- nutritional_info['carbohydrates_sugar'] += \
- self.ingredient.carbohydrates_sugar * item_weight / 100
-
- if self.ingredient.fat_saturated:
- nutritional_info['fat_saturated'] += self.ingredient.fat_saturated * item_weight / 100
-
- if self.ingredient.fibres:
- nutritional_info['fibres'] += self.ingredient.fibres * item_weight / 100
-
- if self.ingredient.sodium:
- nutritional_info['sodium'] += self.ingredient.sodium * item_weight / 100
-
- # If necessary, convert weight units
- if not use_metric:
- for key, value in nutritional_info.items():
-
- # Energy is not a weight!
- if key == 'energy':
- continue
-
- # Everything else, to ounces
- nutritional_info[key] = AbstractWeight(value, 'g').oz
-
- nutritional_info['energy_kilojoule'] = Decimal(nutritional_info['energy']) * Decimal(4.184)
-
- # Only 2 decimal places, anything else doesn't make sense
- for i in nutritional_info:
- nutritional_info[i] = Decimal(nutritional_info[i]).quantize(TWOPLACES)
-
- return nutritional_info
-
-
-class MealItem(BaseMealItem, models.Model):
- """
- An item (component) of a meal
- """
-
- meal = models.ForeignKey(
- Meal,
- verbose_name=_('Nutrition plan'),
- editable=False,
- on_delete=models.CASCADE,
- )
- ingredient = models.ForeignKey(
- Ingredient,
- verbose_name=_('Ingredient'),
- on_delete=models.CASCADE,
- )
- weight_unit = models.ForeignKey(
- IngredientWeightUnit,
- verbose_name=_('Weight unit'),
- null=True,
- blank=True,
- on_delete=models.CASCADE,
- )
-
- order = models.IntegerField(
- verbose_name=_('Order'),
- blank=True,
- editable=False,
- )
- amount = models.DecimalField(
- decimal_places=2,
- max_digits=6,
- verbose_name=_('Amount'),
- validators=[MinValueValidator(1), MaxValueValidator(1000)],
- )
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return "{0}g ingredient {1}".format(self.amount, self.ingredient_id)
-
- def get_owner_object(self):
- """
- Returns the object that has owner information
- """
- return self.meal.plan
-
-
-class LogItem(BaseMealItem, models.Model):
- """
- An item (component) of a log
- """
-
- # Metaclass to set some other properties
- class Meta:
- ordering = [
- "datetime",
- ]
-
- plan = models.ForeignKey(
- NutritionPlan,
- verbose_name=_('Nutrition plan'),
- on_delete=models.CASCADE,
- )
- """
- The plan this log belongs to
- """
-
- datetime = models.DateTimeField(default=timezone.now)
- """
- Time and date when the log was added
- """
-
- comment = models.TextField(
- verbose_name=_('Comment'),
- blank=True,
- null=True,
- )
- """
- Comment field, for additional information
- """
-
- ingredient = models.ForeignKey(
- Ingredient,
- verbose_name=_('Ingredient'),
- on_delete=models.CASCADE,
- )
- """
- Ingredient
- """
-
- weight_unit = models.ForeignKey(
- IngredientWeightUnit,
- verbose_name=_('Weight unit'),
- null=True,
- blank=True,
- on_delete=models.CASCADE,
- )
- """
- Weight unit used (grams, slices, etc.)
- """
-
- amount = models.DecimalField(
- decimal_places=2,
- max_digits=6,
- verbose_name=_('Amount'),
- validators=[MinValueValidator(1), MaxValueValidator(1000)],
- )
- """
- The amount of units
- """
-
- def __str__(self):
- """
- Return a more human-readable representation
- """
- return "Diary entry for {}, plan {}".format(self.datetime, self.plan.pk)
-
- def get_owner_object(self):
- """
- Returns the object that has owner information
- """
- return self.plan
diff --git a/wger/nutrition/models/__init__.py b/wger/nutrition/models/__init__.py
new file mode 100644
index 000000000..b9455d3c0
--- /dev/null
+++ b/wger/nutrition/models/__init__.py
@@ -0,0 +1,25 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Local
+from .ingredient import Ingredient
+from .ingredient_category import IngredientCategory
+from .ingredient_weight_unit import IngredientWeightUnit
+from .log import LogItem
+from .meal import Meal
+from .meal_item import MealItem
+from .plan import NutritionPlan
+from .weight_unit import WeightUnit
diff --git a/wger/nutrition/models/ingredient.py b/wger/nutrition/models/ingredient.py
new file mode 100644
index 000000000..cf8b6a38b
--- /dev/null
+++ b/wger/nutrition/models/ingredient.py
@@ -0,0 +1,402 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Standard Library
+import logging
+from decimal import Decimal
+
+# Django
+from django.conf import settings
+from django.contrib.auth.models import User
+from django.contrib.sites.models import Site
+from django.core import mail
+from django.core.cache import cache
+from django.core.exceptions import ValidationError
+from django.core.validators import (
+ MaxValueValidator,
+ MinLengthValidator,
+ MinValueValidator,
+)
+from django.db import models
+from django.template.loader import render_to_string
+from django.urls import reverse
+from django.utils import translation
+from django.utils.text import slugify
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.core.models import Language
+from wger.utils.cache import cache_mapper
+from wger.utils.constants import TWOPLACES
+from wger.utils.managers import SubmissionManager
+from wger.utils.models import (
+ AbstractLicenseModel,
+ AbstractSubmissionModel,
+)
+
+# Local
+from ..consts import ENERGY_FACTOR
+from .ingredient_category import IngredientCategory
+
+logger = logging.getLogger(__name__)
+
+
+class Ingredient(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
+ """
+ An ingredient, with some approximate nutrition values
+ """
+ objects = SubmissionManager()
+ """Custom manager"""
+
+ ENERGY_APPROXIMATION = 15
+ """
+ How much the calculated energy from protein, etc. can deviate from the
+ energy amount given (in percent).
+ """
+
+ # Metaclass to set some other properties
+ class Meta:
+ ordering = [
+ "name",
+ ]
+
+ # Meta data
+ language = models.ForeignKey(
+ Language,
+ verbose_name=_('Language'),
+ editable=False,
+ on_delete=models.CASCADE,
+ )
+
+ creation_date = models.DateField(_('Date'), auto_now_add=True)
+ update_date = models.DateField(
+ _('Date'),
+ auto_now=True,
+ blank=True,
+ editable=False,
+ )
+
+ # Product infos
+ name = models.CharField(
+ max_length=200,
+ verbose_name=_('Name'),
+ validators=[MinLengthValidator(3)],
+ )
+
+ energy = models.IntegerField(verbose_name=_('Energy'), help_text=_('In kcal per 100g'))
+
+ protein = models.DecimalField(
+ decimal_places=3,
+ max_digits=6,
+ verbose_name=_('Protein'),
+ help_text=_('In g per 100g of product'),
+ validators=[MinValueValidator(0), MaxValueValidator(100)],
+ )
+
+ carbohydrates = models.DecimalField(
+ decimal_places=3,
+ max_digits=6,
+ verbose_name=_('Carbohydrates'),
+ help_text=_('In g per 100g of product'),
+ validators=[MinValueValidator(0), MaxValueValidator(100)],
+ )
+
+ carbohydrates_sugar = models.DecimalField(
+ decimal_places=3,
+ max_digits=6,
+ blank=True,
+ null=True,
+ verbose_name=_('Sugar content in carbohydrates'),
+ help_text=_('In g per 100g of product'),
+ validators=[MinValueValidator(0), MaxValueValidator(100)],
+ )
+
+ fat = models.DecimalField(
+ decimal_places=3,
+ max_digits=6,
+ verbose_name=_('Fat'),
+ help_text=_('In g per 100g of product'),
+ validators=[MinValueValidator(0), MaxValueValidator(100)],
+ )
+
+ fat_saturated = models.DecimalField(
+ decimal_places=3,
+ max_digits=6,
+ blank=True,
+ null=True,
+ verbose_name=_('Saturated fat content in fats'),
+ help_text=_('In g per 100g of product'),
+ validators=[MinValueValidator(0), MaxValueValidator(100)],
+ )
+
+ fibres = models.DecimalField(
+ decimal_places=3,
+ max_digits=6,
+ blank=True,
+ null=True,
+ verbose_name=_('Fibres'),
+ help_text=_('In g per 100g of product'),
+ validators=[MinValueValidator(0), MaxValueValidator(100)],
+ )
+
+ sodium = models.DecimalField(
+ decimal_places=3,
+ max_digits=6,
+ blank=True,
+ null=True,
+ verbose_name=_('Sodium'),
+ help_text=_('In g per 100g of product'),
+ validators=[MinValueValidator(0), MaxValueValidator(100)],
+ )
+
+ code = models.CharField(
+ max_length=200,
+ null=True,
+ blank=True,
+ db_index=True,
+ )
+ """Internal ID of the source database, e.g. a barcode or similar"""
+
+ source_name = models.CharField(
+ max_length=200,
+ null=True,
+ blank=True,
+ )
+ """Name of the source, such as Open Food Facts"""
+
+ source_url = models.URLField(
+ verbose_name=_('Link'),
+ help_text=_('Link to product'),
+ blank=True,
+ null=True,
+ )
+ """URL of the product at the source"""
+
+ last_imported = models.DateTimeField(
+ _('Date'),
+ auto_now_add=True,
+ null=True,
+ blank=True,
+ )
+
+ common_name = models.CharField(
+ max_length=200,
+ null=True,
+ blank=True,
+ )
+
+ category = models.ForeignKey(
+ IngredientCategory,
+ verbose_name=_('Category'),
+ on_delete=models.CASCADE,
+ null=True,
+ blank=True,
+ )
+
+ brand = models.CharField(
+ max_length=200,
+ verbose_name=_('Brand name of product'),
+ null=True,
+ blank=True,
+ )
+
+ #
+ # Django methods
+ #
+
+ def get_absolute_url(self):
+ """
+ Returns the canonical URL to view this object.
+
+ Since some names consist of only non-ascii characters (e.g. 감자깡), the
+ resulting slug would be empty and no URL would match. In that case, use
+ the regular URL with only the ID.
+ """
+ slug = slugify(self.name)
+ if not slug:
+ return reverse('nutrition:ingredient:view', kwargs={'id': self.id})
+ else:
+ return reverse('nutrition:ingredient:view', kwargs={'id': self.id, 'slug': slug})
+
+ def clean(self):
+ """
+ Do a very broad sanity check on the nutritional values according to
+ the following rules:
+ - 1g of protein: 4kcal
+ - 1g of carbohydrates: 4kcal
+ - 1g of fat: 9kcal
+
+ The sum is then compared to the given total energy, with ENERGY_APPROXIMATION
+ percent tolerance.
+ """
+
+ # Note: calculations in 100 grams, to save us the '/100' everywhere
+ energy_protein = 0
+ if self.protein:
+ energy_protein = self.protein * ENERGY_FACTOR['protein']['kg']
+
+ energy_carbohydrates = 0
+ if self.carbohydrates:
+ energy_carbohydrates = self.carbohydrates * ENERGY_FACTOR['carbohydrates']['kg']
+
+ energy_fat = 0
+ if self.fat:
+ # TODO: for some reason, during the tests the fat value is not
+ # converted to decimal (django 1.9)
+ energy_fat = Decimal(self.fat * ENERGY_FACTOR['fat']['kg'])
+
+ energy_calculated = energy_protein + energy_carbohydrates + energy_fat
+
+ # Compare the values, but be generous
+ if self.energy:
+ energy_upper = self.energy * (1 + (self.ENERGY_APPROXIMATION / Decimal(100.0)))
+ energy_lower = self.energy * (1 - (self.ENERGY_APPROXIMATION / Decimal(100.0)))
+
+ if not ((energy_upper > energy_calculated) and (energy_calculated > energy_lower)):
+ raise ValidationError(
+ _(
+ 'The total energy ({energy}kcal) is not the approximate sum of the '
+ 'energy provided by protein, carbohydrates and fat ({energy_calculated}kcal '
+ '+/-{energy_approx}%)'.format(
+ energy=self.energy,
+ energy_calculated=energy_calculated,
+ energy_approx=self.ENERGY_APPROXIMATION
+ )
+ )
+ )
+
+ def save(self, *args, **kwargs):
+ """
+ Reset the cache
+ """
+
+ super(Ingredient, self).save(*args, **kwargs)
+ cache.delete(cache_mapper.get_ingredient_key(self.id))
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return self.name
+
+ def __eq__(self, other):
+ """
+ Compare ingredients based on their values, not like django on their PKs
+ """
+
+ logger.debug('Overwritten behaviour: comparing ingredients on values, not PK.')
+ equal = True
+ if isinstance(other, self.__class__):
+ for i in self._meta.fields:
+ if (
+ hasattr(self, i.name) and hasattr(other, i.name)
+ and (getattr(self, i.name, None) != getattr(other, i.name, None))
+ ):
+ equal = False
+ else:
+ equal = False
+ return equal
+
+ def __hash__(self):
+ """
+ Define a hash function
+
+ This is rather unnecessary, but it seems that newer versions of django
+ have a problem when the __eq__ function is implemented, but not the
+ __hash__ one. Returning hash(pk) is also django's default.
+
+ :return: hash(pk)
+ """
+ return hash(self.pk)
+
+ #
+ # Own methods
+ #
+ def compare_with_database(self):
+ """
+ Compares the current ingredient with the version saved in the database.
+
+ If the current object has no PK, returns false
+ """
+ if not self.pk:
+ return False
+
+ ingredient = Ingredient.objects.get(pk=self.pk)
+ if self != ingredient:
+ return False
+ else:
+ return True
+
+ def send_email(self, request):
+ """
+ Sends an email after being successfully added to the database (for user
+ submitted ingredients only)
+ """
+ try:
+ user = User.objects.get(username=self.license_author)
+ except User.DoesNotExist:
+ return
+
+ if self.license_author and user.email:
+ translation.activate(user.userprofile.notification_language.short_name)
+ url = request.build_absolute_uri(self.get_absolute_url())
+ subject = _('Ingredient was successfully added to the general database')
+ context = {
+ 'ingredient': self.name,
+ 'url': url,
+ 'site': Site.objects.get_current().domain
+ }
+ message = render_to_string('ingredient/email_new.tpl', context)
+ mail.send_mail(
+ subject,
+ message,
+ settings.WGER_SETTINGS['EMAIL_FROM'], [user.email],
+ fail_silently=True
+ )
+
+ def set_author(self, request):
+ if request.user.has_perm('nutrition.add_ingredient'):
+ self.status = Ingredient.STATUS_ACCEPTED
+ if not self.license_author:
+ self.license_author = request.get_host().split(':')[0]
+ else:
+ if not self.license_author:
+ self.license_author = request.user.username
+
+ # Send email to administrator
+ subject = _('New user submitted ingredient')
+ message = _(
+ """The user {0} submitted a new ingredient "{1}".""".format(
+ request.user.username, self.name
+ )
+ )
+ mail.mail_admins(subject, message, fail_silently=True)
+
+ def get_owner_object(self):
+ """
+ Ingredient has no owner information
+ """
+ return False
+
+ @property
+ def energy_kilojoule(self):
+ """
+ returns kilojoules for current ingredient, 0 if energy is uninitialized
+ """
+ if self.energy:
+ return Decimal(self.energy * 4.184).quantize(TWOPLACES)
+ else:
+ return 0
diff --git a/wger/nutrition/models/ingredient_category.py b/wger/nutrition/models/ingredient_category.py
new file mode 100644
index 000000000..040f120ff
--- /dev/null
+++ b/wger/nutrition/models/ingredient_category.py
@@ -0,0 +1,45 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+
+class IngredientCategory(models.Model):
+ """
+ Model for an Ingredient category
+ """
+ name = models.CharField(max_length=100, verbose_name=_('Name'))
+
+ # Metaclass to set some other properties
+ class Meta:
+ verbose_name_plural = _("Ingredient Categories")
+ ordering = [
+ "name",
+ ]
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return self.name
+
+ def get_owner_object(self):
+ """
+ Category has no owner information
+ """
+ return False
diff --git a/wger/nutrition/models/ingredient_weight_unit.py b/wger/nutrition/models/ingredient_weight_unit.py
new file mode 100644
index 000000000..c458529bb
--- /dev/null
+++ b/wger/nutrition/models/ingredient_weight_unit.py
@@ -0,0 +1,72 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Standard Library
+import logging
+
+# Django
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# Local
+from .ingredient import Ingredient
+from .weight_unit import WeightUnit
+
+logger = logging.getLogger(__name__)
+
+
+class IngredientWeightUnit(models.Model):
+ """
+ A specific human usable weight unit for an ingredient
+ """
+
+ ingredient = models.ForeignKey(
+ Ingredient,
+ verbose_name=_('Ingredient'),
+ editable=False,
+ on_delete=models.CASCADE,
+ )
+ unit = models.ForeignKey(
+ WeightUnit,
+ verbose_name=_('Weight unit'),
+ on_delete=models.CASCADE,
+ )
+
+ gram = models.IntegerField(verbose_name=_('Amount in grams'))
+ amount = models.DecimalField(
+ decimal_places=2,
+ max_digits=5,
+ default=1,
+ verbose_name=_('Amount'),
+ help_text=_('Unit amount, e.g. "1 Cup" or "1/2 spoon"'),
+ )
+
+ def get_owner_object(self):
+ """
+ Weight unit has no owner information
+ """
+ return None
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+
+ return "{0}{1} ({2}g)".format(
+ self.amount if self.amount > 1 else '',
+ self.unit.name,
+ self.gram,
+ )
diff --git a/wger/nutrition/models/log.py b/wger/nutrition/models/log.py
new file mode 100644
index 000000000..48c55f719
--- /dev/null
+++ b/wger/nutrition/models/log.py
@@ -0,0 +1,109 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.core.validators import (
+ MaxValueValidator,
+ MinValueValidator,
+)
+from django.db import models
+from django.utils import timezone
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.nutrition.helpers import BaseMealItem
+
+# Local
+from .ingredient import Ingredient
+from .ingredient_weight_unit import IngredientWeightUnit
+from .plan import NutritionPlan
+
+
+class LogItem(BaseMealItem, models.Model):
+ """
+ An item (component) of a log
+ """
+
+ # Metaclass to set some other properties
+ class Meta:
+ ordering = [
+ "datetime",
+ ]
+
+ plan = models.ForeignKey(
+ NutritionPlan,
+ verbose_name=_('Nutrition plan'),
+ on_delete=models.CASCADE,
+ )
+ """
+ The plan this log belongs to
+ """
+
+ datetime = models.DateTimeField(default=timezone.now)
+ """
+ Time and date when the log was added
+ """
+
+ comment = models.TextField(
+ verbose_name=_('Comment'),
+ blank=True,
+ null=True,
+ )
+ """
+ Comment field, for additional information
+ """
+
+ ingredient = models.ForeignKey(
+ Ingredient,
+ verbose_name=_('Ingredient'),
+ on_delete=models.CASCADE,
+ )
+ """
+ Ingredient
+ """
+
+ weight_unit = models.ForeignKey(
+ IngredientWeightUnit,
+ verbose_name=_('Weight unit'),
+ null=True,
+ blank=True,
+ on_delete=models.CASCADE,
+ )
+ """
+ Weight unit used (grams, slices, etc.)
+ """
+
+ amount = models.DecimalField(
+ decimal_places=2,
+ max_digits=6,
+ verbose_name=_('Amount'),
+ validators=[MinValueValidator(1), MaxValueValidator(1000)],
+ )
+ """
+ The amount of units
+ """
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return "Diary entry for {}, plan {}".format(self.datetime, self.plan.pk)
+
+ def get_owner_object(self):
+ """
+ Returns the object that has owner information
+ """
+ return self.plan
diff --git a/wger/nutrition/models/meal.py b/wger/nutrition/models/meal.py
new file mode 100644
index 000000000..fa931dd76
--- /dev/null
+++ b/wger/nutrition/models/meal.py
@@ -0,0 +1,105 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Standard Library
+import logging
+from decimal import Decimal
+
+# Django
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.utils.constants import TWOPLACES
+from wger.utils.fields import Html5TimeField
+
+# Local
+from .plan import NutritionPlan
+
+logger = logging.getLogger(__name__)
+
+
+class Meal(models.Model):
+ """
+ A meal
+ """
+
+ # Metaclass to set some other properties
+ class Meta:
+ ordering = [
+ "time",
+ ]
+
+ plan = models.ForeignKey(
+ NutritionPlan,
+ verbose_name=_('Nutrition plan'),
+ editable=False,
+ on_delete=models.CASCADE,
+ )
+ order = models.IntegerField(
+ verbose_name=_('Order'),
+ blank=True,
+ editable=False,
+ )
+ time = Html5TimeField(
+ null=True,
+ blank=True,
+ verbose_name=_('Time (approx)'),
+ )
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return "{0} Meal".format(self.order)
+
+ def get_owner_object(self):
+ """
+ Returns the object that has owner information
+ """
+ return self.plan
+
+ def get_nutritional_values(self, use_metric=True):
+ """
+ Sums the nutrional info of all items in the meal
+
+ :param use_metric Flag that controls the units used
+ """
+ nutritional_info = {
+ 'energy': 0,
+ 'protein': 0,
+ 'carbohydrates': 0,
+ 'carbohydrates_sugar': 0,
+ 'fat': 0,
+ 'fat_saturated': 0,
+ 'fibres': 0,
+ 'sodium': 0
+ }
+
+ # Get the calculated values from the meal item and add them
+ for item in self.mealitem_set.select_related():
+
+ values = item.get_nutritional_values(use_metric=use_metric)
+ for key in nutritional_info.keys():
+ nutritional_info[key] += values[key]
+
+ nutritional_info['energy_kilojoule'] = Decimal(nutritional_info['energy']) * Decimal(4.184)
+
+ # Only 2 decimal places, anything else doesn't make sense
+ for i in nutritional_info:
+ nutritional_info[i] = Decimal(nutritional_info[i]).quantize(TWOPLACES)
+
+ return nutritional_info
diff --git a/wger/nutrition/models/meal_item.py b/wger/nutrition/models/meal_item.py
new file mode 100644
index 000000000..8f31152bb
--- /dev/null
+++ b/wger/nutrition/models/meal_item.py
@@ -0,0 +1,85 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Standard Library
+import logging
+
+# Django
+from django.core.validators import (
+ MaxValueValidator,
+ MinValueValidator,
+)
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.nutrition.helpers import BaseMealItem
+
+# Local
+from .ingredient import Ingredient
+from .ingredient_weight_unit import IngredientWeightUnit
+from .meal import Meal
+
+logger = logging.getLogger(__name__)
+
+
+class MealItem(BaseMealItem, models.Model):
+ """
+ An item (component) of a meal
+ """
+
+ meal = models.ForeignKey(
+ Meal,
+ verbose_name=_('Nutrition plan'),
+ editable=False,
+ on_delete=models.CASCADE,
+ )
+ ingredient = models.ForeignKey(
+ Ingredient,
+ verbose_name=_('Ingredient'),
+ on_delete=models.CASCADE,
+ )
+ weight_unit = models.ForeignKey(
+ IngredientWeightUnit,
+ verbose_name=_('Weight unit'),
+ null=True,
+ blank=True,
+ on_delete=models.CASCADE,
+ )
+
+ order = models.IntegerField(
+ verbose_name=_('Order'),
+ blank=True,
+ editable=False,
+ )
+ amount = models.DecimalField(
+ decimal_places=2,
+ max_digits=6,
+ verbose_name=_('Amount'),
+ validators=[MinValueValidator(1), MaxValueValidator(1000)],
+ )
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return "{0}g ingredient {1}".format(self.amount, self.ingredient_id)
+
+ def get_owner_object(self):
+ """
+ Returns the object that has owner information
+ """
+ return self.meal.plan
diff --git a/wger/nutrition/models/plan.py b/wger/nutrition/models/plan.py
new file mode 100644
index 000000000..668ecc8c5
--- /dev/null
+++ b/wger/nutrition/models/plan.py
@@ -0,0 +1,249 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Standard Library
+import datetime
+import logging
+from decimal import Decimal
+
+# Django
+from django.contrib.auth.models import User
+from django.core.cache import cache
+from django.db import models
+from django.urls import reverse
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.core.models import Language
+from wger.nutrition.consts import ENERGY_FACTOR
+from wger.utils.cache import cache_mapper
+from wger.utils.constants import TWOPLACES
+from wger.weight.models import WeightEntry
+
+logger = logging.getLogger(__name__)
+
+
+class NutritionPlan(models.Model):
+ """
+ A nutrition plan
+ """
+
+ # Metaclass to set some other properties
+ class Meta:
+
+ # Order by creation_date, descending (oldest first)
+ ordering = [
+ "-creation_date",
+ ]
+
+ user = models.ForeignKey(
+ User,
+ verbose_name=_('User'),
+ editable=False,
+ on_delete=models.CASCADE,
+ )
+ language = models.ForeignKey(
+ Language,
+ verbose_name=_('Language'),
+ editable=False,
+ on_delete=models.CASCADE,
+ )
+ creation_date = models.DateField(_('Creation date'), auto_now_add=True)
+ description = models.CharField(
+ max_length=80,
+ blank=True,
+ verbose_name=_('Description'),
+ help_text=_(
+ 'A description of the goal of the plan, e.g. '
+ '"Gain mass" or "Prepare for summer"'
+ ),
+ )
+ has_goal_calories = models.BooleanField(
+ verbose_name=_('Use daily calories'),
+ default=False,
+ help_text=_(
+ "Tick the box if you want to mark this "
+ "plan as having a goal amount of calories. "
+ "You can use the calculator or enter the "
+ "value yourself."
+ ),
+ )
+ """A flag indicating whether the plan has a goal amount of calories"""
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ if self.description:
+ return "{0}".format(self.description)
+ else:
+ return "{0}".format(_("Nutrition plan"))
+
+ def get_absolute_url(self):
+ """
+ Returns the canonical URL to view this object
+ """
+ return reverse('nutrition:plan:view', kwargs={'id': self.id})
+
+ def get_nutritional_values(self):
+ """
+ Sums the nutritional info of all items in the plan
+ """
+ nutritional_representation = cache.get(cache_mapper.get_nutrition_cache_by_key(self.pk))
+ if not nutritional_representation:
+ use_metric = self.user.userprofile.use_metric
+ unit = 'kg' if use_metric else 'lb'
+ result = {
+ 'total': {
+ 'energy': 0,
+ 'protein': 0,
+ 'carbohydrates': 0,
+ 'carbohydrates_sugar': 0,
+ 'fat': 0,
+ 'fat_saturated': 0,
+ 'fibres': 0,
+ 'sodium': 0
+ },
+ 'percent': {
+ 'protein': 0,
+ 'carbohydrates': 0,
+ 'fat': 0
+ },
+ 'per_kg': {
+ 'protein': 0,
+ 'carbohydrates': 0,
+ 'fat': 0
+ },
+ }
+
+ # Energy
+ for meal in self.meal_set.select_related():
+ values = meal.get_nutritional_values(use_metric=use_metric)
+ for key in result['total'].keys():
+ result['total'][key] += values[key]
+
+ energy = result['total']['energy']
+ result['total']['energy_kilojoule'] = result['total']['energy'] * Decimal(4.184)
+
+ # In percent
+ if energy:
+ for key in result['percent'].keys():
+ result['percent'][key] = \
+ result['total'][key] * ENERGY_FACTOR[key][unit] / energy * 100
+
+ # Per body weight
+ weight_entry = self.get_closest_weight_entry()
+ if weight_entry:
+ for key in result['per_kg'].keys():
+ result['per_kg'][key] = result['total'][key] / weight_entry.weight
+
+ # Only 2 decimal places, anything else doesn't make sense
+ for key in result.keys():
+ for i in result[key]:
+ result[key][i] = Decimal(result[key][i]).quantize(TWOPLACES)
+ nutritional_representation = result
+ cache.set(cache_mapper.get_nutrition_cache_by_key(self.pk), nutritional_representation)
+ return nutritional_representation
+
+ def get_closest_weight_entry(self):
+ """
+ Returns the closest weight entry for the nutrition plan.
+ Returns None if there are no entries.
+ """
+ target = self.creation_date
+ closest_entry_gte = WeightEntry.objects.filter(user=self.user) \
+ .filter(date__gte=target).order_by('date').first()
+ closest_entry_lte = WeightEntry.objects.filter(user=self.user) \
+ .filter(date__lte=target).order_by('-date').first()
+ if closest_entry_gte is None or closest_entry_lte is None:
+ return closest_entry_gte or closest_entry_lte
+ if abs(closest_entry_gte.date - target) < abs(closest_entry_lte.date - target):
+ return closest_entry_gte
+ else:
+ return closest_entry_lte
+
+ def get_owner_object(self):
+ """
+ Returns the object that has owner information
+ """
+ return self
+
+ def get_calories_approximation(self):
+ """
+ Calculates the deviation from the goal calories and the actual
+ amount of the current plan
+ """
+
+ goal_calories = self.user.userprofile.calories
+ actual_calories = self.get_nutritional_values()['total']['energy']
+
+ # Within 3%
+ if (actual_calories < goal_calories * 1.03) and (actual_calories > goal_calories * 0.97):
+ return 1
+ # within 7%
+ elif (actual_calories < goal_calories * 1.07) and (actual_calories > goal_calories * 0.93):
+ return 2
+ # within 10%
+ elif (actual_calories < goal_calories * 1.10) and (actual_calories > goal_calories * 0.9):
+ return 3
+ # even more
+ else:
+ return 4
+
+ def get_log_overview(self):
+ """
+ Returns an overview for all logs available for this plan
+ """
+ result = []
+ for date in self.logitem_set.datetimes('datetime', 'day', order='DESC'):
+ # TODO: in python 3.5 this can be simplified as z = {**x, **y}
+ tmp = self.get_log_summary(date=date).copy()
+ tmp.update({'date': date.date()})
+ result.append(tmp)
+
+ return result
+
+ def get_log_entries(self, date=None):
+ """
+ Convenience function that returns the log entries for a given date
+ """
+ if not date:
+ date = datetime.date.today()
+
+ return self.logitem_set.filter(datetime__date=date).select_related()
+
+ def get_log_summary(self, date=None):
+ """
+ Sums the nutritional info of the items logged for the given date
+ """
+ use_metric = self.user.userprofile.use_metric
+ result = {
+ 'energy': 0,
+ 'protein': 0,
+ 'carbohydrates': 0,
+ 'carbohydrates_sugar': 0,
+ 'fat': 0,
+ 'fat_saturated': 0,
+ 'fibres': 0,
+ 'sodium': 0
+ }
+
+ # Perform the sums
+ for item in self.get_log_entries(date):
+ values = item.get_nutritional_values(use_metric=use_metric)
+ for key in result.keys():
+ result[key] += values[key]
+ return result
diff --git a/wger/nutrition/models/weight_unit.py b/wger/nutrition/models/weight_unit.py
new file mode 100644
index 000000000..cfa5f27b9
--- /dev/null
+++ b/wger/nutrition/models/weight_unit.py
@@ -0,0 +1,57 @@
+# This file is part of wger Workout Manager <https://github.com/wger-project>.
+# Copyright (C) 2013 - 2021 wger Team
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# Django
+from django.db import models
+from django.utils.translation import gettext_lazy as _
+
+# wger
+from wger.core.models import Language
+
+
+class WeightUnit(models.Model):
+ """
+ A more human usable weight unit (spoon, table, slice...)
+ """
+
+ language = models.ForeignKey(
+ Language,
+ verbose_name=_('Language'),
+ editable=False,
+ on_delete=models.CASCADE,
+ )
+ name = models.CharField(
+ max_length=200,
+ verbose_name=_('Name'),
+ )
+
+ # Metaclass to set some other properties
+ class Meta:
+ ordering = [
+ "name",
+ ]
+
+ def __str__(self):
+ """
+ Return a more human-readable representation
+ """
+ return self.name
+
+ def get_owner_object(self):
+ """
+ Weight unit has no owner information
+ """
+ return None
diff --git a/wger/nutrition/views/plan.py b/wger/nutrition/views/plan.py
index 78bcf5ed4..dc31e9cd8 100644
--- a/wger/nutrition/views/plan.py
+++ b/wger/nutrition/views/plan.py
@@ -54,11 +54,11 @@ from reportlab.platypus import (
)
# wger
-from wger.nutrition.models import (
+from wger.nutrition.consts import (
MEALITEM_WEIGHT_GRAM,
MEALITEM_WEIGHT_UNIT,
- NutritionPlan,
)
+from wger.nutrition.models import NutritionPlan
from wger.utils.generic_views import (
WgerDeleteMixin,
WgerFormMixin,
@@ -76,7 +76,6 @@ from wger.utils.pdf import (
styleSheet,
)
-
logger = logging.getLogger(__name__)
# ************************