mirror of
https://github.com/wger-project/wger.git
synced 2026-12-06 15:54:39 +01:00
Leave out the owner's history in public template date sequences
This commit is contained in:
1 parent
ed636e6ac5
commit
5e528329a9
8 files changed
+178
-26
No files matched your search
@@ -29,7 +29,8 @@ class RoutinePermission(permissions.BasePermission):
|
||||
|
||||
# Routine actions that expose the owner's personal training history
|
||||
# rather than the public template structure. They must stay
|
||||
# owner-only, even on public templates.
|
||||
# owner-only, even on public templates. The date-sequence actions stay
|
||||
# open but leave out the owner's history for others (see RoutineViewSet).
|
||||
OWNER_ONLY_ACTIONS = frozenset({'logs', 'stats'})
|
||||
|
||||
def has_object_permission(self, request, view, obj):
|
||||
|
||||
@@ -124,6 +124,11 @@ class RoutineViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
serializer.save(user=self.request.user)
|
||||
|
||||
def _date_sequence(self):
|
||||
"""The date sequence, following the owner's sessions and logs only for the owner"""
|
||||
routine = self.get_object()
|
||||
return routine.get_date_sequence(with_history=routine.user == self.request.user)
|
||||
|
||||
@extend_schema(responses={200: WorkoutDayDataDisplayModeSerializer(many=True)})
|
||||
@action(detail=True, url_path='date-sequence-display', pagination_class=None)
|
||||
def date_sequence_display_mode(self, request, pk):
|
||||
@@ -135,10 +140,7 @@ class RoutineViewSet(viewsets.ModelViewSet):
|
||||
if cached_data is not None:
|
||||
return Response(cached_data)
|
||||
|
||||
out = WorkoutDayDataDisplayModeSerializer(
|
||||
self.get_object().date_sequence,
|
||||
many=True,
|
||||
).data
|
||||
out = WorkoutDayDataDisplayModeSerializer(self._date_sequence(), many=True).data
|
||||
cache.set(cache_key, out, settings.WGER_SETTINGS['ROUTINE_CACHE_TTL'])
|
||||
|
||||
return Response(out)
|
||||
@@ -154,7 +156,7 @@ class RoutineViewSet(viewsets.ModelViewSet):
|
||||
if cached_data is not None:
|
||||
return Response(cached_data)
|
||||
|
||||
out = WorkoutDayDataGymModeSerializer(self.get_object().date_sequence, many=True).data
|
||||
out = WorkoutDayDataGymModeSerializer(self._date_sequence(), many=True).data
|
||||
cache.set(cache_key, out, settings.WGER_SETTINGS['ROUTINE_CACHE_TTL'])
|
||||
|
||||
return Response(out)
|
||||
|
||||
@@ -219,13 +219,14 @@ class WorkoutDayData:
|
||||
date: datetime.date
|
||||
iteration: int | None
|
||||
label: str | None = None
|
||||
with_history: bool = True
|
||||
|
||||
@property
|
||||
def slots_gym_mode(self) -> List[SlotData]:
|
||||
if not self.day:
|
||||
return []
|
||||
|
||||
return self.day.get_slots_gym_mode(self.iteration)
|
||||
return self.day.get_slots_gym_mode(self.iteration, self.with_history)
|
||||
|
||||
@property
|
||||
def slots_display_mode(self) -> List[SlotData]:
|
||||
@@ -234,7 +235,7 @@ class WorkoutDayData:
|
||||
if not self.day:
|
||||
return []
|
||||
|
||||
return self.day.get_slots_display_mode(self.iteration)
|
||||
return self.day.get_slots_display_mode(self.iteration, self.with_history)
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -117,15 +117,17 @@ class Day(models.Model):
|
||||
"""
|
||||
return self.routine
|
||||
|
||||
def get_slots_gym_mode(self, iteration: int) -> list[SlotData]:
|
||||
def get_slots_gym_mode(self, iteration: int, with_history: bool = True) -> list[SlotData]:
|
||||
"""
|
||||
Return the sets for this day
|
||||
"""
|
||||
slots = getattr(self, 'prefetched_slots', self.slots.all())
|
||||
|
||||
return [SlotData(comment=s.comment, sets=s.set_data_gym(iteration)) for s in slots]
|
||||
return [
|
||||
SlotData(comment=s.comment, sets=s.set_data_gym(iteration, with_history)) for s in slots
|
||||
]
|
||||
|
||||
def get_slots_display_mode(self, iteration: int) -> list[SlotData]:
|
||||
def get_slots_display_mode(self, iteration: int, with_history: bool = True) -> list[SlotData]:
|
||||
"""
|
||||
Return the sets for this day.
|
||||
|
||||
@@ -153,7 +155,7 @@ class Day(models.Model):
|
||||
for slot in slots:
|
||||
slot_data = SlotData(
|
||||
comment=slot.comment,
|
||||
sets=[s.data for s in slot.set_data(iteration)],
|
||||
sets=[s.data for s in slot.set_data(iteration, with_history)],
|
||||
)
|
||||
exercises = slot_data.exercises
|
||||
|
||||
|
||||
@@ -181,10 +181,20 @@ class Routine(models.Model):
|
||||
|
||||
If a day needs logs to continue it will be repeated until the user adds one.
|
||||
"""
|
||||
return self.get_date_sequence()
|
||||
|
||||
def get_date_sequence(self, with_history: bool = True) -> List[WorkoutDayData]:
|
||||
"""
|
||||
Return the date sequence, see date_sequence
|
||||
|
||||
Without history the owner's sessions and logs are ignored, as for a fresh copy.
|
||||
This variant is not cached here, only per user in the API.
|
||||
"""
|
||||
cache_key = CacheKeyMapper.routine_date_sequence_key(self.id)
|
||||
cached_data = cache.get(cache_key)
|
||||
if cached_data is not None:
|
||||
return cached_data
|
||||
if with_history:
|
||||
cached_data = cache.get(cache_key)
|
||||
if cached_data is not None:
|
||||
return cached_data
|
||||
|
||||
# wger
|
||||
from wger.manager.models import (
|
||||
@@ -238,9 +248,10 @@ class Routine(models.Model):
|
||||
# for every session of this routine's user, fetch it once
|
||||
tz = self.user.userprofile.zone_info
|
||||
workout_session_map = defaultdict(set)
|
||||
for day in days:
|
||||
for session in day.workoutsession_set.all():
|
||||
workout_session_map[day.id].add(session.local_day_in(tz))
|
||||
if with_history:
|
||||
for day in days:
|
||||
for session in day.workoutsession_set.all():
|
||||
workout_session_map[day.id].add(session.local_day_in(tz))
|
||||
|
||||
# Main sequence generation logic
|
||||
labels = self.label_dict
|
||||
@@ -295,6 +306,7 @@ class Routine(models.Model):
|
||||
date=placeholder_date,
|
||||
day=None,
|
||||
label=labels.get(placeholder_date),
|
||||
with_history=with_history,
|
||||
# This is ugly, but we don't want to advance the iteration
|
||||
iteration=iteration_counter[current_day.id] - 1,
|
||||
)
|
||||
@@ -310,6 +322,7 @@ class Routine(models.Model):
|
||||
date=current_date,
|
||||
day=current_day,
|
||||
label=labels.get(current_date),
|
||||
with_history=with_history,
|
||||
)
|
||||
)
|
||||
current_date += datetime.timedelta(days=1)
|
||||
@@ -328,7 +341,8 @@ class Routine(models.Model):
|
||||
)
|
||||
ttl = min(ttl, max(1, int((next_midnight - now).total_seconds())))
|
||||
|
||||
cache.set(cache_key, sequence, ttl)
|
||||
if with_history:
|
||||
cache.set(cache_key, sequence, ttl)
|
||||
return sequence
|
||||
|
||||
def data_for_day(self, date=None) -> WorkoutDayData | None:
|
||||
|
||||
@@ -69,15 +69,18 @@ class Slot(models.Model):
|
||||
entries = getattr(self, 'prefetched_entries', self.entries.all())
|
||||
return len(entries) > 1
|
||||
|
||||
def set_data(self, iteration: int) -> list[SetExerciseData]:
|
||||
def set_data(self, iteration: int, with_history: bool = True) -> list[SetExerciseData]:
|
||||
"""Calculates the set data for a specific iteration"""
|
||||
entries = getattr(self, 'prefetched_entries', self.entries.all())
|
||||
|
||||
result = [SetExerciseData(data=e.get_config_data(iteration), config=e) for e in entries]
|
||||
result = [
|
||||
SetExerciseData(data=e.get_config_data(iteration, with_history), config=e)
|
||||
for e in entries
|
||||
]
|
||||
|
||||
return result
|
||||
|
||||
def set_data_gym(self, iteration: int) -> list[SetConfigData]:
|
||||
def set_data_gym(self, iteration: int, with_history: bool = True) -> list[SetConfigData]:
|
||||
"""
|
||||
Calculates the sets as they would be performed in the gym
|
||||
|
||||
@@ -109,7 +112,7 @@ class Slot(models.Model):
|
||||
- Exercise 1, 1 set
|
||||
- Exercise 1, 1 set
|
||||
"""
|
||||
set_data = self.set_data(iteration)
|
||||
set_data = self.set_data(iteration, with_history)
|
||||
|
||||
# If this is not a superset, adjust the sets and just return the data
|
||||
if len(set_data) == 1:
|
||||
|
||||
@@ -416,7 +416,7 @@ class SlotEntry(models.Model):
|
||||
|
||||
return any(all(rule_met(log, rule) for rule in requirements.rules) for log in log_data)
|
||||
|
||||
def get_config_data(self, iteration: int) -> SetConfigData:
|
||||
def get_config_data(self, iteration: int, with_history: bool = True) -> SetConfigData:
|
||||
"""
|
||||
Calculates the configuration for a given iteration of a slot entry.
|
||||
|
||||
@@ -425,6 +425,8 @@ class SlotEntry(models.Model):
|
||||
requirements only apply on iterations where a log of the previous
|
||||
iteration reaches the displayed prescription of all required fields,
|
||||
earning one application per qualifying iteration.
|
||||
|
||||
Without history the owner's logs are ignored.
|
||||
"""
|
||||
|
||||
# If there are no progressions, the value will be always the same
|
||||
@@ -437,7 +439,11 @@ class SlotEntry(models.Model):
|
||||
# routine's owner. The API ownership check should already prevent
|
||||
# cross-user logs from being attached to a slot entry, but this
|
||||
# filter ensures progression calculations stay user-scoped.
|
||||
logs = list(self.workoutlog_set.filter(user=self.slot.day.routine.user))
|
||||
logs = (
|
||||
list(self.workoutlog_set.filter(user=self.slot.day.routine.user))
|
||||
if with_history
|
||||
else []
|
||||
)
|
||||
|
||||
# If there is a custom class set, pass all responsibilities to it
|
||||
if self.class_name:
|
||||
@@ -461,7 +467,9 @@ class SlotEntry(models.Model):
|
||||
max_rir_configs=self.maxrirconfig_set.filter(iteration__lte=iteration),
|
||||
rest_configs=self.restconfig_set.filter(iteration__lte=iteration),
|
||||
max_rest_configs=self.maxrestconfig_set.filter(iteration__lte=iteration),
|
||||
logs=self.workoutlog_set.filter(iteration__lte=iteration),
|
||||
logs=self.workoutlog_set.filter(iteration__lte=iteration)
|
||||
if with_history
|
||||
else WorkoutLog.objects.none(),
|
||||
)
|
||||
|
||||
return custom_logic.calculate()
|
||||
|
||||
@@ -15,20 +15,28 @@
|
||||
# Standard Library
|
||||
import datetime
|
||||
import zoneinfo
|
||||
from decimal import Decimal
|
||||
from unittest import mock
|
||||
|
||||
# Django
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import User
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
|
||||
# wger
|
||||
from wger.core.tests.api_base_test import ApiBaseResourceTestCase
|
||||
from wger.core.tests.base_testcase import WgerTestCase
|
||||
from wger.exercises.models import Exercise
|
||||
from wger.manager.dataclasses import WorkoutDayData
|
||||
from wger.manager.models import (
|
||||
Day,
|
||||
Label,
|
||||
RepetitionsConfig,
|
||||
Slot,
|
||||
SlotEntry,
|
||||
WeightConfig,
|
||||
WorkoutLog,
|
||||
WorkoutSession,
|
||||
)
|
||||
from wger.manager.models.routine import Routine
|
||||
@@ -710,3 +718,116 @@ class RoutineLogsAndStatsScopeTestCase(WgerTestCase):
|
||||
self.user_login('test')
|
||||
response = self.client.get(self.detail_url)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
|
||||
class RoutineDateSequenceHistoryScopeTestCase(WgerTestCase):
|
||||
"""
|
||||
The date sequence of a public template only follows the owner's sessions
|
||||
and logs for the owner. Other users get the sequence without any history.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.owner = User.objects.get(username='trainer2')
|
||||
|
||||
# Day A only advances after a logged session, the owner had one on 01-03
|
||||
self.days_template = Routine.objects.create(
|
||||
user=self.owner,
|
||||
name='Days',
|
||||
start=datetime.date(2024, 1, 1),
|
||||
end=datetime.date(2024, 1, 6),
|
||||
is_template=True,
|
||||
is_public=True,
|
||||
)
|
||||
day_a = Day.objects.create(
|
||||
routine=self.days_template,
|
||||
order=1,
|
||||
name='A',
|
||||
need_logs_to_advance=True,
|
||||
)
|
||||
Day.objects.create(routine=self.days_template, order=2, name='B')
|
||||
WorkoutSession.objects.create(
|
||||
user=self.owner,
|
||||
routine=self.days_template,
|
||||
day=day_a,
|
||||
datetime_start=datetime.datetime(2024, 1, 3, 12, 0, tzinfo=datetime.timezone.utc),
|
||||
)
|
||||
|
||||
# +2.5 kg per iteration once the previous iteration reached 5 repetitions
|
||||
self.progression_template = Routine.objects.create(
|
||||
user=self.owner,
|
||||
name='Progression',
|
||||
start=datetime.date(2024, 2, 1),
|
||||
end=datetime.date(2024, 2, 3),
|
||||
is_template=True,
|
||||
is_public=True,
|
||||
)
|
||||
day = Day.objects.create(routine=self.progression_template, order=1, name='Squat')
|
||||
exercise = Exercise.objects.first()
|
||||
entry = SlotEntry.objects.create(
|
||||
slot=Slot.objects.create(day=day, order=1),
|
||||
exercise=exercise,
|
||||
order=1,
|
||||
)
|
||||
RepetitionsConfig.objects.create(slot_entry=entry, iteration=1, value=5)
|
||||
WeightConfig.objects.create(slot_entry=entry, iteration=1, value=100)
|
||||
WeightConfig.objects.create(
|
||||
slot_entry=entry,
|
||||
iteration=2,
|
||||
value=2.5,
|
||||
operation='+',
|
||||
repeat=True,
|
||||
requirements={'rules': ['repetitions']},
|
||||
)
|
||||
when = datetime.datetime(2024, 2, 1, 18, 0, tzinfo=datetime.timezone.utc)
|
||||
session = WorkoutSession.objects.create(
|
||||
user=self.owner,
|
||||
routine=self.progression_template,
|
||||
day=day,
|
||||
datetime_start=when,
|
||||
)
|
||||
WorkoutLog.objects.create(
|
||||
user=self.owner,
|
||||
session=session,
|
||||
routine=self.progression_template,
|
||||
slot_entry=entry,
|
||||
exercise=exercise,
|
||||
iteration=1,
|
||||
date=when,
|
||||
repetitions=5,
|
||||
repetitions_unit_id=1,
|
||||
weight=100,
|
||||
weight_unit_id=1,
|
||||
)
|
||||
|
||||
def day_names(self, url_name: str, username: str) -> list[str]:
|
||||
self.user_login(username)
|
||||
response = self.client.get(reverse(url_name, kwargs={'pk': self.days_template.pk}))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
return [entry['day']['name'] for entry in response.data]
|
||||
|
||||
def weights(self, url_name: str, username: str) -> list[Decimal]:
|
||||
self.user_login(username)
|
||||
response = self.client.get(reverse(url_name, kwargs={'pk': self.progression_template.pk}))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
return [Decimal(str(entry['slots'][0]['sets'][0]['weight'])) for entry in response.data]
|
||||
|
||||
def test_days_follow_sessions_only_for_owner(self):
|
||||
"""The owner's session moves the sequence on, for other users it does not"""
|
||||
for url_name in ('routine-date-sequence-display-mode', 'routine-date-sequence-gym-mode'):
|
||||
with self.subTest(url_name=url_name):
|
||||
self.assertEqual(
|
||||
self.day_names(url_name, 'trainer2'),
|
||||
['A', 'A', 'A', 'B', 'A', 'A'],
|
||||
)
|
||||
self.assertEqual(self.day_names(url_name, 'test'), ['A'] * 6)
|
||||
|
||||
def test_progression_follows_logs_only_for_owner(self):
|
||||
"""The owner's log unlocks the progression, for other users it does not"""
|
||||
for url_name in ('routine-date-sequence-display-mode', 'routine-date-sequence-gym-mode'):
|
||||
with self.subTest(url_name=url_name):
|
||||
self.assertEqual(
|
||||
self.weights(url_name, 'trainer2'),
|
||||
[Decimal(100), Decimal('102.5'), Decimal('102.5')],
|
||||
)
|
||||
self.assertEqual(self.weights(url_name, 'test'), [Decimal(100)] * 3)
|
||||
Reference in new issue
Block a user