diff --git a/lib/features/nutrition/screens/log_meal_screen.dart b/lib/features/nutrition/screens/log_meal_screen.dart index 53fa2e552..fcd44b53a 100644 --- a/lib/features/nutrition/screens/log_meal_screen.dart +++ b/lib/features/nutrition/screens/log_meal_screen.dart @@ -21,6 +21,7 @@ import 'package:material_ui/material_ui.dart'; import 'package:wger/core/snackbar.dart'; import 'package:wger/core/widgets/datetime_input.dart'; import 'package:wger/features/nutrition/models/meal.dart'; +import 'package:wger/features/nutrition/models/meal_item.dart'; import 'package:wger/features/nutrition/providers/nutrition_notifier.dart'; import 'package:wger/features/nutrition/widgets/meal.dart'; import 'package:wger/features/nutrition/widgets/nutrition_tiles.dart'; @@ -52,11 +53,19 @@ class _LogMealScreenState extends ConsumerState { final i18n = AppLocalizations.of(context); final args = ModalRoute.of(context)!.settings.arguments as LogMealArguments; + // Rounded to the two decimal places the server stores final meal = args.meal.copyWith( mealItems: args.meal.mealItems - .map((mealItem) => mealItem.copyWith(amount: mealItem.amount * portionPct / 100)) + .map( + (mealItem) => mealItem.copyWith( + amount: (mealItem.amount * portionPct).round() / 100, + ), + ) .toList(), ); + // The server only accepts diary amounts between 1 and 1000 + bool isOutOfRange(MealItem item) => item.amount < 1 || item.amount > 1000; + final hasOutOfRange = meal.mealItems.any(isOutOfRange); return Scaffold( appBar: AppBar(title: Text(i18n.logMeal)), @@ -78,18 +87,26 @@ class _LogMealScreenState extends ConsumerState { Column( children: [ const DiaryheaderTile(), - ...meal.mealItems.map( - (item) => MealItemEditableFullTile(item, ViewMode.withAllDetails, false), - ), + for (final item in meal.mealItems) ...[ + MealItemEditableFullTile(item, ViewMode.withAllDetails, false), + if (isOutOfRange(item)) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Text( + i18n.formMinMaxValues(1, 1000), + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ), + ], const SizedBox(height: 32), Text( 'Portion: ${portionPct.round()} %', style: Theme.of(context).textTheme.bodyLarge, ), Slider.adaptive( - min: 0, + min: 5, max: 150, - divisions: 30, + divisions: 29, onChanged: (value) => setState(() => portionPct = value), value: portionPct, ), @@ -127,28 +144,30 @@ class _LogMealScreenState extends ConsumerState { children: [ if (meal.mealItems.isNotEmpty) TextButton( + onPressed: hasOutOfRange + ? null + : () async { + final loggedDate = DateTime( + _date.year, + _date.month, + _date.day, + _time.hour, + _time.minute, + ); + await ref + .read(nutritionProvider.notifier) + .logMealToDiary(meal, loggedDate); + + if (context.mounted) { + showSnackbar(context, i18n.mealLogged, center: true); + + Navigator.of(context).pop(); + if (args.popTwice) { + Navigator.of(context).pop(); + } + } + }, child: Text(i18n.save), - onPressed: () async { - final loggedDate = DateTime( - _date.year, - _date.month, - _date.day, - _time.hour, - _time.minute, - ); - await ref - .read(nutritionProvider.notifier) - .logMealToDiary(meal, loggedDate); - - if (context.mounted) { - showSnackbar(context, i18n.mealLogged, center: true); - - Navigator.of(context).pop(); - if (args.popTwice) { - Navigator.of(context).pop(); - } - } - }, ), TextButton( child: Text( diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index dc04befec..ee855965e 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -4144,6 +4144,28 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get personalExercisesWarningTitle => + (super.noSuchMethod( + Invocation.getter(#personalExercisesWarningTitle), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#personalExercisesWarningTitle), + ), + ) + as String); + + @override + String get personalExercisesWarningBody => + (super.noSuchMethod( + Invocation.getter(#personalExercisesWarningBody), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#personalExercisesWarningBody), + ), + ) + as String); + @override String get translation => (super.noSuchMethod( @@ -5764,6 +5786,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String workoutNotificationExtendRest(int? seconds) => + (super.noSuchMethod( + Invocation.method(#workoutNotificationExtendRest, [seconds]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#workoutNotificationExtendRest, [seconds]), + ), + ) + as String); + @override String durationHoursMinutes(int? hours, int? minutes) => (super.noSuchMethod( @@ -5786,6 +5819,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String portionAmountRange(String? names) => + (super.noSuchMethod( + Invocation.method(#portionAmountRange, [names]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#portionAmountRange, [names]), + ), + ) + as String); + @override String planDateRange(String? startDate, String? endDate) => (super.noSuchMethod( @@ -6061,6 +6105,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String enterMinWords(int? min) => + (super.noSuchMethod( + Invocation.method(#enterMinWords, [min]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#enterMinWords, [min]), + ), + ) + as String); + @override String enterMaxCharacters(int? max) => (super.noSuchMethod( diff --git a/test/features/nutrition/screens/log_meal_screen_test.dart b/test/features/nutrition/screens/log_meal_screen_test.dart new file mode 100644 index 000000000..52d4d6fa0 --- /dev/null +++ b/test/features/nutrition/screens/log_meal_screen_test.dart @@ -0,0 +1,142 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2020 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +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:wger/features/nutrition/models/log.dart'; +import 'package:wger/features/nutrition/models/meal.dart'; +import 'package:wger/features/nutrition/models/meal_item.dart'; +import 'package:wger/features/nutrition/providers/nutrition_repository.dart'; +import 'package:wger/features/nutrition/screens/log_meal_screen.dart'; +import 'package:wger/features/nutrition/widgets/meal.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/l10n/localizations_delegates.dart'; + +import '../../../../test_data/nutritional_plans.dart'; +import '../../../helpers/fake_auth_environment.dart'; +import '../../../helpers/fake_connectivity.dart'; +import 'log_meal_screen_test.mocks.dart'; + +@GenerateMocks([NutritionRepository]) +void main() { + installFakeConnectivity(); + installFakeAuthEnvironment(); + + late MockNutritionRepository mockRepo; + + setUp(() { + mockRepo = MockNutritionRepository(); + when(mockRepo.watchAllDrift()).thenAnswer((_) => Stream.value([])); + when(mockRepo.watchAllMealsHydrated()).thenAnswer((_) => Stream.value([])); + when(mockRepo.watchAllLogsHydrated()).thenAnswer((_) => Stream.value([])); + when(mockRepo.addLogLocalDrift(any)).thenAnswer((_) async {}); + }); + + /// A meal with one item per amount, in grams + Meal mealWith(List amounts) { + final meal = Meal(id: testMealUuid1, plan: testPlanUuid1, name: 'Breakfast'); + meal.mealItems = [ + for (final amount in amounts) + MealItem(mealId: testMealUuid1, ingredientId: 1, amount: amount, ingredient: ingredient1), + ]; + return meal; + } + + Future openScreen(WidgetTester tester, Meal meal) async { + tester.view.physicalSize = const Size(500, 1200); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.reset); + + final container = ProviderContainer( + overrides: [nutritionRepositoryProvider.overrideWithValue(mockRepo)], + ); + addTearDown(container.dispose); + + final key = GlobalKey(); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + locale: const Locale('en'), + localizationsDelegates: appLocalizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + navigatorKey: key, + home: const SizedBox(), + ), + ), + ); + key.currentState!.push( + MaterialPageRoute( + settings: RouteSettings(arguments: LogMealArguments(meal, false)), + builder: (_) => const LogMealScreen(), + ), + ); + await tester.pumpAndSettle(); + } + + Future setPortion(WidgetTester tester, double percent) async { + tester.widget(find.byType(Slider)).onChanged!(percent); + await tester.pump(); + } + + Finder saveButton() => find.widgetWithText(TextButton, 'Save'); + + List loggedAmounts() => verify( + mockRepo.addLogLocalDrift(captureAny), + ).captured.map((log) => (log as LogItem).amount).toList(); + + testWidgets('the portion starts at 100 percent and ranges from 5 to 150', (tester) async { + await openScreen(tester, mealWith([100])); + final slider = tester.widget(find.byType(Slider)); + expect(slider.value, 100); + expect(slider.min, 5); + expect(slider.max, 150); + }); + + testWidgets('a portion scales every amount, rounded to two decimal places', (tester) async { + await openScreen(tester, mealWith([33.33, 200])); + await setPortion(tester, 55); + await tester.tap(saveButton()); + await tester.pumpAndSettle(); + + expect(loggedAmounts(), [18.33, 110]); + }); + + for (final (label, amount, portion) in [('below 1', 10, 5.0), ('above 1000', 800, 150.0)]) { + testWidgets('a portion that puts an amount $label cannot be saved', (tester) async { + await openScreen(tester, mealWith([amount, 100])); + await setPortion(tester, portion); + + // One message, right below the ingredient it is about + final message = find.text('Please enter a value between 1 and 1000'); + expect(message, findsOneWidget); + final tiles = find.byType(MealItemEditableFullTile); + final messageTop = tester.getTopLeft(message).dy; + expect(messageTop, greaterThanOrEqualTo(tester.getBottomLeft(tiles.at(0)).dy)); + expect(messageTop, lessThan(tester.getTopLeft(tiles.at(1)).dy)); + + expect(tester.widget(saveButton()).onPressed, isNull); + await tester.tap(saveButton()); + await tester.pumpAndSettle(); + verifyNever(mockRepo.addLogLocalDrift(any)); + }); + } +} diff --git a/test/features/nutrition/screens/log_meal_screen_test.mocks.dart b/test/features/nutrition/screens/log_meal_screen_test.mocks.dart new file mode 100644 index 000000000..f9cf084e3 --- /dev/null +++ b/test/features/nutrition/screens/log_meal_screen_test.mocks.dart @@ -0,0 +1,162 @@ +// Mocks generated by Mockito from annotations +// in wger/test/features/nutrition/screens/log_meal_screen_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/nutrition/models/log.dart' as _i7; +import 'package:wger/features/nutrition/models/meal.dart' as _i5; +import 'package:wger/features/nutrition/models/meal_item.dart' as _i6; +import 'package:wger/features/nutrition/models/nutritional_plan.dart' as _i4; +import 'package:wger/features/nutrition/providers/nutrition_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 [NutritionRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockNutritionRepository extends _i1.Mock implements _i2.NutritionRepository { + MockNutritionRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i3.Stream> watchAllDrift() => + (super.noSuchMethod( + Invocation.method(#watchAllDrift, []), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Future addPlanLocalDrift(_i4.NutritionalPlan? plan) => + (super.noSuchMethod( + Invocation.method(#addPlanLocalDrift, [plan]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future editLocalDrift(_i4.NutritionalPlan? plan) => + (super.noSuchMethod( + Invocation.method(#editLocalDrift, [plan]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future deleteLocalDrift(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteLocalDrift, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Stream> watchAllMealsHydrated() => + (super.noSuchMethod( + Invocation.method(#watchAllMealsHydrated, []), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Future addMealLocalDrift(_i5.Meal? meal) => + (super.noSuchMethod( + Invocation.method(#addMealLocalDrift, [meal]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future editMealLocalDrift(_i5.Meal? meal) => + (super.noSuchMethod( + Invocation.method(#editMealLocalDrift, [meal]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future deleteMealLocalDrift(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteMealLocalDrift, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future addMealItemLocalDrift(_i6.MealItem? item) => + (super.noSuchMethod( + Invocation.method(#addMealItemLocalDrift, [item]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future editMealItemLocalDrift(_i6.MealItem? item) => + (super.noSuchMethod( + Invocation.method(#editMealItemLocalDrift, [item]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future deleteMealItemLocalDrift(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteMealItemLocalDrift, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Stream> watchAllLogsHydrated() => + (super.noSuchMethod( + Invocation.method(#watchAllLogsHydrated, []), + returnValue: _i3.Stream>.empty(), + ) + as _i3.Stream>); + + @override + _i3.Future addLogLocalDrift(_i7.LogItem? log) => + (super.noSuchMethod( + Invocation.method(#addLogLocalDrift, [log]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); + + @override + _i3.Future deleteLogLocalDrift(String? id) => + (super.noSuchMethod( + Invocation.method(#deleteLogLocalDrift, [id]), + returnValue: _i3.Future.value(), + returnValueForMissingStub: _i3.Future.value(), + ) + as _i3.Future); +}