Move set logging and rest skipping into the gym mode notifier

This commit is contained in:
Roland Geider
2026-10-08 16:50:52 +02:00
parent 016568b6b7
commit 23c99ba2ba
5 changed files with 362 additions and 18 deletions

View File

@@ -31,6 +31,8 @@ import 'package:wger/features/routines/models/weight_unit.dart';
import 'package:wger/features/routines/providers/gym_log_notifier.dart';
import 'package:wger/features/routines/providers/gym_state.dart';
import 'package:wger/features/routines/providers/routines_notifier.dart';
import 'package:wger/features/routines/providers/workout_logs_notifier.dart';
import 'package:wger/features/routines/validators.dart';
part 'gym_state_notifier.g.dart';
@@ -317,12 +319,76 @@ class GymStateNotifier extends _$GymStateNotifier {
return;
}
final log = Log.fromSetConfigData(
slotEntryPage.setConfigData!,
routineId: state.routine.id,
iteration: state.iteration,
);
ref.read(gymLogProvider.notifier).setLog(log);
ref.read(gymLogProvider.notifier).setLog(_draftFor(slotEntryPage));
}
/// The log draft a slot page starts with, prefilled with the planned values
Log _draftFor(SlotPageEntry slotPage) => Log.fromSetConfigData(
slotPage.setConfigData!,
routineId: state.routine.id,
iteration: state.iteration,
);
/// Ends the rest of the current timer page and moves on. No-op on other pages.
void skipRest() {
if (state.getSlotEntryPageByIndex()?.type != SlotPageType.timer) {
return;
}
setCurrentPage(state.currentPage + 1);
}
/// Saves the log draft of the current log page, marks the page as done and
/// moves on to the next page. A failed write propagates to the caller.
Future<void> logCurrentSet() async {
final slotPage = state.getSlotEntryPageByIndex();
final log = ref.read(gymLogProvider);
if (slotPage == null || slotPage.type != SlotPageType.log || log == null) {
_logger.warning('logCurrentSet called without a log draft on a log page');
return;
}
// Done before the write, so a repeated logPlannedSet is rejected meanwhile
markSlotPageAsDone(slotPage.uuid, isDone: true);
try {
await ref.read(workoutLogProvider).addEntry(log, dayId: state.dayId);
} catch (_) {
markSlotPageAsDone(slotPage.uuid, isDone: false);
rethrow;
}
// The user may have moved on or left gym mode during the write
if (state.currentPage == slotPage.pageIndex) {
setCurrentPage(slotPage.pageIndex + 1);
}
}
/// Logs the set of the log page [slotPageUuid] without the UI, e.g. from a
/// notification. From the rest right before it the planned values are logged,
/// on the page itself the current draft. False if stale, done or incomplete.
Future<bool> logPlannedSet(String slotPageUuid) async {
final target = state.getSlotPageByUUID(slotPageUuid);
if (target == null || target.type != SlotPageType.log || target.logDone) {
return false;
}
final onTarget = state.currentPage == target.pageIndex;
final onRestBefore =
state.currentPage == target.pageIndex - 1 &&
state.getSlotEntryPageByIndex()?.type == SlotPageType.timer;
if (!onTarget && !onRestBefore) {
return false;
}
final log = onTarget ? ref.read(gymLogProvider) : _draftFor(target);
if (log == null || !isWorkoutLogComplete(repetitions: log.repetitions, weight: log.weight)) {
return false;
}
if (onRestBefore) {
setCurrentPage(target.pageIndex);
}
await logCurrentSet();
return true;
}
/// Starts the rest when on a timer page, ends it everywhere else. A rest

View File

@@ -19,15 +19,18 @@
import 'package:wger/features/routines/models/session.dart';
import 'package:wger/l10n/generated/app_localizations.dart';
/// Cross-field validation for a workout log entry, mirroring the
/// reachable part of the backend `WorkoutLog.clean()` rule: at least
/// one of [repetitions] or [weight] must be set.
/// Whether a workout log entry passes the reachable part of the backend
/// `WorkoutLog.clean()` rule: at least one of [repetitions] or [weight] is set.
bool isWorkoutLogComplete({required num? repetitions, required num? weight}) =>
repetitions != null || weight != null;
/// Cross-field validation for a workout log entry, see [isWorkoutLogComplete]
String? validateWorkoutLogCrossField({
required num? repetitions,
required num? weight,
required AppLocalizations i18n,
}) {
if (repetitions == null && weight == null) {
if (!isWorkoutLogComplete(repetitions: repetitions, weight: weight)) {
return i18n.weightOrRepsRequired;
}
return null;

View File

@@ -301,7 +301,6 @@ class _LogFormWidgetState extends ConsumerState<LogFormWidget> {
@override
Widget build(BuildContext context) {
final i18n = AppLocalizations.of(context);
final logProvider = ref.read(workoutLogProvider);
final log = ref.watch(gymLogProvider);
// The log is populated when the page becomes current: the PageView can lay
@@ -387,18 +386,13 @@ class _LogFormWidgetState extends ConsumerState<LogFormWidget> {
return;
}
final gymState = ref.read(gymStateProvider);
final gymProvider = ref.read(gymStateProvider.notifier);
final page = gymState.getSlotEntryPageByIndex()!;
// A failed write is intentionally left to propagate to the global
// error handler; the success path below is then skipped.
await logProvider.addEntry(log, dayId: gymState.dayId);
await ref.read(gymStateProvider.notifier).logCurrentSet();
if (!context.mounted) {
return;
}
gymProvider.markSlotPageAsDone(page.uuid, isDone: true);
showSnackbar(
context,
i18n.successfullySaved,

View File

@@ -16,10 +16,13 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:async';
import 'package:clock/clock.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:material_ui/material_ui.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
@@ -30,26 +33,36 @@ import 'package:wger/features/account/providers/user_profile_repository.dart';
import 'package:wger/features/exercises/models/exercise.dart';
import 'package:wger/features/routines/models/day.dart';
import 'package:wger/features/routines/models/day_data.dart';
import 'package:wger/features/routines/models/log.dart';
import 'package:wger/features/routines/models/routine.dart';
import 'package:wger/features/routines/models/set_config_data.dart';
import 'package:wger/features/routines/models/slot_data.dart';
import 'package:wger/features/routines/providers/gym_log_notifier.dart';
import 'package:wger/features/routines/providers/gym_state.dart';
import 'package:wger/features/routines/providers/gym_state_notifier.dart';
import 'package:wger/features/routines/providers/routines_notifier.dart';
import 'package:wger/features/routines/providers/workout_logs_repository.dart';
import '../../../../test_data/exercises.dart';
import '../../../../test_data/routines.dart';
import '../helpers/routine_form_test_overrides.dart';
import 'gym_state_test.mocks.dart';
@GenerateMocks([WorkoutLogRepository])
void main() {
late GymStateNotifier notifier;
late ProviderContainer container;
late MockWorkoutLogRepository mockLogRepo;
setUp(() {
TestWidgetsFlutterBinding.ensureInitialized();
SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty();
container = ProviderContainer.test();
mockLogRepo = MockWorkoutLogRepository();
when(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).thenAnswer((_) async {});
container = ProviderContainer.test(
overrides: [workoutLogRepositoryProvider.overrideWithValue(mockLogRepo)],
);
notifier = container.read(gymStateProvider.notifier);
notifier.state = notifier.state.copyWith(
showExercisePages: true,
@@ -605,6 +618,195 @@ void main() {
});
});
group('GymStateNotifier logging and skipping', () {
final start = DateTime.utc(2024, 5, 1, 17, 30);
List<SlotPageEntry> slotPages() => notifier.state.pages.expand((p) => p.slotPages).toList();
// First slot of the fixture: overview, then log/timer pairs with 3x100kg
// and a rest time of 120 s
SlotPageEntry firstLog() => slotPages().firstWhere((p) => p.type == SlotPageType.log);
SlotPageEntry secondLog() => slotPages().where((p) => p.type == SlotPageType.log).elementAt(1);
Log capturedLog() =>
verify(mockLogRepo.addLocalDrift(captureAny, dayId: anyNamed('dayId'))).captured.single
as Log;
test('logCurrentSet saves the draft, marks the page done and starts the rest', () async {
final log = firstLog();
notifier.setCurrentPage(log.pageIndex);
container.read(gymLogProvider.notifier).setRepetitions(12);
await withClock(Clock.fixed(start), notifier.logCurrentSet);
final captured = verify(
mockLogRepo.addLocalDrift(captureAny, dayId: captureAnyNamed('dayId')),
).captured;
expect((captured[0] as Log).repetitions, 12);
expect(captured[1], 1);
expect(notifier.state.getSlotPageByUUID(log.uuid)!.logDone, isTrue);
expect(notifier.state.currentPage, log.pageIndex + 1);
expect(notifier.state.restEndsAt, start.add(const Duration(seconds: 120)));
});
test('logCurrentSet keeps the page open when the write fails', () async {
final log = firstLog();
notifier.setCurrentPage(log.pageIndex);
when(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).thenThrow(Exception('db'));
await expectLater(notifier.logCurrentSet(), throwsException);
expect(notifier.state.getSlotPageByUUID(log.uuid)!.logDone, isFalse);
expect(notifier.state.currentPage, log.pageIndex);
});
test('logCurrentSet does not move on when the user left the page meanwhile', () async {
final write = Completer<void>();
when(
mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId')),
).thenAnswer((_) => write.future);
notifier.setCurrentPage(firstLog().pageIndex);
final saving = notifier.logCurrentSet();
notifier.setCurrentPage(0);
write.complete();
await saving;
expect(notifier.state.currentPage, 0);
});
test('logPlannedSet from the rest before the set logs the planned values', () async {
final log = secondLog();
notifier.setCurrentPage(log.pageIndex - 1);
final logged = await withClock(
Clock.fixed(start),
() => notifier.logPlannedSet(log.uuid),
);
expect(logged, isTrue);
final saved = capturedLog();
expect(saved.repetitions, log.setConfigData!.repetitions);
expect(saved.weight, log.setConfigData!.weight);
expect(notifier.state.getSlotPageByUUID(log.uuid)!.logDone, isTrue);
expect(notifier.state.currentPage, log.pageIndex + 1);
expect(notifier.state.restStartedAt, start);
});
test('logPlannedSet on the set page itself logs the edited draft', () async {
final log = secondLog();
notifier.setCurrentPage(log.pageIndex);
container.read(gymLogProvider.notifier).setRepetitions(7);
expect(await notifier.logPlannedSet(log.uuid), isTrue);
expect(capturedLog().repetitions, 7);
});
test('logPlannedSet on the set page needs the draft', () async {
// A restored state points at the page before onPageChanged seeds the draft
final log = secondLog();
notifier.state = notifier.state.copyWith(currentPage: log.pageIndex);
expect(await notifier.logPlannedSet(log.uuid), isFalse);
verifyNever(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId')));
});
test('logPlannedSet ignores a second action while the first one is saving', () async {
final write = Completer<void>();
when(
mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId')),
).thenAnswer((_) => write.future);
final log = secondLog();
notifier.setCurrentPage(log.pageIndex - 1);
final first = notifier.logPlannedSet(log.uuid);
final second = await notifier.logPlannedSet(log.uuid);
write.complete();
expect(second, isFalse);
expect(await first, isTrue);
verify(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId'))).called(1);
});
test('logPlannedSet ignores stale actions', () async {
final log = secondLog();
notifier.setCurrentPage(log.pageIndex - 1);
final timerUuid = notifier.state.getSlotEntryPageByIndex()!.uuid;
expect(await notifier.logPlannedSet('unknown'), isFalse, reason: 'unknown page');
expect(await notifier.logPlannedSet(timerUuid), isFalse, reason: 'not a log page');
expect(await notifier.logPlannedSet(firstLog().uuid), isFalse, reason: 'not the next set');
notifier.markSlotPageAsDone(log.uuid, isDone: true);
expect(await notifier.logPlannedSet(log.uuid), isFalse, reason: 'already logged');
verifyNever(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId')));
expect(notifier.state.currentPage, log.pageIndex - 1);
});
test('logPlannedSet only starts from a rest, not from the exercise overview', () async {
final log = firstLog();
notifier.setCurrentPage(log.pageIndex - 1);
expect(notifier.state.getSlotEntryPageByIndex()!.type, SlotPageType.exerciseOverview);
expect(await notifier.logPlannedSet(log.uuid), isFalse);
verifyNever(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId')));
});
test('logPlannedSet leaves a set without planned values to the app', () async {
final config = SetConfigData(
exerciseId: 1,
exercise: getTestExercises().first,
slotEntryId: 1,
nrOfSets: 1,
repetitions: null,
weight: null,
restTime: 60,
textRepr: '',
);
final routine = getTestRoutine()
..dayDataGym = [
DayData(
iteration: 1,
date: DateTime(2024, 11, 1),
day: Day(id: 1, routineId: 1, name: 'Open sets'),
slots: [
SlotData(isSuperset: false, exerciseIds: [1], setConfigs: [config, config]),
],
),
];
notifier.state = notifier.state.copyWith(routine: routine);
notifier.calculatePages();
final log = secondLog();
notifier.setCurrentPage(log.pageIndex - 1);
expect(await notifier.logPlannedSet(log.uuid), isFalse);
verifyNever(mockLogRepo.addLocalDrift(any, dayId: anyNamed('dayId')));
expect(notifier.state.currentPage, log.pageIndex - 1, reason: 'stays on the rest');
});
test('skipRest moves from the timer page to the next set', () {
final log = secondLog();
notifier.setCurrentPage(log.pageIndex - 1);
notifier.skipRest();
expect(notifier.state.currentPage, log.pageIndex);
expect(notifier.state.restStartedAt, isNull);
});
test('skipRest does nothing outside a rest', () {
final log = firstLog();
notifier.setCurrentPage(log.pageIndex);
notifier.skipRest();
expect(notifier.state.currentPage, log.pageIndex);
});
});
group('GymStateNotifier.startWorkout', () {
test('Resets the workout start time to now', () {
// Arrange

View File

@@ -0,0 +1,79 @@
// Mocks generated by Mockito from annotations
// in wger/test/features/routines/providers/gym_state_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'package:wger/features/routines/models/log.dart' as _i4;
import 'package:wger/features/routines/providers/workout_logs_repository.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: experimental_member_use
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: must_be_immutable
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
// ignore_for_file: invalid_use_of_internal_member
/// A class which mocks [WorkoutLogRepository].
///
/// See the documentation for Mockito's code generation for more information.
class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogRepository {
MockWorkoutLogRepository() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Stream<List<_i4.Log>> watchLogsByExerciseDrift({
int? routineId,
required int? exerciseId,
DateTime? since,
}) =>
(super.noSuchMethod(
Invocation.method(#watchLogsByExerciseDrift, [], {
#routineId: routineId,
#exerciseId: exerciseId,
#since: since,
}),
returnValue: _i3.Stream<List<_i4.Log>>.empty(),
)
as _i3.Stream<List<_i4.Log>>);
@override
_i3.Future<void> deleteLocalDrift(String? id) =>
(super.noSuchMethod(
Invocation.method(#deleteLocalDrift, [id]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> updateLocalDrift(_i4.Log? log) =>
(super.noSuchMethod(
Invocation.method(#updateLocalDrift, [log]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> addLocalDrift(_i4.Log? log, {int? dayId}) =>
(super.noSuchMethod(
Invocation.method(#addLocalDrift, [log], {#dayId: dayId}),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
}