From b90d0a0008949bf2974bcdfa22fbca76f938040b Mon Sep 17 00:00:00 2001 From: Roland Geider Date: Thu, 13 May 2021 13:19:07 +0200 Subject: [PATCH] Fetch plan details when visiting the detail page See #14 --- lib/models/workouts/workout_plan.dart | 1 + lib/providers/workout_plans.dart | 49 ++++++-- lib/screens/dashboard.dart | 31 ++++-- lib/screens/workout_plan_screen.dart | 155 +++++++++++++++----------- test/workout_form_test.dart | 41 ++++--- test/workout_form_test.mocks.dart | 19 +++- 6 files changed, 188 insertions(+), 108 deletions(-) diff --git a/lib/models/workouts/workout_plan.dart b/lib/models/workouts/workout_plan.dart index 71a15f453..c5fd8aa8c 100644 --- a/lib/models/workouts/workout_plan.dart +++ b/lib/models/workouts/workout_plan.dart @@ -61,6 +61,7 @@ class WorkoutPlan { WorkoutPlan.empty() { creationDate = DateTime.now(); name = ''; + description = ''; } // Boilerplate diff --git a/lib/providers/workout_plans.dart b/lib/providers/workout_plans.dart index adb3f3d86..60ce217ac 100644 --- a/lib/providers/workout_plans.dart +++ b/lib/providers/workout_plans.dart @@ -124,28 +124,62 @@ class WorkoutPlansProvider extends WgerBaseProvider with ChangeNotifier { * Workouts */ - Future fetchAndSetAllPlans() async { + /// Fetches and sets all workout plans fully, i.e. with all corresponding child + /// attributes + Future fetchAndSetAllPlansFull() async { final data = await fetch(makeUrl(_workoutPlansUrlPath, query: {'ordering': '-creation_date'})); for (final entry in data['results']) { - await fetchAndSetWorkoutPlan(entry['id']); + await fetchAndSetWorkoutPlanFull(entry['id']); } notifyListeners(); } - Future fetchAndSetWorkoutPlan(int workoutId) async { + /// Fetches all workout plan sparsely, i.e. only with the data on the plan + /// object itself and no child attributes + Future fetchAndSetAllPlansSparse() async { + final data = await fetch(makeUrl(_workoutPlansUrlPath, query: {'ordering': '-creation_date'})); + for (final entry in data['results']) { + await fetchAndSetPlanSparse(entry['id']); + } + + notifyListeners(); + } + + /// Fetches a workout plan sparsely, i.e. only with the data on the plan + /// object itself and no child attributes + Future fetchAndSetPlanSparse(int planId) async { + final fullPlanData = await fetch( + makeUrl(_workoutPlansUrlPath, id: planId), + ); + final plan = WorkoutPlan.fromJson(fullPlanData); + _workoutPlans.add(plan); + _workoutPlans.sort((a, b) => b.creationDate.compareTo(a.creationDate)); + + notifyListeners(); + return plan; + } + + /// Fetches a workout plan fully, i.e. with all corresponding child attributes + Future fetchAndSetWorkoutPlanFull(int workoutId) async { // Load a list of all settings so that we can search through it late // // This is a bit ugly, but makes saves sending lots of requests later on - final allSsettingsData = await fetch( + final allSettingsData = await fetch( makeUrl(_settingsUrlPath, query: {'limit': '1000'}), ); + WorkoutPlan plan; + try { + plan = findById(workoutId); + } on StateError catch (e) { + plan = await fetchAndSetPlanSparse(workoutId); + } + // Plan final fullPlanData = await fetch( makeUrl(_workoutPlansUrlPath, id: workoutId, objectMethod: 'canonical_representation'), ); - final plan = WorkoutPlan.fromJson(fullPlanData['obj']); // Days List days = []; @@ -161,7 +195,7 @@ class WorkoutPlansProvider extends WgerBaseProvider with ChangeNotifier { // Settings List settings = []; - final settingData = allSsettingsData['results'].where((s) => s['set'] == workoutSet.id); + final settingData = allSettingsData['results'].where((s) => s['set'] == workoutSet.id); for (final settingEntry in settingData) { final workoutSetting = Setting.fromJson(settingEntry); @@ -202,9 +236,8 @@ class WorkoutPlansProvider extends WgerBaseProvider with ChangeNotifier { } // ... and done - _workoutPlans.add(plan); - _workoutPlans.sort((a, b) => b.creationDate.compareTo(a.creationDate)); notifyListeners(); + return plan; } Future addWorkout(WorkoutPlan workout) async { diff --git a/lib/screens/dashboard.dart b/lib/screens/dashboard.dart index 37528d474..4e76a1793 100644 --- a/lib/screens/dashboard.dart +++ b/lib/screens/dashboard.dart @@ -60,29 +60,36 @@ class _DashboardScreenState extends State { if (!Provider.of(context, listen: false).dataInit) { Provider.of(context, listen: false).setServerVersion(); + final workoutPlansProvider = Provider.of(context, listen: false); + final nutritionPlansProvider = Provider.of(context, listen: false); + final exercisesProvider = Provider.of(context, listen: false); + final galleryProvider = Provider.of(context, listen: false); + final weightProvider = Provider.of(context, listen: false); + // Base data await Future.wait([ - Provider.of(context, listen: false).fetchAndSetUnits(), - Provider.of(context, listen: false).fetchIngredientsFromCache(), - Provider.of(context, listen: false).fetchAndSetExercises(), + workoutPlansProvider.fetchAndSetUnits(), + nutritionPlansProvider.fetchIngredientsFromCache(), + exercisesProvider.fetchAndSetExercises(), ]); // Plans, weight and gallery await Future.wait([ - Provider.of(context, listen: false).fetchAndSetGallery(), - Provider.of(context, listen: false).fetchAndSetAllPlans(), - Provider.of(context, listen: false).fetchAndSetAllPlans(), - Provider.of(context, listen: false).fetchAndSetEntries(), + galleryProvider.fetchAndSetGallery(), + nutritionPlansProvider.fetchAndSetAllPlans(), + workoutPlansProvider.fetchAndSetAllPlansSparse(), + weightProvider.fetchAndSetEntries(), ]); // Nutrition logs - await Provider.of(context, listen: false).fetchAndSetAllLogs(); + await nutritionPlansProvider.fetchAndSetAllLogs(); // Current workout plan - if (Provider.of(context, listen: false).activePlan != null) { - Provider.of(context, listen: false).setCurrentPlan( - Provider.of(context, listen: false).activePlan!.id!, - ); + if (workoutPlansProvider.activePlan != null) { + final planId = workoutPlansProvider.activePlan!.id!; + + await workoutPlansProvider.fetchAndSetWorkoutPlanFull(planId); + workoutPlansProvider.setCurrentPlan(planId); } } diff --git a/lib/screens/workout_plan_screen.dart b/lib/screens/workout_plan_screen.dart index 1de4c6654..56624a398 100644 --- a/lib/screens/workout_plan_screen.dart +++ b/lib/screens/workout_plan_screen.dart @@ -53,6 +53,11 @@ class _WorkoutPlanScreenState extends State { }); } + Future _loadFullWorkout(BuildContext context, int planId) async { + return await Provider.of(context, listen: false) + .fetchAndSetWorkoutPlanFull(planId); + } + Widget getBody(WorkoutPlan plan) { switch (_mode) { case WorkoutScreenMode.workout: @@ -69,75 +74,91 @@ class _WorkoutPlanScreenState extends State { final workoutPlan = ModalRoute.of(context)!.settings.arguments as WorkoutPlan; return Scaffold( - //appBar: getAppBar(workoutPlan), - body: Consumer( - builder: (context, value, child) => CustomScrollView( - slivers: [ - SliverAppBar( - expandedHeight: 250, - pinned: true, - flexibleSpace: FlexibleSpaceBar( - title: Text(workoutPlan.name), - background: Image( - image: AssetImage('assets/images/backgrounds/workout_plans.jpg'), - fit: BoxFit.cover, - ), + body: CustomScrollView( + slivers: [ + SliverAppBar( + expandedHeight: 250, + pinned: true, + flexibleSpace: FlexibleSpaceBar( + title: Text(workoutPlan.name), + background: Image( + image: AssetImage('assets/images/backgrounds/workout_plans.jpg'), + fit: BoxFit.cover, ), - actions: [ - PopupMenuButton( - icon: Icon(Icons.more_vert), - onSelected: (value) { - // Edit - if (value == WorkoutOptions.edit) { - Navigator.pushNamed( - context, - FormScreen.routeName, - arguments: FormScreenArguments( - AppLocalizations.of(context)!.edit, - WorkoutForm(workoutPlan), - ), - ); - - // Delete - } else if (value == WorkoutOptions.delete) { - Provider.of(context, listen: false) - .deleteWorkout(workoutPlan.id!); - Navigator.of(context).pop(); - - // Toggle Mode - } else if (value == WorkoutOptions.toggleMode) { - if (_mode == WorkoutScreenMode.workout) { - _changeMode(WorkoutScreenMode.log); - } else { - _changeMode(WorkoutScreenMode.workout); - } - } - }, - itemBuilder: (BuildContext context) { - return [ - PopupMenuItem( - child: _mode == WorkoutScreenMode.log - ? Text(AppLocalizations.of(context)!.labelWorkoutPlan) - : Text(AppLocalizations.of(context)!.labelWorkoutLogs), - value: WorkoutOptions.toggleMode, - ), - PopupMenuItem( - value: WorkoutOptions.edit, - child: Text(AppLocalizations.of(context)!.edit), - ), - const PopupMenuDivider(), - PopupMenuItem( - value: WorkoutOptions.delete, - child: Text(AppLocalizations.of(context)!.delete), - ), - ]; - }, - ), - ], ), - getBody(workoutPlan), - ], - ), + actions: [ + PopupMenuButton( + icon: Icon(Icons.more_vert), + onSelected: (value) { + // Edit + if (value == WorkoutOptions.edit) { + Navigator.pushNamed( + context, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context)!.edit, + WorkoutForm(workoutPlan), + ), + ); + + // Delete + } else if (value == WorkoutOptions.delete) { + Provider.of(context, listen: false) + .deleteWorkout(workoutPlan.id!); + Navigator.of(context).pop(); + + // Toggle Mode + } else if (value == WorkoutOptions.toggleMode) { + if (_mode == WorkoutScreenMode.workout) { + _changeMode(WorkoutScreenMode.log); + } else { + _changeMode(WorkoutScreenMode.workout); + } + } + }, + itemBuilder: (BuildContext context) { + return [ + PopupMenuItem( + child: _mode == WorkoutScreenMode.log + ? Text(AppLocalizations.of(context)!.labelWorkoutPlan) + : Text(AppLocalizations.of(context)!.labelWorkoutLogs), + value: WorkoutOptions.toggleMode, + ), + PopupMenuItem( + value: WorkoutOptions.edit, + child: Text(AppLocalizations.of(context)!.edit), + ), + const PopupMenuDivider(), + PopupMenuItem( + value: WorkoutOptions.delete, + child: Text(AppLocalizations.of(context)!.delete), + ), + ]; + }, + ), + ], + ), + FutureBuilder( + future: _loadFullWorkout(context, workoutPlan.id!), + builder: (context, AsyncSnapshot snapshot) => + snapshot.connectionState == ConnectionState.waiting + ? SliverList( + delegate: SliverChildListDelegate( + [ + Container( + height: 200, + child: Center( + child: CircularProgressIndicator(), + ), + ) + ], + ), + ) + : Consumer( + builder: (context, value, child) => getBody(workoutPlan), + ), + ) + ], ), ); } diff --git a/test/workout_form_test.dart b/test/workout_form_test.dart index 1b3727ff9..d524b4251 100644 --- a/test/workout_form_test.dart +++ b/test/workout_form_test.dart @@ -33,16 +33,20 @@ import 'workout_form_test.mocks.dart'; @GenerateMocks([WorkoutPlansProvider]) void main() { var mockWorkoutPlans = MockWorkoutPlansProvider(); - final plan1 = WorkoutPlan( + + final existingPlan = WorkoutPlan( id: 1, creationDate: DateTime(2021, 1, 1), name: 'test 1', description: 'description 1', ); - final plan2 = WorkoutPlan(creationDate: DateTime(2021, 1, 2), name: ''); + final newPlan = WorkoutPlan.empty(); setUp(() { mockWorkoutPlans = MockWorkoutPlansProvider(); + when(mockWorkoutPlans.editWorkout(any)).thenAnswer((_) => Future.value(existingPlan)); + when(mockWorkoutPlans.fetchAndSetWorkoutPlanFull(any)) + .thenAnswer((_) => Future.value(existingPlan)); }); Widget createHomeScreen(WorkoutPlan workoutPlan, {locale = 'en'}) { @@ -66,7 +70,7 @@ void main() { } testWidgets('Test the widgets on the workout form', (WidgetTester tester) async { - await tester.pumpWidget(createHomeScreen(plan1)); + await tester.pumpWidget(createHomeScreen(existingPlan)); await tester.pumpAndSettle(); expect(find.byType(TextFormField), findsNWidgets(2)); @@ -74,10 +78,7 @@ void main() { }); testWidgets('Test editing an existing workout', (WidgetTester tester) async { - when(mockWorkoutPlans.editWorkout(any)).thenAnswer((_) => Future.value(plan1)); - when(mockWorkoutPlans.addWorkout(any)).thenAnswer((_) => Future.value(plan2)); - - await tester.pumpWidget(createHomeScreen(plan1)); + await tester.pumpWidget(createHomeScreen(existingPlan)); await tester.pumpAndSettle(); expect( @@ -107,14 +108,19 @@ void main() { }); testWidgets('Test creating a new workout - only name', (WidgetTester tester) async { - when(mockWorkoutPlans.editWorkout(any)).thenAnswer((_) => Future.value(plan1)); - when(mockWorkoutPlans.addWorkout(any)).thenAnswer((_) => Future.value(plan2)); + final editWorkout = WorkoutPlan( + id: 2, + creationDate: newPlan.creationDate, + name: 'New cool workout', + ); - await tester.pumpWidget(createHomeScreen(plan2)); + when(mockWorkoutPlans.addWorkout(any)).thenAnswer((_) => Future.value(editWorkout)); + + await tester.pumpWidget(createHomeScreen(newPlan)); await tester.pumpAndSettle(); expect(find.text(('')), findsNWidgets(2), reason: 'New workout has no name or description'); - await tester.enterText(find.byKey(Key('field-name')), 'New cool workout'); + await tester.enterText(find.byKey(Key('field-name')), editWorkout.name); await tester.tap(find.byKey(Key(SUBMIT_BUTTON_KEY_NAME))); verifyNever(mockWorkoutPlans.editWorkout(any)); @@ -125,16 +131,17 @@ void main() { expect(find.text(('New cool workout')), findsOneWidget, reason: 'Workout plan detail page'); }); - testWidgets('Test creating a new workout - description', (WidgetTester tester) async { - when(mockWorkoutPlans.editWorkout(any)).thenAnswer((_) => Future.value(plan1)); - when(mockWorkoutPlans.addWorkout(any)).thenAnswer((_) => Future.value(plan2)); + testWidgets('Test creating a new workout - name and description', (WidgetTester tester) async { + final editWorkout = WorkoutPlan( + id: 2, creationDate: newPlan.creationDate, name: 'My workout', description: 'Get yuuuge'); + when(mockWorkoutPlans.addWorkout(any)).thenAnswer((_) => Future.value(editWorkout)); - await tester.pumpWidget(createHomeScreen(plan2)); + await tester.pumpWidget(createHomeScreen(newPlan)); await tester.pumpAndSettle(); expect(find.text(('')), findsNWidgets(2), reason: 'New workout has no name or description'); - await tester.enterText(find.byKey(Key('field-name')), 'My workout'); - await tester.enterText(find.byKey(Key('field-description')), 'Get yuuuge'); + await tester.enterText(find.byKey(Key('field-name')), editWorkout.name); + await tester.enterText(find.byKey(Key('field-description')), editWorkout.description); await tester.tap(find.byKey(Key(SUBMIT_BUTTON_KEY_NAME))); verifyNever(mockWorkoutPlans.editWorkout(any)); diff --git a/test/workout_form_test.mocks.dart b/test/workout_form_test.mocks.dart index e44a01d34..ea9450402 100644 --- a/test/workout_form_test.mocks.dart +++ b/test/workout_form_test.mocks.dart @@ -113,16 +113,27 @@ class MockWorkoutPlansProvider extends _i1.Mock super.noSuchMethod(Invocation.method(#resetCurrentPlan, []), returnValueForMissingStub: null); @override - _i14.Future fetchAndSetAllPlans() => - (super.noSuchMethod(Invocation.method(#fetchAndSetAllPlans, []), + _i14.Future fetchAndSetAllPlansFull() => + (super.noSuchMethod(Invocation.method(#fetchAndSetAllPlansFull, []), returnValue: Future.value(null), returnValueForMissingStub: Future.value()) as _i14.Future); @override - _i14.Future fetchAndSetWorkoutPlan(int? workoutId) => (super - .noSuchMethod(Invocation.method(#fetchAndSetWorkoutPlan, [workoutId]), + _i14.Future fetchAndSetAllPlansSparse() => + (super.noSuchMethod(Invocation.method(#fetchAndSetAllPlansSparse, []), returnValue: Future.value(null), returnValueForMissingStub: Future.value()) as _i14.Future); @override + _i14.Future<_i6.WorkoutPlan> fetchAndSetPlanSparse(int? planId) => + (super.noSuchMethod(Invocation.method(#fetchAndSetPlanSparse, [planId]), + returnValue: Future<_i6.WorkoutPlan>.value(_FakeWorkoutPlan())) + as _i14.Future<_i6.WorkoutPlan>); + @override + _i14.Future<_i6.WorkoutPlan> fetchAndSetWorkoutPlanFull(int? workoutId) => + (super.noSuchMethod( + Invocation.method(#fetchAndSetWorkoutPlanFull, [workoutId]), + returnValue: Future<_i6.WorkoutPlan>.value(_FakeWorkoutPlan())) + as _i14.Future<_i6.WorkoutPlan>); + @override _i14.Future<_i6.WorkoutPlan> addWorkout(_i6.WorkoutPlan? workout) => (super.noSuchMethod(Invocation.method(#addWorkout, [workout]), returnValue: Future<_i6.WorkoutPlan>.value(_FakeWorkoutPlan()))