Merge branch 'fix/remove-api-workaounds'

This commit is contained in:
Roland Geider
2026-11-08 12:46:21 +01:00
6 changed files with 6 additions and 499 deletions

View File

@@ -13,9 +13,6 @@
# 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
# Django
from django.core.exceptions import ValidationError as DjangoValidationError
from django.utils import timezone
@@ -24,7 +21,6 @@ from django.utils import timezone
from rest_framework import serializers
# wger
from wger.core.models import UserProfile
from wger.manager.api.consts import BASE_CONFIG_FIELDS
from wger.manager.api.fields import DecimalOrIntegerField
from wger.manager.api.validators import validate_requirements
@@ -436,11 +432,6 @@ class WorkoutSessionSerializer(serializers.ModelSerializer):
Workout session serializer
"""
# Write-only compatibility with the pre-2.7 API, remove in 2.8. The app
# queues its offline writes with the column names it had at the time, so
# uploads written before the update still arrive in the old shape.
LEGACY_FIELDS = ('date', 'time_start', 'time_end')
class Meta:
model = WorkoutSession
fields = (
@@ -478,79 +469,6 @@ class WorkoutSessionSerializer(serializers.ModelSerializer):
return attrs
def to_internal_value(self, data):
return super().to_internal_value(self._translate_legacy_input(data))
def _translate_legacy_input(self, data):
"""
Compose datetime_start/datetime_end out of the deprecated triple
Only components the request did not send are taken from the instance, so
a PATCH that just sets time_end keeps the day and start time it had. Values
sent in the new format always win. The wall times resolve in the owner's
zone: a queued 07:00 is the user's 07:00, whatever zone the request
happens to run in.
"""
if not any(key in data for key in self.LEGACY_FIELDS):
return data
tz = self._owner_zone()
data = data.copy()
date = self._legacy_value('date', data, serializers.DateField)
time_start = self._legacy_value('time_start', data, serializers.TimeField)
time_end = self._legacy_value('time_end', data, serializers.TimeField)
local_start = (
timezone.localtime(self.instance.datetime_start, tz)
if self.instance and self.instance.datetime_start
else None
)
if date is None:
date = local_start.date() if local_start else timezone.localdate(timezone=tz)
if 'time_start' not in data:
time_start = local_start.time() if local_start else datetime.time()
if 'time_end' not in data and self.instance and self.instance.datetime_end:
time_end = timezone.localtime(self.instance.datetime_end, tz).time()
if 'datetime_start' not in data:
data['datetime_start'] = timezone.make_aware(
datetime.datetime.combine(date, time_start or datetime.time()), tz
)
if 'datetime_end' not in data:
end = None
if time_end:
end = timezone.make_aware(datetime.datetime.combine(date, time_end), tz)
if time_start and time_end < time_start:
end += datetime.timedelta(days=1)
data['datetime_end'] = end
return data
def _owner_zone(self):
"""The owner's timezone, falling back to the active one when unknown"""
if self.instance:
return self.instance.user.userprofile.zone_info
user_id = self.context.get('user_id')
if user_id is None:
request = self.context.get('request')
if request is not None and request.user.is_authenticated:
user_id = request.user.pk
if user_id is None:
return timezone.get_current_timezone()
return UserProfile.objects.get(user_id=user_id).zone_info
@staticmethod
def _legacy_value(key, data, field_class):
"""Parse one deprecated value, reporting errors under its own key"""
if data.get(key) in (None, ''):
return None
try:
return field_class().to_internal_value(data[key])
except serializers.ValidationError as e:
raise serializers.ValidationError({key: e.detail})
class OwnerScopedSessionField(serializers.PrimaryKeyRelatedField):
"""

View File

@@ -346,23 +346,3 @@ class WorkoutLog(models.Model):
# Save to db
super().save(*args, **kwargs)
# The app creates its sessions itself and can leave the day empty, which
# hides them from days with need_logs_to_advance. Only filled in when all
# logs of the session agree on one day, like migration 0028 does: a wrong
# day would open the gate on a day the user never trained.
#
# Can be removed once the app versions that set the day are widely adopted.
if self.session_id and self.slot_entry and self.session.day_id is None:
days = list(
WorkoutLog.objects.filter(
session_id=self.session_id,
slot_entry__isnull=False,
)
.values_list('slot_entry__slot__day_id', 'slot_entry__slot__day__routine_id')
.distinct()
)
if len(days) == 1 and days[0][1] == self.session.routine_id:
self.session.day_id = days[0][0]
self.session.save(update_fields=['day'])

View File

@@ -53,8 +53,6 @@ class WorkoutSessionHandler(PowerSyncHandler):
model = WorkoutSession
serializer_class = WorkoutSessionSerializer
viewset_class = WorkoutSessionViewSet
# The legacy-triple shim resolves its wall times in the owner's zone
pass_user_id_in_context = True
@register_handler

View File

@@ -23,8 +23,6 @@ from django.utils import timezone
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.manager.models import (
Slot,
SlotEntry,
WorkoutLog,
WorkoutSession,
)
@@ -152,27 +150,6 @@ class LogModelTestCase(WgerTestCase):
self.assertEqual(WorkoutSession.objects.count(), 1)
def test_create_session_sets_day(self):
"""
The auto-created session inherits the day of the log's slot entry, so
that need_logs_to_advance days can find it
"""
WorkoutLog.objects.all().delete()
WorkoutSession.objects.all().delete()
WorkoutLog(
user_id=1,
exercise_id=1,
routine_id=1,
slot_entry_id=1,
weight=10,
repetitions=10,
).save()
session = WorkoutSession.objects.get()
self.assertEqual(session.day_id, 1)
def test_create_session_without_slot_entry_has_no_day(self):
"""
A free log without a slot entry can't know its day
@@ -191,28 +168,6 @@ class LogModelTestCase(WgerTestCase):
session = WorkoutSession.objects.get()
self.assertIsNone(session.day_id)
def test_fills_missing_day_on_a_client_created_session(self):
"""
A session the client created without a day gets it from the log, so that
need_logs_to_advance days can find it
"""
session = WorkoutSession.objects.get(pk='bbbbbbbb-bbbb-bbbb-bbbb-000000000001')
self.assertIsNone(session.day_id)
WorkoutLog(
user_id=1,
exercise_id=1,
routine_id=1,
slot_entry_id=1,
session=session,
weight=10,
repetitions=10,
).save()
session.refresh_from_db()
self.assertEqual(session.day_id, 1)
def test_does_not_overwrite_the_day_of_a_session(self):
"""
A session that already has a day keeps it, even when the log points
@@ -236,112 +191,6 @@ class LogModelTestCase(WgerTestCase):
session.refresh_from_db()
self.assertEqual(session.day_id, 3)
def test_does_not_fill_the_day_when_the_logs_span_several_days(self):
"""
A session whose logs come from more than one day stays without one, since
no single day is the right answer
"""
session = WorkoutSession.objects.get(pk='bbbbbbbb-bbbb-bbbb-bbbb-000000000001')
self.assertIsNone(session.day_id)
# A second entry, on another day of the same routine
other_slot = Slot.objects.create(day_id=3, order=1)
other_entry = SlotEntry.objects.create(slot=other_slot, exercise_id=1, order=1)
WorkoutLog(
user_id=1,
exercise_id=1,
routine_id=1,
slot_entry_id=1,
session=session,
weight=10,
repetitions=10,
).save()
session.refresh_from_db()
self.assertEqual(session.day_id, 1)
# The day of the first log is no longer the whole truth, but an already
# set day is never taken away again
WorkoutLog(
user_id=1,
exercise_id=1,
routine_id=1,
slot_entry=other_entry,
session=session,
weight=10,
repetitions=10,
).save()
session.refresh_from_db()
self.assertEqual(session.day_id, 1)
def test_does_not_fill_the_day_when_earlier_logs_disagree(self):
"""
Logs that were already there decide as well, not just the one being saved
"""
session = WorkoutSession.objects.get(pk='bbbbbbbb-bbbb-bbbb-bbbb-000000000001')
other_slot = Slot.objects.create(day_id=3, order=1)
other_entry = SlotEntry.objects.create(slot=other_slot, exercise_id=1, order=1)
# Two logs from different days, written without going through save()
for slot_entry_id in (1, other_entry.pk):
WorkoutLog.objects.bulk_create(
[
WorkoutLog(
user_id=1,
exercise_id=1,
routine_id=1,
slot_entry_id=slot_entry_id,
session=session,
weight=10,
repetitions=10,
)
]
)
session.refresh_from_db()
self.assertIsNone(session.day_id)
WorkoutLog(
user_id=1,
exercise_id=1,
routine_id=1,
slot_entry_id=1,
session=session,
weight=20,
repetitions=8,
).save()
session.refresh_from_db()
self.assertIsNone(session.day_id)
def test_does_not_fill_the_day_from_another_routine(self):
"""
The day of a slot entry from a different routine must not leak into the
session
"""
session = WorkoutSession.objects.get(pk='bbbbbbbb-bbbb-bbbb-bbbb-000000000003')
self.assertIsNone(session.day_id)
self.assertEqual(session.routine_id, 2)
# slot entry 1 lives in routine 1, the session in routine 2
WorkoutLog(
user_id=1,
exercise_id=1,
routine_id=1,
slot_entry_id=1,
session=session,
weight=10,
repetitions=10,
).save()
session.refresh_from_db()
self.assertIsNone(session.day_id)
def test_save_reuses_session_when_duplicates_exist(self):
"""
Duplicate routine-less sessions can exist for one (user, date) because the

View File

@@ -12,18 +12,7 @@
#
# You should have received a copy of the GNU Affero General Public License
# Standard Library
import datetime
import zoneinfo
# Django
from django.utils import timezone
# Third Party
from rest_framework import status
# wger
from wger.core.models import UserProfile
from wger.core.tests import powersync_base_test
from wger.manager.models import (
Routine,
@@ -102,62 +91,6 @@ class WorkoutSessionPowerSyncTestCase(powersync_base_test.PowerSyncResourceTestC
fk_ownership = (('routine', ROUTINE_OTHER),)
def test_create_with_deprecated_fields(self):
"""
A push queued by an app version that predates 2.7 still lands on the day
and time it was recorded on
"""
self.authenticate()
response = self.push(
'PUT',
{
'id': 'bbbbbbbb-bbbb-bbbb-bbbb-000000000098',
'date': '2030-01-15',
'time_start': '23:00:00',
'time_end': '01:30:00',
'routine': ROUTINE_OWNED,
'impression': '2',
},
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
session = WorkoutSession.objects.get(pk='bbbbbbbb-bbbb-bbbb-bbbb-000000000098')
self.assertEqual(
session.datetime_start,
timezone.make_aware(datetime.datetime(2030, 1, 15, 23, 0)),
)
self.assertEqual(
session.datetime_end,
timezone.make_aware(datetime.datetime(2030, 1, 16, 1, 30)),
)
def test_deprecated_fields_resolve_in_the_owners_timezone(self):
"""The queued wall time is the user's, not the zone the request runs in"""
profile = UserProfile.objects.get(user__username=self.user_access)
profile.time_zone = 'Pacific/Auckland'
profile.save()
self.authenticate()
response = self.push(
'PUT',
{
'id': 'bbbbbbbb-bbbb-bbbb-bbbb-000000000097',
'date': '2030-01-15',
'time_start': '07:00:00',
'routine': ROUTINE_OWNED,
'impression': '2',
},
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
session = WorkoutSession.objects.get(pk='bbbbbbbb-bbbb-bbbb-bbbb-000000000097')
self.assertEqual(
session.datetime_start,
datetime.datetime(2030, 1, 15, 7, 0, tzinfo=zoneinfo.ZoneInfo('Pacific/Auckland')),
)
class RoutinePowerSyncTestCase(
powersync_base_test.PowerSyncBaseTestCase,

View File

@@ -140,10 +140,13 @@ class WorkoutSessionDurationTestCase(WgerTestCase):
"""Editing the times of such a session does run into the limit"""
self.stretch_session()
session = WorkoutSession.objects.get(pk=self.SESSION)
response = self.client.patch(
reverse('workoutsession-detail', kwargs={'pk': self.SESSION}),
data={'time_end': '23:00'},
data={
'datetime_end': (session.datetime_start + datetime.timedelta(hours=9)).isoformat()
},
content_type='application/json',
)
@@ -235,168 +238,17 @@ class WorkoutSessionIntervalConstraintTestCase(WgerTestCase):
self.assertIsNone(session.datetime_end)
class WorkoutSessionLegacyFieldsTestCase(WgerTestCase):
class WorkoutSessionFilterTestCase(WgerTestCase):
"""
Test that writes in the pre-2.7 shape still arrive
Test filtering sessions over the API
"""
SESSION = 'bbbbbbbb-bbbb-bbbb-bbbb-000000000005'
ROUTINE = 3
def setUp(self):
super().setUp()
self.user_login('test')
def test_the_deprecated_fields_are_not_returned(self):
"""They are accepted on write, but they are not part of the response"""
response = self.client.get(reverse('workoutsession-detail', kwargs={'pk': self.SESSION}))
self.assertNotIn('date', response.json())
self.assertNotIn('time_start', response.json())
self.assertNotIn('time_end', response.json())
def test_create_with_the_deprecated_triple(self):
"""The deprecated fields are composed into datetime_start/datetime_end"""
response = self.client.post(
reverse('workoutsession-list'),
data={
'routine': self.ROUTINE,
'impression': '2',
'date': '2025-03-12',
'time_start': '10:00',
'time_end': '11:30',
},
content_type='application/json',
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
session = WorkoutSession.objects.get(pk=response.json()['id'])
self.assertEqual(
session.datetime_start,
timezone.make_aware(datetime.datetime(2025, 3, 12, 10, 0)),
)
self.assertEqual(
session.datetime_end,
timezone.make_aware(datetime.datetime(2025, 3, 12, 11, 30)),
)
def test_the_triple_is_composed_in_the_owners_timezone(self):
"""A queued 07:00 is the owner's 07:00, not the zone the request runs in"""
profile = User.objects.get(username='test').userprofile
profile.time_zone = 'Pacific/Auckland'
profile.save()
response = self.client.post(
reverse('workoutsession-list'),
data={
'routine': self.ROUTINE,
'impression': '2',
'date': '2025-03-12',
'time_start': '07:00',
},
content_type='application/json',
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
session = WorkoutSession.objects.get(pk=response.json()['id'])
self.assertEqual(
session.datetime_start,
datetime.datetime(2025, 3, 12, 7, 0, tzinfo=zoneinfo.ZoneInfo('Pacific/Auckland')),
)
def test_create_over_midnight_ends_on_the_next_day(self):
"""An end time before the start time means the session ended the day after"""
response = self.client.post(
reverse('workoutsession-list'),
data={
'routine': self.ROUTINE,
'impression': '2',
'date': '2025-03-10',
'time_start': '23:00',
'time_end': '01:30',
},
content_type='application/json',
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
session = WorkoutSession.objects.get(pk=response.json()['id'])
self.assertEqual(
session.datetime_start,
timezone.make_aware(datetime.datetime(2025, 3, 10, 23, 0)),
)
self.assertEqual(
session.datetime_end,
timezone.make_aware(datetime.datetime(2025, 3, 11, 1, 30)),
)
def test_create_without_a_start_time_starts_at_midnight(self):
"""A session without times covers the day it was logged on"""
response = self.client.post(
reverse('workoutsession-list'),
data={'routine': self.ROUTINE, 'impression': '2', 'date': '2025-03-12'},
content_type='application/json',
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
session = WorkoutSession.objects.get(pk=response.json()['id'])
self.assertEqual(
session.datetime_start,
timezone.make_aware(datetime.datetime(2025, 3, 12, 0, 0)),
)
self.assertIsNone(session.datetime_end)
def test_patch_time_end_keeps_day_and_start(self):
"""Closing a session takes the day and start time from the stored session"""
session = WorkoutSession.objects.get(pk=self.SESSION)
start = session.datetime_start
response = self.client.patch(
reverse('workoutsession-detail', kwargs={'pk': self.SESSION}),
data={'time_end': '12:30'},
content_type='application/json',
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
session.refresh_from_db()
self.assertEqual(session.datetime_start, start)
self.assertEqual(
timezone.localtime(session.datetime_end),
timezone.make_aware(
datetime.datetime.combine(
timezone.localtime(start).date(),
datetime.time(12, 30),
)
),
)
def test_the_new_fields_win(self):
"""A request that sends both formats is not overwritten by the deprecated one"""
response = self.client.post(
reverse('workoutsession-list'),
data={
'routine': self.ROUTINE,
'impression': '2',
'date': '2020-01-01',
'time_start': '08:00',
'datetime_start': '2025-03-12T10:00:00Z',
},
content_type='application/json',
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
session = WorkoutSession.objects.get(pk=response.json()['id'])
self.assertEqual(
session.datetime_start,
datetime.datetime(2025, 3, 12, 10, 0, tzinfo=datetime.timezone.utc),
)
def test_filter_by_day(self):
"""The viewset has a filterset, so a day can be selected without an error"""
@@ -413,26 +265,3 @@ class WorkoutSessionLegacyFieldsTestCase(WgerTestCase):
{'datetime_start__date': (day + datetime.timedelta(days=1)).isoformat()},
)
self.assertEqual(response.json()['results'], [])
def test_untouched_when_no_deprecated_field_is_sent(self):
"""A request without the deprecated fields leaves the timestamps alone"""
session = WorkoutSession.objects.get(pk=self.SESSION)
response = self.client.patch(
reverse('workoutsession-detail', kwargs={'pk': self.SESSION}),
data={'notes': 'Only the notes change'},
content_type='application/json',
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
session.refresh_from_db()
self.assertEqual(session.notes, 'Only the notes change')
self.assertEqual(
session.datetime_start,
datetime.datetime(2025, 11, 1, 10, 0, tzinfo=datetime.timezone.utc),
)
self.assertEqual(
session.datetime_end,
datetime.datetime(2025, 11, 1, 10, 15, tzinfo=datetime.timezone.utc),
)