diff --git a/lib/features/routines/providers/gym_state.dart b/lib/features/routines/providers/gym_state.dart index 869aaa5e1..ef5b5c9ac 100644 --- a/lib/features/routines/providers/gym_state.dart +++ b/lib/features/routines/providers/gym_state.dart @@ -21,7 +21,6 @@ import 'package:material_ui/material_ui.dart'; import 'package:wger/features/exercises/models/exercise.dart'; import 'package:wger/features/routines/models/added_exercise.dart'; import 'package:wger/features/routines/models/day_data.dart'; -import 'package:wger/features/routines/models/log.dart'; import 'package:wger/features/routines/models/page_progress.dart'; import 'package:wger/features/routines/models/routine.dart'; import 'package:wger/features/routines/models/set_config_data.dart'; @@ -179,14 +178,10 @@ class GymModeState { final bool showWorkoutDuration; /// Whether the log form of a set is pre-filled with the values last - /// logged for the same exercise during this workout, instead of the - /// planned ones. Disabled by default. + /// logged for the same exercise, in this or an earlier workout, instead + /// of the planned ones. Disabled by default. final bool stickySetValues; - /// The values last logged per exercise during this workout, used to - /// pre-fill the log form when [stickySetValues] is enabled. - final Map lastLoggedValues; - /// What happened on the pages so far, by page key. Kept apart from the pages /// so that recalculating them doesn't lose it. final Map progress; @@ -213,7 +208,6 @@ class GymModeState { this.showDistinctLogs = true, this.showWorkoutDuration = true, this.stickySetValues = false, - this.lastLoggedValues = const {}, this.progress = const {}, this.addedExercises = const [], int? dayId, @@ -261,7 +255,6 @@ class GymModeState { bool? showDistinctLogs, bool? showWorkoutDuration, bool? stickySetValues, - Map? lastLoggedValues, Map? progress, List? addedExercises, }) { @@ -287,7 +280,6 @@ class GymModeState { showDistinctLogs: showDistinctLogs ?? this.showDistinctLogs, showWorkoutDuration: showWorkoutDuration ?? this.showWorkoutDuration, stickySetValues: stickySetValues ?? this.stickySetValues, - lastLoggedValues: lastLoggedValues ?? this.lastLoggedValues, progress: progress ?? this.progress, addedExercises: addedExercises ?? this.addedExercises, ); diff --git a/lib/features/routines/providers/gym_state_notifier.dart b/lib/features/routines/providers/gym_state_notifier.dart index 7b9dff9e2..29d6a71a2 100644 --- a/lib/features/routines/providers/gym_state_notifier.dart +++ b/lib/features/routines/providers/gym_state_notifier.dart @@ -259,11 +259,6 @@ class GymStateNotifier extends _$GymStateNotifier { workoutStart: saved.workoutStart, validUntil: saved.validUntil, progress: progress, - // In page order, so the last set of an exercise wins - lastLoggedValues: { - for (final log in slotPages.map((p) => progress[p.key]?.loggedEntry).nonNulls) - log.exerciseId: log, - }, ); _logger.fine('Restored workout progress on page ${state.currentPage}'); @@ -448,8 +443,6 @@ class GymStateNotifier extends _$GymStateNotifier { // A fresh workout also restarts the elapsed timer and the resume window workoutStart: shouldReset ? clock.now() : null, validUntil: shouldReset ? clock.now().add(DEFAULT_DURATION) : null, - // An abandoned workout never reaches clear(), so forget its values here - lastLoggedValues: shouldReset ? const {} : null, progress: shouldReset ? const {} : null, addedExercises: shouldReset ? const [] : null, ); @@ -484,7 +477,7 @@ class GymStateNotifier extends _$GymStateNotifier { /// Seeds the log form of the current page with a fresh entry, also to log /// another set on a page that was already logged. - void startNewEntry() { + Future startNewEntry() async { // Ensure that there is a log entry for the current slot entry final slotEntryPage = state.getSlotEntryPageByIndex(); if (slotEntryPage == null || slotEntryPage.setConfigData == null) { @@ -497,13 +490,20 @@ class GymStateNotifier extends _$GymStateNotifier { iteration: state.iteration, ); final logNotifier = ref.read(gymLogProvider.notifier)..setLog(log); + if (!state.stickySetValues) { + return; + } - // Pre-fill with the values last logged for this exercise during this - // workout (e.g. when dialing in the weight over the first sets), if enabled - final lastValues = state.stickySetValues - ? state.lastLoggedValues[slotEntryPage.setConfigData!.exerciseId] - : null; - if (lastValues != null) { + // Pre-fill with the values last logged for this exercise, in this or any + // earlier workout. Read from the DB so they survive however gym mode was + // left, and a corrected earlier set keeps its date and doesn't win. + final seeded = ref.read(gymLogProvider); + final lastValues = await ref + .read(workoutLogRepositoryProvider) + .getLatestLogByExercise(slotEntryPage.setConfigData!.exerciseId); + + // Leave the form alone if the user already moved on or started typing + if (lastValues != null && ref.mounted && identical(ref.read(gymLogProvider), seeded)) { logNotifier.copyValuesFrom(lastValues); } } @@ -556,15 +556,6 @@ class GymStateNotifier extends _$GymStateNotifier { _savePrefs(); } - /// Remembers the values logged for the log's exercise so that the next - /// set of the exercise can be pre-filled with them, see - /// [GymModeState.stickySetValues]. - void recordLoggedValues(Log log) { - final updated = Map.of(state.lastLoggedValues); - updated[log.exerciseId] = log; - state = state.copyWith(lastLoggedValues: updated); - } - /// Applies [update] to the progress of the page with [key] void _updateProgress(String key, PageProgress Function(PageProgress) update) { state = state.copyWith(progress: {...state.progress, key: update(state.progressOf(key))}); @@ -688,7 +679,6 @@ class GymStateNotifier extends _$GymStateNotifier { isInitialized: false, pages: [], currentPage: 0, - lastLoggedValues: const {}, progress: const {}, addedExercises: const [], diff --git a/lib/features/routines/providers/gym_state_notifier.g.dart b/lib/features/routines/providers/gym_state_notifier.g.dart index 9e8adfb2f..a4682dc24 100644 --- a/lib/features/routines/providers/gym_state_notifier.g.dart +++ b/lib/features/routines/providers/gym_state_notifier.g.dart @@ -40,7 +40,7 @@ final class GymStateNotifierProvider extends $NotifierProvider r'6edef80da81e457a1d2b600dc205194d34adb407'; +String _$gymStateNotifierHash() => r'c03c5ee5ca6f1db5d63193e15744589f12486ea4'; abstract class _$GymStateNotifier extends $Notifier { GymModeState build(); diff --git a/lib/features/routines/providers/workout_logs_repository.dart b/lib/features/routines/providers/workout_logs_repository.dart index 4346cc226..ce2294fe0 100644 --- a/lib/features/routines/providers/workout_logs_repository.dart +++ b/lib/features/routines/providers/workout_logs_repository.dart @@ -75,6 +75,17 @@ class WorkoutLogRepository { return query.watch().map((rows) => rows.map(_readWithUnits).toList()); } + /// The newest log of an exercise across all routines, with its units, or + /// null if the exercise was never logged + Future getLatestLogByExercise(int exerciseId) async { + final query = _selectWithUnits() + ..where(_db.workoutLogTable.exerciseId.equals(exerciseId)) + ..orderBy([OrderingTerm(expression: _db.workoutLogTable.date, mode: OrderingMode.desc)]) + ..limit(1); + final row = await query.getSingleOrNull(); + return row == null ? null : _readWithUnits(row); + } + /// The logs with one of the [ids] that exist locally, with their units Future> getLogsByIds(List ids) async { final query = _selectWithUnits()..where(_db.workoutLogTable.id.isIn(ids)); diff --git a/lib/features/routines/widgets/gym_mode/log_page.dart b/lib/features/routines/widgets/gym_mode/log_page.dart index f7d70ea8a..412b1b4e6 100644 --- a/lib/features/routines/widgets/gym_mode/log_page.dart +++ b/lib/features/routines/widgets/gym_mode/log_page.dart @@ -414,12 +414,6 @@ class _LogFormWidgetState extends ConsumerState { } gymProvider.markSlotPageAsDone(page.key, isDone: true, log: log); - - // Correcting an earlier set must not replace a later set's values - final lastLogged = gymState.lastLoggedValues[log.exerciseId]; - if (isNewEntry || lastLogged?.id == log.id) { - gymProvider.recordLoggedValues(log); - } showSnackbar( context, i18n.successfullySaved, diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 5148a8e7b..98aedeaed 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -1179,6 +1179,6 @@ "calculationHelpWindowDays": "{min} bis {max}. Wie weit zurück ein bester Satz zählt.", "useDynamicColor": "Dynamische Farben verwenden", "gymModeStickySetValues": "Werte des letzten Satzes übernehmen", - "gymModeStickySetValuesHelp": "Den nächsten Satz einer Übung mit den Werten vorbelegen, die du in diesem Training zuletzt dafür eingetragen hast", + "gymModeStickySetValuesHelp": "Den nächsten Satz einer Übung mit den Werten vorbelegen, die du zuletzt dafür eingetragen hast", "upNext": "Als Nächstes" } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 7f1d75eca..8839af841 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -415,7 +415,7 @@ "@gymModeStickySetValues": { "description": "Label for a gym mode setting: when enabled, the next set of an exercise is pre-filled with the values last logged instead of the planned ones" }, - "gymModeStickySetValuesHelp": "Pre-fill the next set of an exercise with the values you last logged for it during this workout", + "gymModeStickySetValuesHelp": "Pre-fill the next set of an exercise with the values you last logged for it", "@gymModeStickySetValuesHelp": { "description": "Help text for the sticky set values setting in the gym mode" }, diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 1b6ee3eac..d8ea971bf 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -1196,6 +1196,6 @@ "calculationHelpWindowDays": "De {min} a {max}. Hasta dónde cuenta la mejor serie.", "useDynamicColor": "Usar color dinámico", "gymModeStickySetValues": "Mantener los valores de la última serie", - "gymModeStickySetValuesHelp": "Rellenar la siguiente serie de un ejercicio con los valores que registraste por última vez durante este entrenamiento", + "gymModeStickySetValuesHelp": "Rellenar la siguiente serie de un ejercicio con los valores que registraste por última vez", "upNext": "A continuación" } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index d15127b8a..47cd4c55c 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -1188,6 +1188,6 @@ "calculationHelpWindowDays": "De {min} à {max}. Jusqu’où remonte la meilleure série.", "useDynamicColor": "Utiliser les couleurs dynamiques", "gymModeStickySetValues": "Reprendre les valeurs de la dernière série", - "gymModeStickySetValuesHelp": "Pré-remplir la série suivante d'un exercice avec les dernières valeurs que vous avez enregistrées pendant cet entraînement", + "gymModeStickySetValuesHelp": "Pré-remplir la série suivante d'un exercice avec les dernières valeurs que vous avez enregistrées", "upNext": "À suivre" } diff --git a/test/features/routines/providers/gym_state_test.dart b/test/features/routines/providers/gym_state_test.dart index 8a4dd8817..03f503be2 100644 --- a/test/features/routines/providers/gym_state_test.dart +++ b/test/features/routines/providers/gym_state_test.dart @@ -16,6 +16,7 @@ * along with this program. If not, see . */ +import 'dart:async'; import 'dart:convert'; import 'package:clock/clock.dart'; @@ -735,9 +736,23 @@ void main() { // slot 1 (exercise 1): overview(1), log(2), timer(3), log(4), timer(5), log(6), timer(7) // slot 2 (exercise 6): overview(8), log(9), ... + late MockWorkoutLogRepository logRepo; + + setUp(() { + logRepo = MockWorkoutLogRepository(); + when(logRepo.getLatestLogByExercise(any)).thenAnswer((_) async => null); + + final initialState = notifier.state; + container = ProviderContainer.test( + overrides: [workoutLogRepositoryProvider.overrideWithValue(logRepo)], + ); + notifier = container.read(gymStateProvider.notifier)..state = initialState; + }); + Log buildLoggedValues() { final slotPage = notifier.state.pages[1].slotPages[1]; return Log.fromSetConfigData(slotPage.setConfigData!, routineId: 1, iteration: 1) + ..id = 'log-1' ..repetitions = 7 ..weight = 42.5 ..rir = 1; @@ -753,106 +768,72 @@ void main() { expect(await PreferenceHelper.asyncPref.getBool(PREFS_STICKY_SET_VALUES), true); }); - test( - 'Pre-fills the next set of the exercise with the last logged values when enabled', - () async { - // Arrange - notifier.setStickySetValues(true); - await pumpEventQueue(); - notifier.recordLoggedValues(buildLoggedValues()); - - // Act: navigate to the second set of the same exercise - notifier.setCurrentPage(4); - - // Assert - final gymLog = container.read(gymLogProvider)!; - expect(gymLog.repetitions, 7); - expect(gymLog.weight, 42.5); - expect(gymLog.rir, 1); - expect(gymLog.id, isNull, reason: 'A fresh log is seeded, not a copy of the saved one'); - }, - ); - - test('Pre-fills with the planned values when disabled', () { + test('Pre-fills the set with the last logged values of the exercise when enabled', () async { // Arrange - notifier.recordLoggedValues(buildLoggedValues()); + notifier.setStickySetValues(true); + await pumpEventQueue(); + when(logRepo.getLatestLogByExercise(1)).thenAnswer((_) async => buildLoggedValues()); // Act notifier.setCurrentPage(4); - - // Assert: the values of the set configuration - final gymLog = container.read(gymLogProvider)!; - expect(gymLog.repetitions, 3); - expect(gymLog.weight, 100); - }); - - test('Does not carry values over to a different exercise', () async { - // Arrange - notifier.setStickySetValues(true); await pumpEventQueue(); - notifier.recordLoggedValues(buildLoggedValues()); - - // Act: navigate to the first set of the second exercise - notifier.setCurrentPage(9); - - // Assert: the values of that exercise's set configuration - final gymLog = container.read(gymLogProvider)!; - expect(gymLog.repetitions, 12); - expect(gymLog.weight, 10); - }); - - test('A new workout forgets the values of an abandoned one', () async { - // Arrange: the summary page (and clear()) is never reached - notifier.setStickySetValues(true); - await pumpEventQueue(); - notifier.state = notifier.state.copyWith( - isInitialized: true, - dayId: 1, - validUntil: DateTime(2024, 5, 1, 10, 0), - ); - notifier.recordLoggedValues(buildLoggedValues()); - - // Act - withClock( - Clock.fixed(DateTime(2024, 5, 2, 18, 0)), - () => notifier.initData(getTestRoutine(), 1, 1), - ); - notifier.setCurrentPage(2); - - // Assert: the values of the set configuration - expect(notifier.state.lastLoggedValues, isEmpty); - final gymLog = container.read(gymLogProvider)!; - expect(gymLog.repetitions, 3); - expect(gymLog.weight, 100); - }); - - test('Resuming the same workout keeps the logged values', () async { - // Arrange - notifier.setStickySetValues(true); - await pumpEventQueue(); - notifier.state = notifier.state.copyWith(isInitialized: true, dayId: 1); - notifier.recordLoggedValues(buildLoggedValues()); - - // Act - notifier.initData(getTestRoutine(), 1, 1); - notifier.setCurrentPage(4); // Assert final gymLog = container.read(gymLogProvider)!; expect(gymLog.repetitions, 7); expect(gymLog.weight, 42.5); + expect(gymLog.rir, 1); + expect(gymLog.id, isNull, reason: 'A fresh log is seeded, not a copy of the saved one'); }); - test('Clearing the state forgets the logged values', () { + test('Pre-fills with the planned values when disabled', () async { // Arrange - notifier.recordLoggedValues(buildLoggedValues()); - expect(notifier.state.lastLoggedValues, isNotEmpty); + when(logRepo.getLatestLogByExercise(1)).thenAnswer((_) async => buildLoggedValues()); // Act - notifier.clear(); + notifier.setCurrentPage(4); + await pumpEventQueue(); + + // Assert: the values of the set configuration + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.repetitions, 3); + expect(gymLog.weight, 100); + verifyNever(logRepo.getLatestLogByExercise(any)); + }); + + test('Pre-fills with the planned values when the exercise was never logged', () async { + // Arrange + notifier.setStickySetValues(true); + await pumpEventQueue(); + + // Act: the first set of the second exercise + notifier.setCurrentPage(9); + await pumpEventQueue(); + + // Assert: the values of that exercise's set configuration + verify(logRepo.getLatestLogByExercise(6)); + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.repetitions, 12); + expect(gymLog.weight, 10); + }); + + test('Does not overwrite values entered while the lookup was running', () async { + // Arrange + notifier.setStickySetValues(true); + await pumpEventQueue(); + final lookup = Completer(); + when(logRepo.getLatestLogByExercise(1)).thenAnswer((_) => lookup.future); + + // Act + notifier.setCurrentPage(4); + container.read(gymLogProvider.notifier).setWeight(55); + lookup.complete(buildLoggedValues()); + await pumpEventQueue(); // Assert - expect(notifier.state.lastLoggedValues, isEmpty); + final gymLog = container.read(gymLogProvider)!; + expect(gymLog.weight, 55); + expect(gymLog.repetitions, 3); }); }); @@ -1115,11 +1096,6 @@ void main() { DateTime(2026, 7, 26, 18, 30), reason: 'the rest that started with the logged set keeps running', ); - expect( - restarted.state.lastLoggedValues[1]!.weight, - 80, - reason: 'the sticky values come from the restored logs', - ); }); test('Restores the rest of the progress when the logs can not be read', () async { diff --git a/test/features/routines/providers/gym_state_test.mocks.dart b/test/features/routines/providers/gym_state_test.mocks.dart index 9ffda94cb..536a2e2bc 100644 --- a/test/features/routines/providers/gym_state_test.mocks.dart +++ b/test/features/routines/providers/gym_state_test.mocks.dart @@ -50,6 +50,14 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogReposit ) as _i3.Stream>); + @override + _i3.Future<_i4.Log?> getLatestLogByExercise(int? exerciseId) => + (super.noSuchMethod( + Invocation.method(#getLatestLogByExercise, [exerciseId]), + returnValue: _i3.Future<_i4.Log?>.value(), + ) + as _i3.Future<_i4.Log?>); + @override _i3.Future> getLogsByIds(List? ids) => (super.noSuchMethod( diff --git a/test/features/routines/providers/workout_logs_notifier_test.mocks.dart b/test/features/routines/providers/workout_logs_notifier_test.mocks.dart index 614da26dc..ded5ef543 100644 --- a/test/features/routines/providers/workout_logs_notifier_test.mocks.dart +++ b/test/features/routines/providers/workout_logs_notifier_test.mocks.dart @@ -50,6 +50,14 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogReposit ) as _i3.Stream>); + @override + _i3.Future<_i4.Log?> getLatestLogByExercise(int? exerciseId) => + (super.noSuchMethod( + Invocation.method(#getLatestLogByExercise, [exerciseId]), + returnValue: _i3.Future<_i4.Log?>.value(), + ) + as _i3.Future<_i4.Log?>); + @override _i3.Future> getLogsByIds(List? ids) => (super.noSuchMethod( diff --git a/test/features/routines/providers/workout_logs_repository_test.dart b/test/features/routines/providers/workout_logs_repository_test.dart index 3c8b43d78..4875b333b 100644 --- a/test/features/routines/providers/workout_logs_repository_test.dart +++ b/test/features/routines/providers/workout_logs_repository_test.dart @@ -267,6 +267,40 @@ void main() { }); }); + group('getLatestLogByExercise', () { + test('returns null when the exercise was never logged', () async { + await db.into(db.workoutLogTable).insert(makeLog(exerciseId: 2).toCompanion()); + + expect(await repo.getLatestLogByExercise(1), isNull); + }); + + test('returns the newest log of the exercise across routines', () async { + await seedUnits(); + await db + .into(db.workoutLogTable) + .insert(makeLog(date: DateTime.utc(2026, 4, 14), weight: 14).toCompanion()); + await db + .into(db.workoutLogTable) + .insert( + makeLog(routineId: 999, date: DateTime.utc(2026, 4, 16), weight: 16).toCompanion(), + ); + await db + .into(db.workoutLogTable) + .insert(makeLog(date: DateTime.utc(2026, 4, 15), weight: 15).toCompanion()); + // Newer, but a different exercise + await db + .into(db.workoutLogTable) + .insert( + makeLog(exerciseId: 2, date: DateTime.utc(2026, 4, 17), weight: 17).toCompanion(), + ); + + final log = await repo.getLatestLogByExercise(1); + + expect(log!.weight, 16); + expect(log.weightUnitObj?.name, 'kg'); + }); + }); + group('updateLocalDrift', () { test('overwrites the row with matching id', () async { final log = makeLog(sessionId: 'session-1', weight: 50); diff --git a/test/features/routines/screens/gym_mode_test.mocks.dart b/test/features/routines/screens/gym_mode_test.mocks.dart index 95fc3f0ab..ccf083404 100644 --- a/test/features/routines/screens/gym_mode_test.mocks.dart +++ b/test/features/routines/screens/gym_mode_test.mocks.dart @@ -553,6 +553,14 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i27.WorkoutLogReposi ) as _i10.Stream>); + @override + _i10.Future<_i28.Log?> getLatestLogByExercise(int? exerciseId) => + (super.noSuchMethod( + Invocation.method(#getLatestLogByExercise, [exerciseId]), + returnValue: _i10.Future<_i28.Log?>.value(), + ) + as _i10.Future<_i28.Log?>); + @override _i10.Future> getLogsByIds(List? ids) => (super.noSuchMethod( diff --git a/test/features/routines/screens/routine_logs_screen_test.mocks.dart b/test/features/routines/screens/routine_logs_screen_test.mocks.dart index c2ab95ffc..e36f8f31e 100644 --- a/test/features/routines/screens/routine_logs_screen_test.mocks.dart +++ b/test/features/routines/screens/routine_logs_screen_test.mocks.dart @@ -156,6 +156,14 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i9.WorkoutLogReposit ) as _i5.Stream>); + @override + _i5.Future<_i10.Log?> getLatestLogByExercise(int? exerciseId) => + (super.noSuchMethod( + Invocation.method(#getLatestLogByExercise, [exerciseId]), + returnValue: _i5.Future<_i10.Log?>.value(), + ) + as _i5.Future<_i10.Log?>); + @override _i5.Future> getLogsByIds(List? ids) => (super.noSuchMethod( diff --git a/test/features/routines/widgets/gym_mode/log_page_test.dart b/test/features/routines/widgets/gym_mode/log_page_test.dart index eaa41adc6..4d4a093a2 100644 --- a/test/features/routines/widgets/gym_mode/log_page_test.dart +++ b/test/features/routines/widgets/gym_mode/log_page_test.dart @@ -70,17 +70,39 @@ void main() { late ProviderContainer container; late MockWorkoutLogRepository mockWorkoutLogRepo; + /// What the mocked repository wrote, so the sticky values can be read back + late List storedLogs; + + void storeLog(Log log) { + storedLogs + ..removeWhere((l) => l.id == log.id) + ..add(log.copyWith()); + } + setUp(() { SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); testExercises = getTestExercises(); mockWorkoutLogRepo = MockWorkoutLogRepository(); + storedLogs = []; // Mimic the real insert: the freshly minted id is written back to the log when( mockWorkoutLogRepo.addLocalDrift(any, dayId: anyNamed('dayId')), ).thenAnswer((invocation) async { - (invocation.positionalArguments[0] as Log).id = 'new-log-id'; + storeLog((invocation.positionalArguments[0] as Log)..id = 'new-log-id'); + }); + when(mockWorkoutLogRepo.updateLocalDrift(any)).thenAnswer((invocation) async { + storeLog(invocation.positionalArguments[0] as Log); + }); + // Newest first like the real query, on equal dates the later write wins + when(mockWorkoutLogRepo.getLatestLogByExercise(any)).thenAnswer((invocation) async { + final exerciseId = invocation.positionalArguments[0] as int; + return storedLogs + .where((l) => l.exerciseId == exerciseId) + .fold( + null, + (newest, l) => newest == null || !l.date.isBefore(newest.date) ? l : newest, + ); }); - when(mockWorkoutLogRepo.updateLocalDrift(any)).thenAnswer((_) async {}); // Past logs on the page come from this stream (per exercise); reuse the // test routine's logs so the previous-entries assertions keep working. when( @@ -311,7 +333,7 @@ void main() { when( mockWorkoutLogRepo.addLocalDrift(any, dayId: anyNamed('dayId')), ).thenAnswer((invocation) async { - (invocation.positionalArguments[0] as Log).id = 'log-${++count}'; + storeLog((invocation.positionalArguments[0] as Log)..id = 'log-${++count}'); }); }); @@ -329,6 +351,7 @@ void main() { // Set 3 is pre-filled with the values of set 2 container.read(gymStateProvider.notifier).setCurrentPage(6); + await tester.pump(); final gymLog = container.read(gymLogProvider)!; expect(gymLog.repetitions, 14); expect(gymLog.weight, 40); @@ -346,6 +369,7 @@ void main() { // Set 2 is pre-filled with the corrected values container.read(gymStateProvider.notifier).setCurrentPage(4); + await tester.pump(); final gymLog = container.read(gymLogProvider)!; expect(gymLog.repetitions, 12); expect(gymLog.weight, 36); diff --git a/test/features/routines/widgets/gym_mode/log_page_test.mocks.dart b/test/features/routines/widgets/gym_mode/log_page_test.mocks.dart index 3853e98bc..4340f2626 100644 --- a/test/features/routines/widgets/gym_mode/log_page_test.mocks.dart +++ b/test/features/routines/widgets/gym_mode/log_page_test.mocks.dart @@ -50,6 +50,22 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogReposit ) as _i3.Stream>); + @override + _i3.Future<_i4.Log?> getLatestLogByExercise(int? exerciseId) => + (super.noSuchMethod( + Invocation.method(#getLatestLogByExercise, [exerciseId]), + returnValue: _i3.Future<_i4.Log?>.value(), + ) + as _i3.Future<_i4.Log?>); + + @override + _i3.Future> getLogsByIds(List? ids) => + (super.noSuchMethod( + Invocation.method(#getLogsByIds, [ids]), + returnValue: _i3.Future>.value(<_i4.Log>[]), + ) + as _i3.Future>); + @override _i3.Future deleteLocalDrift(String? id) => (super.noSuchMethod(