Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Remove "need_log_to_apply" field from SlotEntry

Roland Geider5751e0f2deeb
diff --git a/wger/core/api/serializers.py b/wger/core/api/serializers.py
index 03e1edd44..3c704023f 100644
--- a/wger/core/api/serializers.py
+++ b/wger/core/api/serializers.py
@@ -37,6 +37,7 @@ from wger.core.models import (
WeightUnit,
)
+
logger = logging.getLogger(__name__)
diff --git a/wger/core/templatetags/wger_extras.py b/wger/core/templatetags/wger_extras.py
index e6d3244f9..a916af906 100644
--- a/wger/core/templatetags/wger_extras.py
+++ b/wger/core/templatetags/wger_extras.py
@@ -34,6 +34,7 @@ from wger.utils.constants import (
)
from wger.utils.language import get_language_data
+
register = template.Library()
diff --git a/wger/exercises/api/views.py b/wger/exercises/api/views.py
index 39ff8d12c..eac7584bc 100644
--- a/wger/exercises/api/views.py
+++ b/wger/exercises/api/views.py
@@ -56,11 +56,11 @@ from wger.exercises.api.serializers import (
DeletionLogSerializer,
EquipmentSerializer,
ExerciseAliasSerializer,
- ExerciseInfoSerializer,
ExerciseBaseSerializer,
ExerciseCategorySerializer,
ExerciseCommentSerializer,
ExerciseImageSerializer,
+ ExerciseInfoSerializer,
ExerciseTranslationSerializer,
ExerciseVariationSerializer,
ExerciseVideoSerializer,
@@ -90,6 +90,7 @@ from wger.utils.constants import (
from wger.utils.db import is_postgres_db
from wger.utils.language import load_language
+
logger = logging.getLogger(__name__)
diff --git a/wger/exercises/migrations/0032_rename_exercise.py b/wger/exercises/migrations/0032_rename_exercise.py
index 1faa86fa8..23816196f 100644
--- a/wger/exercises/migrations/0032_rename_exercise.py
+++ b/wger/exercises/migrations/0032_rename_exercise.py
@@ -12,7 +12,6 @@ class Migration(migrations.Migration):
operations = [
# Rename exercise base to exercise and exercise to translation
-
migrations.RenameModel(
old_name='Exercise',
new_name='Translation',
@@ -29,80 +28,73 @@ class Migration(migrations.Migration):
old_name='HistoricalExerciseBase',
new_name='HistoricalExercise',
),
-
migrations.AlterModelOptions(
- name="historicalexercise",
+ name='historicalexercise',
options={
- "get_latest_by": ("history_date", "history_id"),
- "ordering": ("-history_date", "-history_id"),
- "verbose_name": "historical exercise",
- "verbose_name_plural": "historical exercises",
+ 'get_latest_by': ('history_date', 'history_id'),
+ 'ordering': ('-history_date', '-history_id'),
+ 'verbose_name': 'historical exercise',
+ 'verbose_name_plural': 'historical exercises',
},
),
migrations.AlterModelOptions(
- name="historicaltranslation",
+ name='historicaltranslation',
options={
- "get_latest_by": ("history_date", "history_id"),
- "ordering": ("-history_date", "-history_id"),
- "verbose_name": "historical translation",
- "verbose_name_plural": "historical translations",
+ 'get_latest_by': ('history_date', 'history_id'),
+ 'ordering': ('-history_date', '-history_id'),
+ 'verbose_name': 'historical translation',
+ 'verbose_name_plural': 'historical translations',
},
),
-
# Rename exercise base foreign keys
migrations.RenameField(
- model_name="exercisevideo",
- old_name="exercise_base",
- new_name="exercise",
+ model_name='exercisevideo',
+ old_name='exercise_base',
+ new_name='exercise',
),
migrations.RenameField(
- model_name="historicalexercisevideo",
- old_name="exercise_base",
- new_name="exercise",
+ model_name='historicalexercisevideo',
+ old_name='exercise_base',
+ new_name='exercise',
),
-
migrations.RenameField(
- model_name="exerciseimage",
- old_name="exercise_base",
- new_name="exercise",
+ model_name='exerciseimage',
+ old_name='exercise_base',
+ new_name='exercise',
),
migrations.RenameField(
- model_name="historicalexerciseimage",
- old_name="exercise_base",
- new_name="exercise",
+ model_name='historicalexerciseimage',
+ old_name='exercise_base',
+ new_name='exercise',
),
-
migrations.RenameField(
- model_name="translation",
- old_name="exercise_base",
- new_name="exercise",
+ model_name='translation',
+ old_name='exercise_base',
+ new_name='exercise',
),
migrations.RenameField(
- model_name="historicaltranslation",
- old_name="exercise_base",
- new_name="exercise",
+ model_name='historicaltranslation',
+ old_name='exercise_base',
+ new_name='exercise',
),
-
migrations.RenameField(
- model_name="alias",
- old_name="exercise",
- new_name="translation",
+ model_name='alias',
+ old_name='exercise',
+ new_name='translation',
),
migrations.RenameField(
- model_name="historicalalias",
- old_name="exercise",
- new_name="translation",
+ model_name='historicalalias',
+ old_name='exercise',
+ new_name='translation',
),
-
migrations.RenameField(
- model_name="exercisecomment",
- old_name="exercise",
- new_name="translation",
+ model_name='exercisecomment',
+ old_name='exercise',
+ new_name='translation',
),
migrations.RenameField(
- model_name="historicalexercisecomment",
- old_name="exercise",
- new_name="translation",
+ model_name='historicalexercisecomment',
+ old_name='exercise',
+ new_name='translation',
),
-
]
diff --git a/wger/exercises/models/image.py b/wger/exercises/models/image.py
index 9353fb030..1c4315ce3 100644
--- a/wger/exercises/models/image.py
+++ b/wger/exercises/models/image.py
@@ -164,17 +164,13 @@ class ExerciseImage(AbstractLicenseModel, AbstractHistoryMixin, models.Model, Ba
# Make sure there is always a main image
if (
- not ExerciseImage.objects.all()
- .filter(exercise=self.exercise, is_main=True)
- .count()
+ not ExerciseImage.objects.all().filter(exercise=self.exercise, is_main=True).count()
and ExerciseImage.objects.all()
.filter(exercise=self.exercise)
.filter(is_main=False)
.count()
):
- image = ExerciseImage.objects.all().filter(
- exercise=self.exercise, is_main=False
- )[0]
+ image = ExerciseImage.objects.all().filter(exercise=self.exercise, is_main=False)[0]
image.is_main = True
image.save()
diff --git a/wger/exercises/models/video.py b/wger/exercises/models/video.py
index c2dd1da4c..07efb2d2b 100644
--- a/wger/exercises/models/video.py
+++ b/wger/exercises/models/video.py
@@ -29,6 +29,7 @@ from simple_history.models import HistoricalRecords
# wger
from wger.utils.cache import reset_exercise_api_cache
+
try:
# Third Party
import ffmpeg
@@ -42,6 +43,7 @@ from wger.utils.models import (
AbstractLicenseModel,
)
+
MAX_FILE_SIZE_MB = 100
diff --git a/wger/exercises/sync.py b/wger/exercises/sync.py
index 7769aa13b..2e3e6c518 100644
--- a/wger/exercises/sync.py
+++ b/wger/exercises/sync.py
@@ -296,6 +296,7 @@ def handle_deleted_entries(
style_fn=lambda x: x,
):
if not print_fn:
+
def print_fn(_):
return None
diff --git a/wger/exercises/tests/test_exercise_images.py b/wger/exercises/tests/test_exercise_images.py
index 4cb85fca8..fd1c13d58 100644
--- a/wger/exercises/tests/test_exercise_images.py
+++ b/wger/exercises/tests/test_exercise_images.py
@@ -19,8 +19,9 @@ from django.core.files import File
from wger.core.tests import api_base_test
from wger.core.tests.base_testcase import WgerTestCase
from wger.exercises.models import (
+ Exercise,
ExerciseImage,
- Translation, Exercise,
+ Translation,
)
diff --git a/wger/exercises/urls.py b/wger/exercises/urls.py
index 268810745..aae5f6489 100644
--- a/wger/exercises/urls.py
+++ b/wger/exercises/urls.py
@@ -31,6 +31,7 @@ from wger.exercises.views import (
muscles,
)
+
# sub patterns for history
patterns_history = [
path('admin-control', history.control, name='overview'),
diff --git a/wger/manager/api/consts.py b/wger/manager/api/consts.py
index de036c02d..c231d839c 100644
--- a/wger/manager/api/consts.py
+++ b/wger/manager/api/consts.py
@@ -5,7 +5,6 @@ BASE_CONFIG_FILTER_FIELDS = (
'value',
'operation',
'step',
- 'need_log_to_apply',
'repeat',
)
diff --git a/wger/manager/api/serializers.py b/wger/manager/api/serializers.py
index 75d9c88d3..fd14522de 100644
--- a/wger/manager/api/serializers.py
+++ b/wger/manager/api/serializers.py
@@ -201,8 +201,7 @@ class SlotEntryStructureSerializer(serializers.ModelSerializer):
max_weight_configs = WeightConfigSerializer(source='maxweightconfig_set', many=True)
repetitions_configs = RepetitionsConfigSerializer(source='repetitionsconfig_set', many=True)
max_repetitions_configs = RepetitionsConfigSerializer(
- source='maxrepetitionsconfig_set',
- many=True
+ source='maxrepetitionsconfig_set', many=True
)
set_nr_configs = SetNrConfigSerializer(source='setsconfig_set', many=True)
max_set_nr_configs = MaxSetNrConfigSerializer(source='maxsetsconfig_set', many=True)
diff --git a/wger/manager/api/validators.py b/wger/manager/api/validators.py
index 150f3872b..140344a7e 100644
--- a/wger/manager/api/validators.py
+++ b/wger/manager/api/validators.py
@@ -17,6 +17,17 @@
from rest_framework import serializers
+REQUIREMENTS_REQUIRED_KEYS = [
+ 'rules',
+]
+REQUIREMENTS_RULES_KEYS = [
+ 'weight',
+ 'repetitions',
+ 'rir',
+ 'rest',
+]
+
+
def validate_requirements(value: dict | None):
"""Validates the requirements field."""
@@ -26,9 +37,12 @@ def validate_requirements(value: dict | None):
if not isinstance(value, dict):
raise serializers.ValidationError('Requirements must be a JSON object.')
- required_keys = {'rules'} # Set of required keys
- if not all(key in value for key in required_keys):
- raise serializers.ValidationError("Missing required keys: 'rules'") # More specific
+ if not all(key in value for key in REQUIREMENTS_REQUIRED_KEYS):
+ raise serializers.ValidationError("Missing required keys: 'rules'")
if 'rules' in value and not isinstance(value['rules'], list):
raise serializers.ValidationError("'rules' must be a list.")
+
+ for rule in value['rules']:
+ if rule not in REQUIREMENTS_RULES_KEYS:
+ raise serializers.ValidationError(f'Invalid rule: {rule}')
diff --git a/wger/manager/dataclasses.py b/wger/manager/dataclasses.py
index d666b0806..0e7b8d619 100644
--- a/wger/manager/dataclasses.py
+++ b/wger/manager/dataclasses.py
@@ -28,6 +28,7 @@ from decimal import (
)
from typing import (
Any,
+ Dict,
List,
)
@@ -45,10 +46,10 @@ from wger.core.models import (
class SetConfigData:
exercise: int
- weight: Decimal | int | None
- repetitions: Decimal | int | None
- rir: Decimal | int | None
- rest: int | None
+ weight: Decimal | int | None = None
+ repetitions: Decimal | int | None = None
+ rir: Decimal | int | None = None
+ rest: int | None = None
max_rir: Decimal | int | None = None
max_weight: Decimal | int | None = None
@@ -99,8 +100,9 @@ class SetConfigData:
if self.repetitions:
reps = round_value(self.repetitions, self.repetitions_rounding)
max_reps = (
- round_value(self.max_repetitions,
- self.repetitions_rounding) if self.max_repetitions else self.max_repetitions
+ round_value(self.max_repetitions, self.repetitions_rounding)
+ if self.max_repetitions
+ else self.max_repetitions
)
if max_reps:
@@ -243,3 +245,11 @@ def round_value(
result = result.quantize(1, ROUND_DOWN)
return result
+
+
+@dataclass(init=False)
+class ConfigRequirements:
+ rules: List[str] = field(default_factory=list)
+
+ def __init__(self, data: Dict[str, Any]):
+ self.rules = data.get('rules', [])
diff --git a/wger/manager/fixtures/test-routine-data.json b/wger/manager/fixtures/test-routine-data.json
index 6e117e79b..5501929d0 100644
--- a/wger/manager/fixtures/test-routine-data.json
+++ b/wger/manager/fixtures/test-routine-data.json
@@ -201,7 +201,6 @@
"value": 5,
"operation": "r",
"step": "abs",
- "need_log_to_apply": false,
"repeat": false
}
},
@@ -214,7 +213,6 @@
"value": 2,
"operation": "r",
"step": "abs",
- "need_log_to_apply": false,
"repeat": false
}
},
@@ -227,7 +225,6 @@
"value": 5,
"operation": "r",
"step": "abs",
- "need_log_to_apply": false,
"repeat": false
}
},
@@ -240,7 +237,6 @@
"value": 3,
"operation": "r",
"step": "abs",
- "need_log_to_apply": false,
"repeat": false
}
},
@@ -253,7 +249,6 @@
"value": 80,
"operation": "r",
"step": "abs",
- "need_log_to_apply": false,
"repeat": false
}
},
@@ -266,7 +261,6 @@
"value": 20,
"operation": "r",
"step": "abs",
- "need_log_to_apply": false,
"repeat": false
}
},
@@ -279,7 +273,6 @@
"value": 80,
"operation": "r",
"step": "abs",
- "need_log_to_apply": false,
"repeat": false
}
},
@@ -292,7 +285,6 @@
"value": 50,
"operation": "r",
"step": "abs",
- "need_log_to_apply": false,
"repeat": false
}
},
@@ -305,7 +297,6 @@
"value": 4,
"operation": "r",
"step": "abs",
- "need_log_to_apply": false,
"repeat": false
}
},
@@ -318,7 +309,6 @@
"value": 5,
"operation": "r",
"step": "abs",
- "need_log_to_apply": false,
"repeat": false
}
},
@@ -331,7 +321,6 @@
"value": 6,
"operation": "r",
"step": "abs",
- "need_log_to_apply": false,
"repeat": false
}
},
@@ -344,7 +333,6 @@
"value": 4,
"operation": "r",
"step": "abs",
- "need_log_to_apply": false,
"repeat": false
}
}
diff --git a/wger/manager/management/commands/dummy-generator-routines.py b/wger/manager/management/commands/dummy-generator-routines.py
index 0388ddcb6..33b6069d1 100644
--- a/wger/manager/management/commands/dummy-generator-routines.py
+++ b/wger/manager/management/commands/dummy-generator-routines.py
@@ -35,6 +35,7 @@ from wger.manager.models import (
)
from wger.manager.models.abstract_config import OperationChoices
+
logger = logging.getLogger(__name__)
diff --git a/wger/manager/management/commands/dummy-generator-workout-diary.py b/wger/manager/management/commands/dummy-generator-workout-diary.py
index 437166ef2..4cd683d28 100644
--- a/wger/manager/management/commands/dummy-generator-workout-diary.py
+++ b/wger/manager/management/commands/dummy-generator-workout-diary.py
@@ -29,6 +29,7 @@ from wger.manager.models import (
WorkoutSession,
)
+
logger = logging.getLogger(__name__)
@@ -106,34 +107,38 @@ class Command(BaseCommand):
date=day_data.date,
routine=routine,
defaults={
- 'impression': random.choice([
- WorkoutSession.IMPRESSION_GOOD,
- WorkoutSession.IMPRESSION_BAD,
- WorkoutSession.IMPRESSION_NEUTRAL,
- ]),
+ 'impression': random.choice(
+ [
+ WorkoutSession.IMPRESSION_GOOD,
+ WorkoutSession.IMPRESSION_BAD,
+ WorkoutSession.IMPRESSION_NEUTRAL,
+ ]
+ ),
'time_start': time_start,
'time_end': time_end,
},
)[0]
- logs.append(WorkoutLog(
- slot_entry_id=set_data.slot_entry_id,
- iteration=day_data.iteration,
- user=user,
- session=session,
- exercise_id=exercise_id,
- routine=routine,
- repetitions=reps,
- repetitions_target=set_data.repetitions,
- repetitions_unit_id=set_data.repetitions_unit,
- weight=weight,
- weight_target=set_data.weight,
- weight_unit_id=set_data.weight_unit,
- date=day_data.date,
- rir=rir,
- rir_target=set_data.rir,
- rest=rest,
- rest_target=set_data.rest,
- ))
+ logs.append(
+ WorkoutLog(
+ slot_entry_id=set_data.slot_entry_id,
+ iteration=day_data.iteration,
+ user=user,
+ session=session,
+ exercise_id=exercise_id,
+ routine=routine,
+ repetitions=reps,
+ repetitions_target=set_data.repetitions,
+ repetitions_unit_id=set_data.repetitions_unit,
+ weight=weight,
+ weight_target=set_data.weight,
+ weight_unit_id=set_data.weight_unit,
+ date=day_data.date,
+ rir=rir,
+ rir_target=set_data.rir,
+ rest=rest,
+ rest_target=set_data.rest,
+ )
+ )
WorkoutLog.objects.bulk_create(logs)
diff --git a/wger/manager/migrations/0018_flexible_routines.py b/wger/manager/migrations/0018_flexible_routines.py
index bef59a6fc..6179d195d 100644
--- a/wger/manager/migrations/0018_flexible_routines.py
+++ b/wger/manager/migrations/0018_flexible_routines.py
@@ -501,7 +501,6 @@ class Migration(migrations.Migration):
null=False,
),
),
- ('need_log_to_apply', models.BooleanField(default=False)),
('repeat', models.BooleanField(default=False)),
(
'slot_entry',
@@ -556,7 +555,6 @@ class Migration(migrations.Migration):
null=False,
),
),
- ('need_log_to_apply', models.BooleanField(default=False)),
('repeat', models.BooleanField(default=False)),
(
'slot_entry',
@@ -617,7 +615,6 @@ class Migration(migrations.Migration):
null=False,
),
),
- ('need_log_to_apply', models.BooleanField(default=False)),
('repeat', models.BooleanField(default=False)),
(
'slot_entry',
@@ -670,7 +667,6 @@ class Migration(migrations.Migration):
max_length=10,
),
),
- ('need_log_to_apply', models.BooleanField(default=False)),
('repeat', models.BooleanField(default=False)),
(
'value',
@@ -732,7 +728,6 @@ class Migration(migrations.Migration):
null=False,
),
),
- ('need_log_to_apply', models.BooleanField(default=False)),
('repeat', models.BooleanField(default=False)),
(
'slot_entry',
@@ -787,7 +782,6 @@ class Migration(migrations.Migration):
null=False,
),
),
- ('need_log_to_apply', models.BooleanField(default=False)),
('repeat', models.BooleanField(default=False)),
(
'slot_entry',
@@ -842,7 +836,6 @@ class Migration(migrations.Migration):
null=False,
),
),
- ('need_log_to_apply', models.BooleanField(default=False)),
('repeat', models.BooleanField(default=False)),
(
'slot_entry',
@@ -897,7 +890,6 @@ class Migration(migrations.Migration):
null=False,
),
),
- ('need_log_to_apply', models.BooleanField(default=False)),
('repeat', models.BooleanField(default=False)),
(
'slot_entry',
@@ -952,7 +944,6 @@ class Migration(migrations.Migration):
null=False,
),
),
- ('need_log_to_apply', models.BooleanField(default=False)),
('repeat', models.BooleanField(default=False)),
(
'slot_entry',
@@ -1006,7 +997,6 @@ class Migration(migrations.Migration):
max_length=10,
),
),
- ('need_log_to_apply', models.BooleanField(default=False)),
('repeat', models.BooleanField(default=False)),
(
'slot_entry',
diff --git a/wger/manager/models/abstract_config.py b/wger/manager/models/abstract_config.py
index 26518422b..f075bcdc6 100644
--- a/wger/manager/models/abstract_config.py
+++ b/wger/manager/models/abstract_config.py
@@ -17,6 +17,9 @@
# Django
from django.db import models
+# wger
+from wger.manager.dataclasses import ConfigRequirements
+
class OperationChoices(models.TextChoices):
PLUS = '+'
@@ -70,12 +73,6 @@ class AbstractChangeConfig(models.Model):
)
"""The step by which the change will happen"""
- need_log_to_apply = models.BooleanField(default=False)
- """
- Only apply the change if the user logged the last weight, otherwise
- apply the rules anyway
- """
-
repeat = models.BooleanField(default=False)
"""
This setting makes the current rule repeat for subsequent iterations until a
@@ -92,9 +89,11 @@ class AbstractChangeConfig(models.Model):
"""
Requirements for the application of this rule as JSON
- Currently supported:
- * list of rules to apply
- * respect/ignore maximum
+ Currently supported is only a list of fields that must be met in the logs in
+ order to continue.
+
+ See the `ConfigRequirements` class and `validate_requirements` for more
+ information on the structure.
"""
@property
@@ -105,6 +104,16 @@ class AbstractChangeConfig(models.Model):
"""
return self.operation == OperationChoices.REPLACE
+ @property
+ def requirements_object(self) -> ConfigRequirements | None:
+ """
+ Get the requirements as an object
+ """
+ if not self.requirements:
+ return None
+
+ return ConfigRequirements(self.requirements)
+
def save(self, **kwargs):
"""
Cleanup some combinations. While these would be ignored in the
@@ -117,7 +126,6 @@ class AbstractChangeConfig(models.Model):
# Override values for replace
if self.replace:
- self.need_log_to_apply = False
self.step = StepChoices.NOT_APPLICABLE
super().save(**kwargs)
diff --git a/wger/manager/models/log.py b/wger/manager/models/log.py
index 392f496f1..0721a103c 100644
--- a/wger/manager/models/log.py
+++ b/wger/manager/models/log.py
@@ -32,7 +32,7 @@ from wger.core.models import (
from wger.exercises.models import Exercise
from wger.manager.consts import (
ID_UNIT_KG,
- ID_UNIT_REPS,
+ ID_UNIT_REPETITIONS,
RIR_OPTIONS,
)
from wger.manager.managers import WorkoutLogManager
@@ -111,7 +111,7 @@ class WorkoutLog(models.Model):
repetitions_unit = models.ForeignKey(
RepetitionUnit,
verbose_name=_('Unit'),
- default=ID_UNIT_REPS,
+ default=ID_UNIT_REPETITIONS,
on_delete=models.CASCADE,
)
"""
@@ -119,7 +119,7 @@ class WorkoutLog(models.Model):
"""
repetitions = models.DecimalField(
- max_digits=5,
+ max_digits=6,
decimal_places=2,
validators=[NullMinValueValidator(0)],
blank=True,
@@ -130,7 +130,7 @@ class WorkoutLog(models.Model):
"""
repetitions_target = models.DecimalField(
- max_digits=5,
+ max_digits=6,
decimal_places=2,
verbose_name=_('Repetitions'),
validators=[NullMinValueValidator(0)],
@@ -152,7 +152,7 @@ class WorkoutLog(models.Model):
"""
weight = models.DecimalField(
- max_digits=5,
+ max_digits=6,
decimal_places=2,
validators=[NullMinValueValidator(0)],
blank=True,
@@ -163,7 +163,7 @@ class WorkoutLog(models.Model):
"""
weight_target = models.DecimalField(
- max_digits=5,
+ max_digits=6,
decimal_places=2,
verbose_name=_('Weight'),
validators=[NullMinValueValidator(0)],
diff --git a/wger/manager/models/slot_entry.py b/wger/manager/models/slot_entry.py
index 2cd843395..dbb45a0bf 100644
--- a/wger/manager/models/slot_entry.py
+++ b/wger/manager/models/slot_entry.py
@@ -155,7 +155,9 @@ class SlotEntry(models.Model):
# For new entries add default rounding if available
if not self.id:
if not self.repetition_rounding:
- self.repetition_rounding = self.slot.day.routine.user.userprofile.repetitions_rounding
+ self.repetition_rounding = (
+ self.slot.day.routine.user.userprofile.repetitions_rounding
+ )
if not self.weight_rounding:
self.weight_rounding = self.slot.day.routine.user.userprofile.weight_rounding
return super().save(*args, **kwargs)
@@ -210,6 +212,17 @@ class SlotEntry(models.Model):
return out
def get_config(self, iteration: int) -> SetConfigData:
+ """
+ This method calculates the configuration for a given iteration of a slot entry.
+
+ It processes each field (weight, repetitions, rir, rest, sets, etc.) individually
+ and for each one it checks if there are any requirements set (minimum values for other
+ fields) and checks if they are met by the logs of the previous iterations.
+
+ E.g. the weight could have the requirements of weight and weight. Only if these are
+ met, the weight will be increased.
+ """
+
# If there is a custom class set, pass all responsibilities to it
if self.class_name:
try:
@@ -235,61 +248,65 @@ class SlotEntry(models.Model):
return custom_logic.calculate()
- max_iter_weight = 1
- max_iter_max_weight = 1
- max_iter_reps = 1
- max_iter_max_reps = 1
-
- weight = self.calculate_weight(max_iter_weight)
- reps = self.calculate_reps(max_iter_reps)
+ max_iterations = {
+ 'weight': 1,
+ 'max_weight': 1,
+ 'repetitions': 1,
+ 'max_repetitions': 1,
+ 'rir': 1,
+ 'max_rir': 1,
+ 'rest': 1,
+ 'max_rest': 1,
+ 'sets': 1,
+ 'max_sets': 1,
+ }
- # Calculate the weights and reps. Note that we can't just take the configs
- # and calculate it like with the other values since these might depend on
- # logged values to continue. Because of this, we need to check step by step
- # up to the current iteration if the weights and reps can be increased.
for i in range(1, iteration + 1):
- weight_config = self.weightconfig_set.filter(iteration__lte=i).last()
- reps_config = self.repetitionsconfig_set.filter(iteration__lte=i).last()
-
- # No configs, return None
- if not weight_config or not reps_config:
- break
-
- # If we don't need to consider any log values, just calculate the value
- elif not weight_config.need_log_to_apply and not reps_config.need_log_to_apply:
- max_iter_weight = i
- max_iter_max_weight = i
- max_iter_reps = i
- max_iter_max_reps = i
-
- # We do need to check the logs, iterate over them and check that we
- # matched the planned values and continue or
- elif weight_config.need_log_to_apply or reps_config.need_log_to_apply:
- log_data = self.workoutlog_set.filter(slot_entry_id=self.id, iteration=i - 1)
-
- # If any of the entries in last log is greater than the last config data,
- # proceed. Otherwise, the weight won't change
+ configs = {
+ 'weight': self.weightconfig_set.filter(iteration__lte=i).last(),
+ 'repetitions': self.repetitionsconfig_set.filter(iteration__lte=i).last(),
+ 'rir': self.rirconfig_set.filter(iteration__lte=i).last(),
+ 'rest': self.restconfig_set.filter(iteration__lte=i).last(),
+ 'sets': self.setsconfig_set.filter(iteration__lte=i).last(),
+ 'max_sets': self.maxsetsconfig_set.filter(iteration__lte=i).last(),
+ }
+ log_data = self.workoutlog_set.filter(slot_entry_id=self.id, iteration=i - 1)
+
+ for field, config in configs.items():
+ if not config:
+ continue
+
+ if not config.requirements:
+ max_iterations[field] = i
+ continue
+
+ requirements = config.requirements_object
+
for log in log_data:
- if log.weight >= weight and log.repetitions >= reps:
- max_iter_weight = i
- max_iter_max_weight = i
- max_iter_reps = i
- max_iter_max_reps = i
+ all_fields_met = all(
+ getattr(log, req_field) is not None
+ and getattr(log, req_field)
+ >= getattr(self, f'calculate_{req_field}')(max_iterations[req_field])
+ for req_field in requirements.rules
+ )
- # As soon as we find a matching log, stop
- break
+ if all_fields_met:
+ max_iterations[field] = i
+
+ sets = self.calculate_sets(max_iterations['sets'])
+ max_sets = self.calculate_max_sets(max_iterations['max_sets'])
- sets = self.calculate_sets(iteration)
- max_sets = self.calculate_max_sets(iteration)
+ weight = self.calculate_weight(max_iterations['weight'])
+ max_weight = self.calculate_max_weight(max_iterations['max_weight'])
- weight = self.calculate_weight(max_iter_weight)
- max_weight = self.calculate_max_weight(max_iter_max_weight)
+ repetitions = self.calculate_repetitions(max_iterations['repetitions'])
+ max_repetitions = self.calculate_max_repetitions(max_iterations['max_repetitions'])
- reps = self.calculate_reps(max_iter_reps)
- max_reps = self.calculate_max_reps(max_iter_max_reps)
+ rir = self.calculate_rir(max_iterations['rir'])
+ max_rir = self.calculate_max_rir(max_iterations['max_rir'])
- rest = self.calculate_rest(iteration)
- max_rest = self.calculate_max_rest(iteration)
+ rest = self.calculate_rest(max_iterations['rest'])
+ max_rest = self.calculate_max_rest(max_iterations['max_rest'])
return SetConfigData(
slot_entry_id=self.id,
@@ -306,20 +323,23 @@ class SlotEntry(models.Model):
# TODO: decide on whether to return None or always the unit
# weight_unit=self.weight_unit.pk if weight is not None else None,
weight_unit=self.weight_unit.pk,
- repetitions=round_value(reps, self.repetition_rounding),
- max_repetitions=round_value(max_reps, self.repetition_rounding)
- if max_reps and reps and max_reps > reps
+ repetitions=round_value(repetitions, self.repetition_rounding),
+ max_repetitions=round_value(max_repetitions, self.repetition_rounding)
+ if max_repetitions and repetitions and max_repetitions > repetitions
else None,
- repetitions_rounding=self.repetition_rounding if reps is not None else None,
+ repetitions_rounding=self.repetition_rounding if repetitions is not None else None,
repetitions_unit=self.repetition_unit.pk,
# TODO: decide on whether to return None or always the unit
# reps_unit=self.repetition_unit.pk if reps is not None else None,
- rir=self.calculate_rir(iteration),
- max_rir=self.calculate_max_rir(iteration),
+ rir=round_value(rir, 0.5),
+ max_rir=round_value(max_rir, 0.5) if max_rir and rir and max_rir > rir else None,
rest=round_value(rest, 1),
max_rest=round_value(max_rest, 1) if max_rest and rest and max_rest > rest else None,
)
+ #
+ # Note: don't rename these methods, they are accessed in get_config via getattr
+ #
def calculate_sets(self, iteration: int) -> Decimal | None:
return self.calculate_config_value(
self.duplicate_configs(
@@ -351,7 +371,7 @@ class SlotEntry(models.Model):
)
)
- def calculate_reps(self, iteration: int) -> Decimal | None:
+ def calculate_repetitions(self, iteration: int) -> Decimal | None:
return self.calculate_config_value(
self.duplicate_configs(
iteration,
@@ -359,7 +379,7 @@ class SlotEntry(models.Model):
)
)
- def calculate_max_reps(self, iteration: int) -> Decimal | None:
+ def calculate_max_repetitions(self, iteration: int) -> Decimal | None:
return self.calculate_config_value(
self.duplicate_configs(
iteration,
diff --git a/wger/manager/tests/test_change_config_model.py b/wger/manager/tests/test_change_config_model.py
new file mode 100644
index 000000000..cdc54972d
--- /dev/null
+++ b/wger/manager/tests/test_change_config_model.py
@@ -0,0 +1,43 @@
+# This file is part of wger Workout Manager.
+#
+# wger Workout Manager is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# wger Workout Manager is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+
+# Standard Library
+import logging
+
+# wger
+from wger.core.tests.base_testcase import WgerTestCase
+from wger.manager.dataclasses import ConfigRequirements
+from wger.manager.models import SetsConfig
+
+
+logger = logging.getLogger(__name__)
+
+
+class ChangeConfigTestCase(WgerTestCase):
+ """
+ Test some logic in the AbstractChangeConfig model
+ (here with a SetsConfig since the abstract class cannot be instantiated)
+ """
+
+ def test_requirements_session(self):
+ """
+ Test the ConfigRequirements object is successfully created
+ """
+
+ config = SetsConfig(requirements={'rules': ['weight', 'repetitions']})
+
+ self.assertEqual(
+ config.requirements_object,
+ ConfigRequirements(data={'rules': ['weight', 'repetitions']}),
+ )
diff --git a/wger/manager/tests/test_slot_entry.py b/wger/manager/tests/test_slot_entry.py
index 1e58462b8..24667721b 100644
--- a/wger/manager/tests/test_slot_entry.py
+++ b/wger/manager/tests/test_slot_entry.py
@@ -136,9 +136,9 @@ class SlotEntryTestCase(WgerTestCase):
slot_entry=self.slot_entry,
iteration=2,
value=2.5,
- need_log_to_apply=True,
operation=OperationChoices.PLUS,
step=StepChoices.ABSOLUTE,
+ requirements={'rules': ['weight', 'repetitions']},
).save()
# Replace weight with 42 at iteration 5, no logs needed
@@ -146,7 +146,6 @@ class SlotEntryTestCase(WgerTestCase):
slot_entry=self.slot_entry,
iteration=5,
value=42,
- need_log_to_apply=False,
operation=OperationChoices.REPLACE,
step=StepChoices.ABSOLUTE,
).save()
@@ -263,6 +262,152 @@ class SlotEntryTestCase(WgerTestCase):
),
)
+ def test_requirements_sets_met(self):
+ """
+ Test that the sets are correctly calculated if there are requirements
+ """
+
+ self.slot_entry.weight_rounding = 2.5
+ self.slot_entry.repetition_rounding = 2
+ self.slot_entry.save()
+
+ # Initial value
+ SetsConfig(
+ slot_entry=self.slot_entry,
+ iteration=1,
+ value=5,
+ ).save()
+ WeightConfig(
+ slot_entry=self.slot_entry,
+ iteration=1,
+ value=50,
+ ).save()
+ RestConfig(
+ slot_entry=self.slot_entry,
+ iteration=1,
+ value=90,
+ ).save()
+
+ # Increase sets by 1 at iteration 2
+ SetsConfig(
+ slot_entry=self.slot_entry,
+ iteration=2,
+ value=1,
+ operation=OperationChoices.PLUS,
+ step=StepChoices.ABSOLUTE,
+ requirements={'rules': ['weight', 'rest']},
+ ).save()
+
+ # Rest is ok
+ WorkoutLog(
+ exercise_id=1,
+ user_id=1,
+ routine_id=1,
+ slot_entry=self.slot_entry,
+ iteration=1,
+ weight=50,
+ rest=100,
+ repetitions=4,
+ ).save()
+
+ self.assertDictEqual(
+ self.slot_entry.get_config(1).__dict__,
+ SetConfigData(
+ slot_entry_id=self.slot_entry.pk,
+ exercise=1,
+ sets=1,
+ weight=Decimal(50),
+ weight_rounding=Decimal(2.5),
+ rest=90,
+ ).__dict__,
+ )
+
+ # Sets did increase
+ self.assertDictEqual(
+ self.slot_entry.get_config(2).__dict__,
+ SetConfigData(
+ slot_entry_id=self.slot_entry.pk,
+ exercise=1,
+ sets=6,
+ weight=Decimal(50),
+ weight_rounding=Decimal(2.5),
+ rest=90,
+ ).__dict__,
+ )
+
+ def test_requirements_sets_unmet(self):
+ """
+ Test that the sets are correctly calculated if there are requirements
+ """
+
+ self.slot_entry.weight_rounding = 2.5
+ self.slot_entry.repetition_rounding = 2
+ self.slot_entry.save()
+
+ # Initial value
+ SetsConfig(
+ slot_entry=self.slot_entry,
+ iteration=1,
+ value=5,
+ ).save()
+ WeightConfig(
+ slot_entry=self.slot_entry,
+ iteration=1,
+ value=50,
+ ).save()
+ RestConfig(
+ slot_entry=self.slot_entry,
+ iteration=1,
+ value=90,
+ ).save()
+
+ # Increase sets by 1 at iteration 2
+ SetsConfig(
+ slot_entry=self.slot_entry,
+ iteration=2,
+ value=1,
+ operation=OperationChoices.PLUS,
+ step=StepChoices.ABSOLUTE,
+ requirements={'rules': ['weight', 'rest']},
+ ).save()
+
+ # Rest too low
+ WorkoutLog(
+ exercise_id=1,
+ user_id=1,
+ routine_id=1,
+ slot_entry=self.slot_entry,
+ iteration=1,
+ weight=50,
+ rest=80,
+ repetitions=4,
+ ).save()
+
+ self.assertEqual(
+ self.slot_entry.get_config(1),
+ SetConfigData(
+ slot_entry_id=self.slot_entry.pk,
+ exercise=1,
+ sets=5,
+ weight=Decimal(50),
+ weight_rounding=Decimal(2.5),
+ rest=90,
+ ),
+ )
+
+ # Sets don't increase
+ self.assertEqual(
+ self.slot_entry.get_config(2),
+ SetConfigData(
+ slot_entry_id=self.slot_entry.pk,
+ exercise=1,
+ sets=5,
+ weight=Decimal(50),
+ weight_rounding=Decimal(2.5),
+ rest=90,
+ ),
+ )
+
def test_weight_config_with_logs_and_range(self):
"""
Test that the weight is correctly calculated for each step / iteration
diff --git a/wger/manager/views/routine.py b/wger/manager/views/routine.py
index 4ddc4ff51..4da2ad013 100644
--- a/wger/manager/views/routine.py
+++ b/wger/manager/views/routine.py
@@ -34,6 +34,7 @@ from wger.manager.models import (
SlotEntry,
)
+
logger = logging.getLogger(__name__)
diff --git a/wger/nutrition/sync.py b/wger/nutrition/sync.py
index 06c3d92c5..01e729c61 100644
--- a/wger/nutrition/sync.py
+++ b/wger/nutrition/sync.py
@@ -50,6 +50,7 @@ from wger.utils.requests import (
)
from wger.utils.url import make_uri
+
logger = logging.getLogger(__name__)
diff --git a/wger/urls.py b/wger/urls.py
index 054258d22..34678c0ce 100644
--- a/wger/urls.py
+++ b/wger/urls.py
@@ -51,6 +51,7 @@ from wger.nutrition.api import views as nutrition_api_views
from wger.utils.generic_views import TextTemplateView
from wger.weight.api import views as weight_api_views
+
#
# REST API
#