From 0c669946446e157143fb75330222b56f128b6397 Mon Sep 17 00:00:00 2001 From: alex-chevski Date: Mon, 16 Nov 2026 17:34:32 +0300 Subject: [PATCH 1/6] fix(settings): show success toast after saving general info related to: #989 --- .../bloc/settings_cubit/settings_cubit.dart | 8 +- .../pages/general_info_screen.dart | 8 +- lib/generated/intl/messages_en.dart | 3 + lib/generated/intl/messages_ru.dart | 3 + lib/generated/l10n.dart | 10 ++ lib/l10n/intl_en.arb | 1 + lib/l10n/intl_ru.arb | 1 + .../bloc/settings_cubit_test.dart | 72 +++++++++++++- .../pages/general_info_screen_test.dart | 95 ++++++++++++++++++- .../pages/other_info_screen_test.dart | 4 +- .../pages/physical_activity_screen_test.dart | 2 +- .../pages/physical_form_screen_test.dart | 2 +- .../pages/pressure_screen_test.dart | 2 +- 13 files changed, 195 insertions(+), 16 deletions(-) diff --git a/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart b/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart index a8479ffc..b5690c68 100644 --- a/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart +++ b/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart @@ -80,29 +80,33 @@ class SettingsCubit extends Cubit { } } - Future updateProfileDetails({ + Future updateProfileDetails({ required ProfileDetailsModel profileDetailsModel, }) async { try { await settingsRepository.updateProfileDetails( profileDetailsModel: profileDetailsModel, ); + return true; } catch (e, st) { await reportFrom(e, st, this); + return false; } finally { await init(); } } - Future updateProfileSettings({ + Future updateProfileSettings({ required ProfileSettingsModel profileSettingsModel, }) async { try { await settingsRepository.updateProfileSettings( profileSettingsModel: profileSettingsModel, ); + return true; } catch (e, st) { await reportFrom(e, st, this); + return false; } finally { await init(); } diff --git a/lib/features/settings/presentation/pages/general_info_screen.dart b/lib/features/settings/presentation/pages/general_info_screen.dart index 3fad0dc4..f4af2f9d 100644 --- a/lib/features/settings/presentation/pages/general_info_screen.dart +++ b/lib/features/settings/presentation/pages/general_info_screen.dart @@ -1,5 +1,6 @@ import 'package:eatvio_app/core/data/selectionPopupModel/selection_popup_model.dart'; import 'package:eatvio_app/core/utils/date_time_utils.dart'; +import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/core/widgets/custom_drop_down.dart'; import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart'; @@ -233,7 +234,7 @@ class _GeneralInfoScreenState extends State { setState(() { isLoading = true; }); - await widget.settingsEntity.settingsCubit.updateProfileDetails( + final detailsSaved = await widget.settingsEntity.settingsCubit.updateProfileDetails( profileDetailsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileDetails.copyWith( firstName: firstNameController.text, lastName: lastNameController.text, @@ -244,7 +245,7 @@ class _GeneralInfoScreenState extends State { lang: languageController.text, ), ); - await widget.settingsEntity.settingsCubit.updateProfileSettings( + final settingsSaved = await widget.settingsEntity.settingsCubit.updateProfileSettings( profileSettingsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileSettings.copyWith( isPublicProfile: isPublicProfile.value, ), @@ -253,6 +254,9 @@ class _GeneralInfoScreenState extends State { setState(() { isLoading = false; }); + if (detailsSaved && settingsSaved) { + showSuccessToast(S.of(context).data_saved_successfully); + } }, borderRadius: BorderRadius.circular(20), child: Ink( diff --git a/lib/generated/intl/messages_en.dart b/lib/generated/intl/messages_en.dart index 20a73529..c5735053 100644 --- a/lib/generated/intl/messages_en.dart +++ b/lib/generated/intl/messages_en.dart @@ -352,6 +352,9 @@ class MessageLookup extends MessageLookupByLibrary { "customer_price": MessageLookupByLibrary.simpleMessage( "Цена для покупателя", ), + "data_saved_successfully": MessageLookupByLibrary.simpleMessage( + "Data saved successfully", + ), "date_has_ben_set": MessageLookupByLibrary.simpleMessage( "Дата старта начала консультации установлена", ), diff --git a/lib/generated/intl/messages_ru.dart b/lib/generated/intl/messages_ru.dart index 2a3fdec0..e6643070 100644 --- a/lib/generated/intl/messages_ru.dart +++ b/lib/generated/intl/messages_ru.dart @@ -163,6 +163,9 @@ class MessageLookup extends MessageLookupByLibrary { "customer_price": MessageLookupByLibrary.simpleMessage( "Цена для покупателя", ), + "data_saved_successfully": MessageLookupByLibrary.simpleMessage( + "Данные успешно сохранены", + ), "date_of_birth": MessageLookupByLibrary.simpleMessage("Дата рождения"), "day": MessageLookupByLibrary.simpleMessage("День"), "days": MessageLookupByLibrary.simpleMessage("дней"), diff --git a/lib/generated/l10n.dart b/lib/generated/l10n.dart index 4f787674..5898dad8 100644 --- a/lib/generated/l10n.dart +++ b/lib/generated/l10n.dart @@ -134,6 +134,16 @@ class S { ); } + /// `Data saved successfully` + String get data_saved_successfully { + return Intl.message( + 'Data saved successfully', + name: 'data_saved_successfully', + desc: '', + args: [], + ); + } + /// `Страна` String get country { return Intl.message('Страна', name: 'country', desc: '', args: []); diff --git a/lib/l10n/intl_en.arb b/lib/l10n/intl_en.arb index 94dde4f0..6cfe8798 100644 --- a/lib/l10n/intl_en.arb +++ b/lib/l10n/intl_en.arb @@ -9,6 +9,7 @@ "last_name": "Фамилия", "what_is_your_name": "Как вас зовут?", "date_of_birth": "Дата рождения", + "data_saved_successfully": "Data saved successfully", "country": "Страна", "Russia": "Россия", "city": "Город", diff --git a/lib/l10n/intl_ru.arb b/lib/l10n/intl_ru.arb index 2cc23e38..0cdd051d 100644 --- a/lib/l10n/intl_ru.arb +++ b/lib/l10n/intl_ru.arb @@ -9,6 +9,7 @@ "last_name": "Фамилия", "what_is_your_name": "Как вас зовут?", "date_of_birth": "Дата рождения", + "data_saved_successfully": "Данные успешно сохранены", "country": "Страна", "Russia": "Россия", "city": "Город", diff --git a/test/features/settings/presentation/bloc/settings_cubit_test.dart b/test/features/settings/presentation/bloc/settings_cubit_test.dart index 674492c4..9cc0ad17 100644 --- a/test/features/settings/presentation/bloc/settings_cubit_test.dart +++ b/test/features/settings/presentation/bloc/settings_cubit_test.dart @@ -141,12 +141,46 @@ void main() { await settingsCubit!.init(); await Future.delayed(const Duration(milliseconds: 100)); - await settingsCubit!.updateProfileDetails(profileDetailsModel: SettingsFixtures.profileDetailsModel()); + final result = await settingsCubit!.updateProfileDetails(profileDetailsModel: SettingsFixtures.profileDetailsModel()); await Future.delayed(const Duration(milliseconds: 100)); + expect(result, true); verify(mockSettingsRepository.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).called(1); }); + test('updateProfileDetails - возвращает false при ошибке и перезагружает состояние', () async { + settingsCubit = SettingsCubit( + profileRepository: mockProfileRepository, + settingsRepository: mockSettingsRepository, + consultantRepository: mockConsultantRepository, + consultationsRepository: mockConsultationsRepository, + sessionLifecycleService: fakeSession, + ); + + when(mockProfileRepository.getMyProfile()) + .thenAnswer((_) async => SettingsFixtures.profileModel()); + when(mockConsultantRepository.getMyRequestStatus(any)) + .thenThrow(Exception('Not found')); + when(mockConsultationsRepository.getUserPurchases(any, any)) + .thenAnswer((_) async => []); + when(mockSettingsRepository.getOAuthAccounts()) + .thenAnswer((_) async => SettingsFixtures.oauthAccountsResponseModel()); + when(mockSettingsRepository.getProfileSettings()) + .thenAnswer((_) async => SettingsFixtures.profileSettingsModel()); + when(mockProfileRepository.getMyProfileDetails()) + .thenAnswer((_) async => SettingsFixtures.profileDetailsModel()); + when(mockSettingsRepository.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))) + .thenThrow(Exception('Ошибка сохранения')); + + await settingsCubit!.init(); + await Future.delayed(const Duration(milliseconds: 100)); + final result = await settingsCubit!.updateProfileDetails(profileDetailsModel: SettingsFixtures.profileDetailsModel()); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(result, false); + expect(settingsCubit!.state, isA()); + }); + test('updateProfileSettings - обновляет настройки профиля', () async { settingsCubit = SettingsCubit( profileRepository: mockProfileRepository, @@ -173,12 +207,46 @@ void main() { await settingsCubit!.init(); await Future.delayed(const Duration(milliseconds: 100)); - await settingsCubit!.updateProfileSettings(profileSettingsModel: SettingsFixtures.profileSettingsModel()); + final result = await settingsCubit!.updateProfileSettings(profileSettingsModel: SettingsFixtures.profileSettingsModel()); await Future.delayed(const Duration(milliseconds: 100)); + expect(result, true); verify(mockSettingsRepository.updateProfileSettings(profileSettingsModel: anyNamed('profileSettingsModel'))).called(1); }); + test('updateProfileSettings - возвращает false при ошибке и перезагружает состояние', () async { + settingsCubit = SettingsCubit( + profileRepository: mockProfileRepository, + settingsRepository: mockSettingsRepository, + consultantRepository: mockConsultantRepository, + consultationsRepository: mockConsultationsRepository, + sessionLifecycleService: fakeSession, + ); + + when(mockProfileRepository.getMyProfile()) + .thenAnswer((_) async => SettingsFixtures.profileModel()); + when(mockConsultantRepository.getMyRequestStatus(any)) + .thenThrow(Exception('Not found')); + when(mockConsultationsRepository.getUserPurchases(any, any)) + .thenAnswer((_) async => []); + when(mockSettingsRepository.getOAuthAccounts()) + .thenAnswer((_) async => SettingsFixtures.oauthAccountsResponseModel()); + when(mockSettingsRepository.getProfileSettings()) + .thenAnswer((_) async => SettingsFixtures.profileSettingsModel()); + when(mockProfileRepository.getMyProfileDetails()) + .thenAnswer((_) async => SettingsFixtures.profileDetailsModel()); + when(mockSettingsRepository.updateProfileSettings(profileSettingsModel: anyNamed('profileSettingsModel'))) + .thenThrow(Exception('Ошибка сохранения')); + + await settingsCubit!.init(); + await Future.delayed(const Duration(milliseconds: 100)); + final result = await settingsCubit!.updateProfileSettings(profileSettingsModel: SettingsFixtures.profileSettingsModel()); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(result, false); + expect(settingsCubit!.state, isA()); + }); + test('deleteAccount - удаляет аккаунт', () async { settingsCubit = SettingsCubit( profileRepository: mockProfileRepository, diff --git a/test/features/settings/presentation/pages/general_info_screen_test.dart b/test/features/settings/presentation/pages/general_info_screen_test.dart index 2f0fa437..2ae6f0ad 100644 --- a/test/features/settings/presentation/pages/general_info_screen_test.dart +++ b/test/features/settings/presentation/pages/general_info_screen_test.dart @@ -13,6 +13,7 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/settings/presentation/pages/general_info_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; @@ -26,6 +27,8 @@ import 'general_info_screen_test.mocks.dart'; @GenerateNiceMocks([MockSpec()]) void main() { group('GeneralInfoScreen smoke', () { + final toastCalls = []; + setUpAll(() async { dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); }); @@ -33,6 +36,21 @@ void main() { setUp(() async { await sl.reset(); sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); + toastCalls.clear(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + (MethodCall methodCall) async { + toastCalls.add(methodCall); + return null; + }, + ); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + null, + ); }); const mockProfile = ProfileModel( @@ -118,7 +136,7 @@ void main() { when(cubit.state).thenReturn(state); when(cubit.stream).thenAnswer((_) => Stream.value(state)); when(cubit.close()).thenAnswer((_) async => Future.value()); - when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); @@ -142,13 +160,13 @@ void main() { profile: mockProfile, hasActiveConsultation: false, ); - final saveCompleter = Completer(); + final saveCompleter = Completer(); when(cubit.state).thenReturn(state); when(cubit.stream).thenAnswer((_) => Stream.value(state)); when(cubit.close()).thenAnswer((_) async => Future.value()); when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) => saveCompleter.future); - when(cubit.updateProfileSettings(profileSettingsModel: anyNamed('profileSettingsModel'))).thenAnswer((_) async {}); + when(cubit.updateProfileSettings(profileSettingsModel: anyNamed('profileSettingsModel'))).thenAnswer((_) async => true); final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); @@ -173,12 +191,81 @@ void main() { final loaderSize = tester.getSize(find.byType(Loader)); expect(loaderSize.height, lessThan(60)); - saveCompleter.complete(); + saveCompleter.complete(true); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(find.text('Сохранить'), findsOneWidget); expect(find.byType(Loader), findsNothing); + + await tester.pump(const Duration(seconds: 2)); + }); + + testWidgets('показывает уведомление после успешного сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); + when(cubit.updateProfileSettings(profileSettingsModel: anyNamed('profileSettingsModel'))).thenAnswer((_) async => true); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(GeneralInfoScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.pump(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + final toastMessages = toastCalls.where((call) => call.method == 'showToast').map((call) => call.arguments['msg']); + expect(toastMessages, contains('Данные успешно сохранены')); + + await tester.pump(const Duration(seconds: 2)); + }); + + testWidgets('не показывает уведомление, если сохранение не удалось', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => false); + when(cubit.updateProfileSettings(profileSettingsModel: anyNamed('profileSettingsModel'))).thenAnswer((_) async => true); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(GeneralInfoScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.pump(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(toastCalls.where((call) => call.method == 'showToast'), isEmpty); }); }); } diff --git a/test/features/settings/presentation/pages/other_info_screen_test.dart b/test/features/settings/presentation/pages/other_info_screen_test.dart index ce6a1406..ff915a99 100644 --- a/test/features/settings/presentation/pages/other_info_screen_test.dart +++ b/test/features/settings/presentation/pages/other_info_screen_test.dart @@ -115,9 +115,7 @@ void main() { when(cubit.state).thenReturn(state); when(cubit.stream).thenAnswer((_) => Stream.value(state)); when(cubit.close()).thenAnswer((_) async => Future.value()); - when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async { - return Future.value(); - }); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); diff --git a/test/features/settings/presentation/pages/physical_activity_screen_test.dart b/test/features/settings/presentation/pages/physical_activity_screen_test.dart index 36b06b96..74ca2e13 100644 --- a/test/features/settings/presentation/pages/physical_activity_screen_test.dart +++ b/test/features/settings/presentation/pages/physical_activity_screen_test.dart @@ -106,7 +106,7 @@ void main() { when(cubit.state).thenReturn(state); when(cubit.stream).thenAnswer((_) => Stream.value(state)); when(cubit.close()).thenAnswer((_) async => Future.value()); - when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); diff --git a/test/features/settings/presentation/pages/physical_form_screen_test.dart b/test/features/settings/presentation/pages/physical_form_screen_test.dart index d0fb6cfd..903a3390 100644 --- a/test/features/settings/presentation/pages/physical_form_screen_test.dart +++ b/test/features/settings/presentation/pages/physical_form_screen_test.dart @@ -115,7 +115,7 @@ void main() { when(cubit.state).thenReturn(state); when(cubit.stream).thenAnswer((_) => Stream.value(state)); when(cubit.close()).thenAnswer((_) async => Future.value()); - when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); diff --git a/test/features/settings/presentation/pages/pressure_screen_test.dart b/test/features/settings/presentation/pages/pressure_screen_test.dart index d83ded4a..6e399b5c 100644 --- a/test/features/settings/presentation/pages/pressure_screen_test.dart +++ b/test/features/settings/presentation/pages/pressure_screen_test.dart @@ -115,7 +115,7 @@ void main() { when(cubit.state).thenReturn(state); when(cubit.stream).thenAnswer((_) => Stream.value(state)); when(cubit.close()).thenAnswer((_) async => Future.value()); - when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); From 66d7028d0f8ae17b50a9bd738900b3bfb885f130 Mon Sep 17 00:00:00 2001 From: alex-chevski Date: Mon, 16 Nov 2026 17:55:57 +0300 Subject: [PATCH 2/6] fix(settings): return to settings with success toast after saving related to: #989 --- .../pages/general_info_screen.dart | 2 + .../presentation/pages/other_info_screen.dart | 11 +- .../pages/physical_activity_screen.dart | 12 +- .../pages/physical_form_screen.dart | 11 +- .../presentation/pages/pressure_screen.dart | 11 +- .../pages/general_info_screen_test.dart | 39 ++++-- .../pages/other_info_screen_test.dart | 109 +++++++++++++++- .../pages/physical_activity_screen_test.dart | 118 +++++++++++++++++- .../pages/physical_form_screen_test.dart | 109 +++++++++++++++- .../pages/pressure_screen_test.dart | 109 +++++++++++++++- 10 files changed, 498 insertions(+), 33 deletions(-) diff --git a/lib/features/settings/presentation/pages/general_info_screen.dart b/lib/features/settings/presentation/pages/general_info_screen.dart index f4af2f9d..91d206e3 100644 --- a/lib/features/settings/presentation/pages/general_info_screen.dart +++ b/lib/features/settings/presentation/pages/general_info_screen.dart @@ -11,6 +11,7 @@ import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; class GeneralInfoScreen extends StatefulWidget { final SettingsEntity settingsEntity; @@ -256,6 +257,7 @@ class _GeneralInfoScreenState extends State { }); if (detailsSaved && settingsSaved) { showSuccessToast(S.of(context).data_saved_successfully); + context.pop(); } }, borderRadius: BorderRadius.circular(20), diff --git a/lib/features/settings/presentation/pages/other_info_screen.dart b/lib/features/settings/presentation/pages/other_info_screen.dart index 839c440d..35a4cc0e 100644 --- a/lib/features/settings/presentation/pages/other_info_screen.dart +++ b/lib/features/settings/presentation/pages/other_info_screen.dart @@ -2,6 +2,7 @@ import 'package:eatvio_app/features/settings/entities/settings_entity.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; @@ -137,8 +138,8 @@ class _OtherInfoScreenState extends State { InkWell _saveButton() { return InkWell( - onTap: () { - widget.settingsEntity.settingsCubit.updateProfileDetails( + onTap: () async { + final saved = await widget.settingsEntity.settingsCubit.updateProfileDetails( profileDetailsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileDetails.copyWith( aboutAlergy: aboutAllergyController.text, aboutTakingPils: aboutTakingPillsController.text, @@ -148,7 +149,11 @@ class _OtherInfoScreenState extends State { additionalInfo: additionalInfoController.text, ), ); - GoRouter.of(context).pop(); + if (!mounted) return; + if (saved) { + showSuccessToast(S.of(context).data_saved_successfully); + GoRouter.of(context).pop(); + } }, borderRadius: BorderRadius.circular(20), child: Ink( diff --git a/lib/features/settings/presentation/pages/physical_activity_screen.dart b/lib/features/settings/presentation/pages/physical_activity_screen.dart index 74b6f971..26747cd8 100644 --- a/lib/features/settings/presentation/pages/physical_activity_screen.dart +++ b/lib/features/settings/presentation/pages/physical_activity_screen.dart @@ -2,6 +2,8 @@ import 'package:eatvio_app/features/settings/entities/settings_entity.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/utils/toasts.dart'; +import 'package:eatvio_app/generated/l10n.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; @@ -200,7 +202,7 @@ class _PhysicalActivityScreenState extends State { InkWell _saveButton() { return InkWell( - onTap: () { + onTap: () async { late final double activityCoefficient; switch (_physicalActivity) { case PhysicalActivity.minimum: @@ -221,12 +223,16 @@ class _PhysicalActivityScreenState extends State { default: break; } - widget.settingsEntity.settingsCubit.updateProfileDetails( + final saved = await widget.settingsEntity.settingsCubit.updateProfileDetails( profileDetailsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileDetails.copyWith( activityCoefficient: activityCoefficient, ), ); - GoRouter.of(context).pop(); + if (!mounted) return; + if (saved) { + showSuccessToast(S.of(context).data_saved_successfully); + GoRouter.of(context).pop(); + } }, borderRadius: BorderRadius.circular(20), child: Ink( diff --git a/lib/features/settings/presentation/pages/physical_form_screen.dart b/lib/features/settings/presentation/pages/physical_form_screen.dart index f806b086..487af658 100644 --- a/lib/features/settings/presentation/pages/physical_form_screen.dart +++ b/lib/features/settings/presentation/pages/physical_form_screen.dart @@ -2,6 +2,7 @@ import 'package:eatvio_app/features/settings/entities/settings_entity.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -108,8 +109,8 @@ class _PhysicalFormScreenState extends State { InkWell _saveButton() { return InkWell( - onTap: () { - widget.settingsEntity.settingsCubit.updateProfileDetails( + onTap: () async { + final saved = await widget.settingsEntity.settingsCubit.updateProfileDetails( profileDetailsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileDetails.copyWith( chestCircumference: int.parse(chestCircumferenceController.text), waistCircumference: int.parse(waistCircumferenceController.text), @@ -118,7 +119,11 @@ class _PhysicalFormScreenState extends State { weight: double.parse(weightController.text), ), ); - GoRouter.of(context).pop(); + if (!mounted) return; + if (saved) { + showSuccessToast(S.of(context).data_saved_successfully); + GoRouter.of(context).pop(); + } }, borderRadius: BorderRadius.circular(20), child: Ink( diff --git a/lib/features/settings/presentation/pages/pressure_screen.dart b/lib/features/settings/presentation/pages/pressure_screen.dart index b50d9a42..e8855a54 100644 --- a/lib/features/settings/presentation/pages/pressure_screen.dart +++ b/lib/features/settings/presentation/pages/pressure_screen.dart @@ -4,6 +4,7 @@ import 'package:eatvio_app/features/settings/entities/settings_entity.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/core/widgets/custom_text_form_field.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -114,8 +115,8 @@ class _PressureScreenState extends State { InkWell _saveButton() { return InkWell( - onTap: () { - widget.settingsEntity.settingsCubit.updateProfileDetails( + onTap: () async { + final saved = await widget.settingsEntity.settingsCubit.updateProfileDetails( profileDetailsModel: (widget.settingsEntity.settingsCubit.state as SettingsStateLoaded).profileDetails.copyWith( bloodPressureUp: int.parse(bloodPressureUpController.text), bloodPressureDown: int.parse(bloodPressureDownController.text), @@ -123,7 +124,11 @@ class _PressureScreenState extends State { hasHypo: hypo.value, ), ); - GoRouter.of(context).pop(); + if (!mounted) return; + if (saved) { + showSuccessToast(S.of(context).data_saved_successfully); + GoRouter.of(context).pop(); + } }, borderRadius: BorderRadius.circular(20), child: Ink( diff --git a/test/features/settings/presentation/pages/general_info_screen_test.dart b/test/features/settings/presentation/pages/general_info_screen_test.dart index 2ae6f0ad..1223718e 100644 --- a/test/features/settings/presentation/pages/general_info_screen_test.dart +++ b/test/features/settings/presentation/pages/general_info_screen_test.dart @@ -119,7 +119,20 @@ void main() { supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', - routes: [GoRoute(path: '/', builder: (context, state) => child)], + routes: [ + GoRoute( + path: '/', + builder: (context, state) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => context.push('/screen'), + child: const Text('open screen'), + ), + ), + ), + ), + GoRoute(path: '/screen', builder: (context, state) => child), + ], ), ); } @@ -146,8 +159,8 @@ void main() { child: wrap(GeneralInfoScreen(settingsEntity: settingsEntity)), ), ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); expect(find.byType(GeneralInfoScreen), findsOneWidget); }); @@ -176,7 +189,8 @@ void main() { child: wrap(GeneralInfoScreen(settingsEntity: settingsEntity)), ), ); - await tester.pump(); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); expect(find.text('Сохранить'), findsOneWidget); expect(find.byType(Loader), findsNothing); @@ -193,10 +207,10 @@ void main() { saveCompleter.complete(true); await tester.pump(); - await tester.pump(const Duration(milliseconds: 50)); + await tester.pumpAndSettle(); - expect(find.text('Сохранить'), findsOneWidget); - expect(find.byType(Loader), findsNothing); + expect(find.byType(GeneralInfoScreen), findsNothing); + expect(find.text('open screen'), findsOneWidget); await tester.pump(const Duration(seconds: 2)); }); @@ -224,7 +238,8 @@ void main() { child: wrap(GeneralInfoScreen(settingsEntity: settingsEntity)), ), ); - await tester.pump(); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); await tester.tap(find.text('Сохранить')); await tester.pump(); @@ -233,6 +248,10 @@ void main() { final toastMessages = toastCalls.where((call) => call.method == 'showToast').map((call) => call.arguments['msg']); expect(toastMessages, contains('Данные успешно сохранены')); + await tester.pumpAndSettle(); + expect(find.byType(GeneralInfoScreen), findsNothing); + expect(find.text('open screen'), findsOneWidget); + await tester.pump(const Duration(seconds: 2)); }); @@ -259,13 +278,15 @@ void main() { child: wrap(GeneralInfoScreen(settingsEntity: settingsEntity)), ), ); - await tester.pump(); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); await tester.tap(find.text('Сохранить')); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(toastCalls.where((call) => call.method == 'showToast'), isEmpty); + expect(find.byType(GeneralInfoScreen), findsOneWidget); }); }); } diff --git a/test/features/settings/presentation/pages/other_info_screen_test.dart b/test/features/settings/presentation/pages/other_info_screen_test.dart index ff915a99..3d8d5f86 100644 --- a/test/features/settings/presentation/pages/other_info_screen_test.dart +++ b/test/features/settings/presentation/pages/other_info_screen_test.dart @@ -10,6 +10,7 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/settings/presentation/pages/other_info_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; @@ -23,6 +24,8 @@ import 'other_info_screen_test.mocks.dart'; @GenerateNiceMocks([MockSpec()]) void main() { group('OtherInfoScreen smoke', () { + final toastCalls = []; + setUpAll(() async { dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); }); @@ -30,6 +33,21 @@ void main() { setUp(() async { await sl.reset(); sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); + toastCalls.clear(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + (MethodCall methodCall) async { + toastCalls.add(methodCall); + return null; + }, + ); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + null, + ); }); const mockProfile = ProfileModel( @@ -98,7 +116,20 @@ void main() { supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', - routes: [GoRoute(path: '/', builder: (context, state) => child)], + routes: [ + GoRoute( + path: '/', + builder: (context, state) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => context.push('/screen'), + child: const Text('open screen'), + ), + ), + ), + ), + GoRoute(path: '/screen', builder: (context, state) => child), + ], ), ); } @@ -125,10 +156,82 @@ void main() { child: wrap(OtherInfoScreen(settingsEntity: settingsEntity)), ), ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); expect(find.byType(OtherInfoScreen), findsOneWidget); }); + + testWidgets('показывает уведомление и возвращается к настройкам после успешного сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(OtherInfoScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + final toastMessages = toastCalls.where((call) => call.method == 'showToast').map((call) => call.arguments['msg']); + expect(toastMessages, contains('Данные успешно сохранены')); + + await tester.pumpAndSettle(); + expect(find.byType(OtherInfoScreen), findsNothing); + expect(find.text('open screen'), findsOneWidget); + + await tester.pump(const Duration(seconds: 2)); + }); + + testWidgets('не показывает уведомление и остаётся на экране при ошибке сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => false); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(OtherInfoScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(toastCalls.where((call) => call.method == 'showToast'), isEmpty); + expect(find.byType(OtherInfoScreen), findsOneWidget); + }); }); } diff --git a/test/features/settings/presentation/pages/physical_activity_screen_test.dart b/test/features/settings/presentation/pages/physical_activity_screen_test.dart index 74ca2e13..b83d6a35 100644 --- a/test/features/settings/presentation/pages/physical_activity_screen_test.dart +++ b/test/features/settings/presentation/pages/physical_activity_screen_test.dart @@ -8,9 +8,12 @@ import 'package:eatvio_app/features/settings/models/profile_settings_model.dart' import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/features/settings/presentation/pages/physical_activity_screen.dart'; +import 'package:eatvio_app/generated/l10n.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:mockito/annotations.dart'; @@ -21,6 +24,8 @@ import 'physical_activity_screen_test.mocks.dart'; @GenerateNiceMocks([MockSpec()]) void main() { group('PhysicalActivityScreen smoke', () { + final toastCalls = []; + setUpAll(() async { dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); }); @@ -28,6 +33,21 @@ void main() { setUp(() async { await sl.reset(); sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); + toastCalls.clear(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + (MethodCall methodCall) async { + toastCalls.add(methodCall); + return null; + }, + ); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + null, + ); }); const mockProfile = ProfileModel( @@ -87,9 +107,29 @@ void main() { Widget wrap(Widget child) { return MaterialApp.router( theme: ThemeHelper().themeData(), + localizationsDelegates: const [ + S.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', - routes: [GoRoute(path: '/', builder: (context, state) => child)], + routes: [ + GoRoute( + path: '/', + builder: (context, state) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => context.push('/screen'), + child: const Text('open screen'), + ), + ), + ), + ), + GoRoute(path: '/screen', builder: (context, state) => child), + ], ), ); } @@ -116,10 +156,82 @@ void main() { child: wrap(PhysicalActivityScreen(settingsEntity: settingsEntity)), ), ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 200)); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); expect(find.byType(PhysicalActivityScreen), findsOneWidget); }); + + testWidgets('показывает уведомление и возвращается к настройкам после успешного сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(PhysicalActivityScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + final toastMessages = toastCalls.where((call) => call.method == 'showToast').map((call) => call.arguments['msg']); + expect(toastMessages, contains('Данные успешно сохранены')); + + await tester.pumpAndSettle(); + expect(find.byType(PhysicalActivityScreen), findsNothing); + expect(find.text('open screen'), findsOneWidget); + + await tester.pump(const Duration(seconds: 2)); + }); + + testWidgets('не показывает уведомление и остаётся на экране при ошибке сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => false); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(PhysicalActivityScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(toastCalls.where((call) => call.method == 'showToast'), isEmpty); + expect(find.byType(PhysicalActivityScreen), findsOneWidget); + }); }); } diff --git a/test/features/settings/presentation/pages/physical_form_screen_test.dart b/test/features/settings/presentation/pages/physical_form_screen_test.dart index 903a3390..b170d657 100644 --- a/test/features/settings/presentation/pages/physical_form_screen_test.dart +++ b/test/features/settings/presentation/pages/physical_form_screen_test.dart @@ -10,6 +10,7 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/settings/presentation/pages/physical_form_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; @@ -23,6 +24,8 @@ import 'physical_form_screen_test.mocks.dart'; @GenerateNiceMocks([MockSpec()]) void main() { group('PhysicalFormScreen smoke', () { + final toastCalls = []; + setUpAll(() async { dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); }); @@ -30,6 +33,21 @@ void main() { setUp(() async { await sl.reset(); sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); + toastCalls.clear(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + (MethodCall methodCall) async { + toastCalls.add(methodCall); + return null; + }, + ); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + null, + ); }); const mockProfile = ProfileModel( @@ -98,7 +116,20 @@ void main() { supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', - routes: [GoRoute(path: '/', builder: (context, state) => child)], + routes: [ + GoRoute( + path: '/', + builder: (context, state) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => context.push('/screen'), + child: const Text('open screen'), + ), + ), + ), + ), + GoRoute(path: '/screen', builder: (context, state) => child), + ], ), ); } @@ -125,10 +156,82 @@ void main() { child: wrap(PhysicalFormScreen(settingsEntity: settingsEntity)), ), ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); expect(find.byType(PhysicalFormScreen), findsOneWidget); }); + + testWidgets('показывает уведомление и возвращается к настройкам после успешного сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(PhysicalFormScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + final toastMessages = toastCalls.where((call) => call.method == 'showToast').map((call) => call.arguments['msg']); + expect(toastMessages, contains('Данные успешно сохранены')); + + await tester.pumpAndSettle(); + expect(find.byType(PhysicalFormScreen), findsNothing); + expect(find.text('open screen'), findsOneWidget); + + await tester.pump(const Duration(seconds: 2)); + }); + + testWidgets('не показывает уведомление и остаётся на экране при ошибке сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => false); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(PhysicalFormScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(toastCalls.where((call) => call.method == 'showToast'), isEmpty); + expect(find.byType(PhysicalFormScreen), findsOneWidget); + }); }); } diff --git a/test/features/settings/presentation/pages/pressure_screen_test.dart b/test/features/settings/presentation/pages/pressure_screen_test.dart index 6e399b5c..69b44bb5 100644 --- a/test/features/settings/presentation/pages/pressure_screen_test.dart +++ b/test/features/settings/presentation/pages/pressure_screen_test.dart @@ -10,6 +10,7 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se import 'package:eatvio_app/features/settings/presentation/pages/pressure_screen.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; @@ -23,6 +24,8 @@ import 'pressure_screen_test.mocks.dart'; @GenerateNiceMocks([MockSpec()]) void main() { group('PressureScreen smoke', () { + final toastCalls = []; + setUpAll(() async { dotenv.loadFromString(envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost'); }); @@ -30,6 +33,21 @@ void main() { setUp(() async { await sl.reset(); sl.registerLazySingleton(() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl('http://localhost')); + toastCalls.clear(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + (MethodCall methodCall) async { + toastCalls.add(methodCall); + return null; + }, + ); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + null, + ); }); const mockProfile = ProfileModel( @@ -98,7 +116,20 @@ void main() { supportedLocales: const [Locale('ru')], routerConfig: GoRouter( initialLocation: '/', - routes: [GoRoute(path: '/', builder: (context, state) => child)], + routes: [ + GoRoute( + path: '/', + builder: (context, state) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => context.push('/screen'), + child: const Text('open screen'), + ), + ), + ), + ), + GoRoute(path: '/screen', builder: (context, state) => child), + ], ), ); } @@ -125,10 +156,82 @@ void main() { child: wrap(PressureScreen(settingsEntity: settingsEntity)), ), ); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); expect(find.byType(PressureScreen), findsOneWidget); }); + + testWidgets('показывает уведомление и возвращается к настройкам после успешного сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => true); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(PressureScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + final toastMessages = toastCalls.where((call) => call.method == 'showToast').map((call) => call.arguments['msg']); + expect(toastMessages, contains('Данные успешно сохранены')); + + await tester.pumpAndSettle(); + expect(find.byType(PressureScreen), findsNothing); + expect(find.text('open screen'), findsOneWidget); + + await tester.pump(const Duration(seconds: 2)); + }); + + testWidgets('не показывает уведомление и остаётся на экране при ошибке сохранения', (tester) async { + final cubit = MockSettingsCubit(); + const state = SettingsState.loaded( + profileSettings: mockProfileSettings, + profileDetails: mockProfileDetails, + profile: mockProfile, + hasActiveConsultation: false, + ); + + when(cubit.state).thenReturn(state); + when(cubit.stream).thenAnswer((_) => Stream.value(state)); + when(cubit.close()).thenAnswer((_) async => Future.value()); + when(cubit.updateProfileDetails(profileDetailsModel: anyNamed('profileDetailsModel'))).thenAnswer((_) async => false); + + final settingsEntity = SettingsEntity(profileSettingsModel: mockProfileSettings, profileDetailsModel: mockProfileDetails, settingsCubit: cubit); + + await tester.pumpWidget( + BlocProvider.value( + value: cubit, + child: wrap(PressureScreen(settingsEntity: settingsEntity)), + ), + ); + await tester.tap(find.text('open screen')); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Сохранить')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(toastCalls.where((call) => call.method == 'showToast'), isEmpty); + expect(find.byType(PressureScreen), findsOneWidget); + }); }); } From 5308c11ca6bb9f1481c7fb36c327df100dfa9f68 Mon Sep 17 00:00:00 2001 From: misha Date: Fri, 20 Nov 2026 14:24:20 +0300 Subject: [PATCH 3/6] fixed sentry crashes handling --- lib/core/app_initializer.dart | 24 +- .../comments/services/comments_service.dart | 6 +- lib/core/di/external_registrations.dart | 8 +- lib/core/di/repository_registrations.dart | 4 +- lib/core/di/service_registrations.dart | 147 ++++++--- .../error_reporting/api_response_dio.dart | 71 ++++ .../api_response_error_reporter.dart | 111 +++++++ .../error_reporting/error_report_policy.dart | 16 +- lib/core/routing/other_routes.dart | 21 +- lib/core/views/service/views_service.dart | 6 +- lib/core/websockets/ws_service.dart | 6 +- lib/features/auth/services/auth_service.dart | 6 +- .../auth/services/reset_password_service.dart | 6 +- .../barcode/services/barcode_service.dart | 52 +-- .../services/blog_post_service.dart | 6 +- .../calendar/services/calendar_service.dart | 6 +- .../service/cancel_plan_service.dart | 6 +- lib/features/chat/services/chat_service.dart | 6 +- .../services/complaining_service.dart | 6 +- .../services/consultant_service.dart | 6 +- .../services/consultant_rating_service.dart | 6 +- .../services/create_diet_service.dart | 6 +- .../services/create_plan_service.dart | 6 +- .../services/recipe_service.dart | 6 +- .../diary/services/diary_service.dart | 6 +- lib/features/diets/services/diet_service.dart | 6 +- lib/features/feed/services/feed_service.dart | 6 +- .../glossary/services/glossary_service.dart | 6 +- .../insights/services/insights_service.dart | 6 +- .../menu/services/blocked_users_service.dart | 6 +- .../notification_settings_service.dart | 6 +- .../my_diets/services/my_diets_service.dart | 6 +- .../my_finance/services/cards_service.dart | 6 +- .../my_plans/services/my_plans_service.dart | 6 +- .../service/notifications_service.dart | 26 +- .../repositories/payment_repository.dart | 28 +- .../personal_diet_suggestion_service.dart | 7 +- lib/features/plans/services/plan_service.dart | 6 +- .../plans/services/plans_service.dart | 6 +- .../profile/services/profile_service.dart | 6 +- .../recipe/services/about_recipe_service.dart | 6 +- .../recipe/services/my_recipes_service.dart | 6 +- .../services/registration_service.dart | 6 +- .../services/registration_service_v2.dart | 6 +- .../settings/services/settings_service.dart | 6 +- .../services/video_call_service.dart | 6 +- lib/main.dart | 15 +- .../api_response_reporting_test.dart | 311 ++++++++++++++++++ 48 files changed, 909 insertions(+), 136 deletions(-) create mode 100644 lib/core/error_reporting/api_response_dio.dart create mode 100644 lib/core/error_reporting/api_response_error_reporter.dart create mode 100644 test/core/error_reporting/api_response_reporting_test.dart diff --git a/lib/core/app_initializer.dart b/lib/core/app_initializer.dart index 601a7984..86f60dbe 100644 --- a/lib/core/app_initializer.dart +++ b/lib/core/app_initializer.dart @@ -18,21 +18,22 @@ class AppInitializer { static Future initialize({required AppBuildType buildType}) async { await _initializeEnvironment(); await _initializeDependencyInjection(buildType: buildType); - await _initializeSentry(); + _preserveSplash(); await _initializeFirebase(); await _initializeDebugMode(); await _initializeAnalytics(); } - /// Инициализация Sentry - static Future _initializeSentry() async { + static void _preserveSplash() { final widgetsBinding = SentryWidgetsFlutterBinding.ensureInitialized(); FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding); } /// Загрузка переменных окружения static Future _initializeEnvironment() async { - await dotenv.load(fileName: ".env"); + if (!dotenv.isInitialized) { + await dotenv.load(fileName: '.env'); + } } /// Инициализация Firebase @@ -64,20 +65,25 @@ class AppInitializer { /// Инициализация аналитики static Future _initializeAnalytics() async { - AppMetrica.activate(AppMetricaConfig(EnvConfig.appMetricaApiKey)); + AppMetrica.activate(AppMetricaConfig(EnvConfig.appMetricaApiKey, flutterCrashReporting: false)); AppMetrica.reportEvent('Application started'); } /// Запуск приложения с Sentry - static Future runAppWithSentry(VoidCallback appRunner) async { + static Future runAppWithSentry( + FutureOr Function() appRunner, + ) async { + SentryWidgetsFlutterBinding.ensureInitialized(); + await _initializeEnvironment(); + const sendInDebug = bool.fromEnvironment('SENTRY_IN_DEBUG'); await SentryFlutter.init((options) { options.dsn = EnvConfig.sentryDsn; options.tracesSampleRate = 1.0; options.debug = false; + if (kDebugMode && sendInDebug) options.environment = 'debug'; options.beforeSend = (event, hint) { - if (kDebugMode) return null; - if (!ErrorReportPolicy.allowSentryEvent(event, hint)) return null; - return event; + if (kDebugMode && !sendInDebug) return null; + return ErrorReportPolicy.prepareSentryEvent(event, hint); }; }, appRunner: appRunner); } diff --git a/lib/core/comments/services/comments_service.dart b/lib/core/comments/services/comments_service.dart index 606f61bd..6c5a1333 100644 --- a/lib/core/comments/services/comments_service.dart +++ b/lib/core/comments/services/comments_service.dart @@ -6,7 +6,11 @@ part 'comments_service.g.dart'; @RestApi() abstract class CommentsService { - factory CommentsService(Dio dio, {String baseUrl}) = _CommentsService; + factory CommentsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _CommentsService; @DELETE('/api/comments/{id}') Future deleteComment(@Path('id') int id); diff --git a/lib/core/di/external_registrations.dart b/lib/core/di/external_registrations.dart index cb285f40..2912633c 100644 --- a/lib/core/di/external_registrations.dart +++ b/lib/core/di/external_registrations.dart @@ -1,6 +1,8 @@ import 'package:dio/dio.dart'; import 'package:eatvio_app/core/app_config.dart'; import 'package:eatvio_app/core/constants/app_constants.dart'; +import 'package:eatvio_app/core/error_reporting/api_response_dio.dart'; +import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart'; import 'package:eatvio_app/core/error_reporting/error_reporter.dart'; import 'package:eatvio_app/core/error_reporting/sentry_error_reporter.dart'; import 'package:eatvio_app/core/interceptors/phone_verify_error_interceptor.dart'; @@ -18,14 +20,15 @@ class ExternalRegistrations { /// Регистрация всех внешних зависимостей static void registerAll() { sl.registerLazySingleton(SentryErrorReporter.new); + sl.registerLazySingleton(() => ApiResponseErrorReporter(sl())); _registerDio(); _registerPrefs(); } /// Регистрация Dio HTTP клиента static void _registerDio() { - sl.registerLazySingleton( - () => Dio( + sl.registerLazySingleton( + () => ApiResponseDio( BaseOptions( baseUrl: sl().baseUrl, headers: {'accept': 'application/json', 'content-type': 'application/json'}, @@ -33,6 +36,7 @@ class ExternalRegistrations { receiveTimeout: AppConstants.pendingDelay, sendTimeout: AppConstants.pendingDelay, ), + sl(), )..interceptors.addAll([TokenInterceptor(), PhoneVerifyErrorInterceptor()]) ..addSentry( failedRequestStatusCodes: const [SentryStatusCode.defaultRange()], diff --git a/lib/core/di/repository_registrations.dart b/lib/core/di/repository_registrations.dart index 545d009f..6b85d0a6 100644 --- a/lib/core/di/repository_registrations.dart +++ b/lib/core/di/repository_registrations.dart @@ -86,7 +86,9 @@ class RepositoryRegistrations { sl.registerLazySingleton(() => CommentsRepository(service: sl())); sl.registerLazySingleton(() => NotificationSettingsRepository(sl())); sl.registerLazySingleton(() => SbpRepository(sbpService: sl())); - sl.registerLazySingleton(() => PaymentRepository(chatService: sl())); + sl.registerLazySingleton( + () => PaymentRepository(chatService: sl(), responseErrors: sl()), + ); sl.registerLazySingleton(() => PersonalDietSuggestionRepository(personalDietSuggestionService: sl())); sl.registerLazySingleton(() => RegistrationRepositoryV2(registrationService: sl())); diff --git a/lib/core/di/service_registrations.dart b/lib/core/di/service_registrations.dart index abddd8eb..a5022c3f 100644 --- a/lib/core/di/service_registrations.dart +++ b/lib/core/di/service_registrations.dart @@ -1,3 +1,4 @@ +import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart'; import 'package:eatvio_app/core/comments/services/comments_service.dart'; import 'package:eatvio_app/core/firebase_api.dart'; import 'package:eatvio_app/core/views/service/views_service.dart'; @@ -56,37 +57,83 @@ class ServiceRegistrations { /// Регистрация Service как синглтонов static void _registerSingletonServices() { // Core services - sl.registerLazySingleton(() => ChatService(sl())); - sl.registerLazySingleton(() => VideoCallService(sl())); + sl.registerLazySingleton( + () => ChatService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => VideoCallService(sl(), errorLogger: sl()), + ); sl.registerLazySingleton( () => const PublicDownloadsSaver(), ); sl.registerLazySingleton( () => VideoCallRecordingFileService(dio: sl(), downloadsSaver: sl()), ); - sl.registerLazySingleton(() => FeedService(sl())); - sl.registerLazySingleton(() => ProfileService(sl())); - sl.registerLazySingleton(() => InsightsService(sl())); - sl.registerLazySingleton(() => CalendarService(sl())); - sl.registerLazySingleton(() => SettingsService(sl())); - sl.registerLazySingleton(() => ConsultantService(sl())); - sl.registerLazySingleton(() => DiaryService(sl())); - sl.registerLazySingleton(() => GlossaryService(sl())); - sl.registerLazySingleton(() => BarcodeService(sl())); - sl.registerLazySingleton(() => DietService(sl())); - sl.registerLazySingleton(() => PlansService(sl())); - sl.registerLazySingleton(() => PlanService(sl())); - sl.registerLazySingleton(() => MyDietsService(sl())); - sl.registerLazySingleton(() => MyPlansService(sl())); - sl.registerLazySingleton(() => WsService(sl())); - sl.registerLazySingleton(() => AboutRecipeService(sl())); - sl.registerLazySingleton(() => ComplainingService(sl())); - sl.registerLazySingleton(() => AuthService(sl())); - sl.registerLazySingleton(() => CardsService(sl())); + sl.registerLazySingleton( + () => FeedService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => ProfileService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => InsightsService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => CalendarService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => SettingsService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => ConsultantService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => DiaryService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => GlossaryService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => BarcodeService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => DietService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => PlansService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => PlanService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => MyDietsService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => MyPlansService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton(() => WsService(sl(), errorLogger: sl())); + sl.registerLazySingleton( + () => AboutRecipeService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => ComplainingService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => AuthService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => CardsService(sl(), errorLogger: sl()), + ); sl.registerLazySingleton(() => ConsultationService(sl())); - sl.registerLazySingleton(() => CancelPlanService(sl())); - sl.registerLazySingleton(() => CreatePlanService(sl())); - sl.registerLazySingleton(() => NotificationsService(sl())); + sl.registerLazySingleton( + () => CancelPlanService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => CreatePlanService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => NotificationsService(sl(), responseErrors: sl()), + ); sl.registerLazySingleton(() => FirebaseApi(errorReporter: sl())); sl.registerLazySingleton( () => VideoCallCallKitCoordinator(firebaseApi: sl()), @@ -94,23 +141,49 @@ class ServiceRegistrations { sl.registerLazySingleton( () => VideoCallSystemPipCoordinator(), ); - sl.registerLazySingleton(() => ResetPasswordService(sl())); - sl.registerLazySingleton(() => BlockedUserService(sl())); - sl.registerLazySingleton(() => CommentsService(sl())); - sl.registerLazySingleton(() => MyRecipesService(sl())); - sl.registerLazySingleton(() => ConsultantRatingService(sl())); - sl.registerLazySingleton(() => NotificationSettingsService(sl())); - sl.registerLazySingleton(() => ViewsService(sl())); + sl.registerLazySingleton( + () => ResetPasswordService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => BlockedUserService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => CommentsService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => MyRecipesService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => ConsultantRatingService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => NotificationSettingsService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => ViewsService(sl(), errorLogger: sl()), + ); sl.registerLazySingleton(() => const SbpServiceImpl()); - sl.registerLazySingleton(() => PersonalDietSuggestionService(sl())); - sl.registerLazySingleton(() => RegistrationServiceV2(sl())); + sl.registerLazySingleton( + () => PersonalDietSuggestionService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => RegistrationServiceV2(sl(), errorLogger: sl()), + ); // Content services - sl.registerLazySingleton(() => CreateRecipeService(sl())); - sl.registerLazySingleton(() => BlogPostService(sl())); - sl.registerLazySingleton(() => CreateDietService(sl())); + sl.registerLazySingleton( + () => CreateRecipeService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => BlogPostService(sl(), errorLogger: sl()), + ); + sl.registerLazySingleton( + () => CreateDietService(sl(), errorLogger: sl()), + ); // Auth services - sl.registerLazySingleton(() => RegistrationService(sl())); + sl.registerLazySingleton( + () => RegistrationService(sl(), errorLogger: sl()), + ); } } diff --git a/lib/core/error_reporting/api_response_dio.dart b/lib/core/error_reporting/api_response_dio.dart new file mode 100644 index 00000000..d9c51f9d --- /dev/null +++ b/lib/core/error_reporting/api_response_dio.dart @@ -0,0 +1,71 @@ +import 'package:dio/dio.dart'; +import 'package:dio/io.dart'; +import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart'; + +class ApiResponseDio extends DioForNative { + ApiResponseDio(BaseOptions super.options, this._responseErrors) { + transformer = _ApiResponseTransformer( + transformer, + _responseErrors, + _responseStatuses, + ); + } + + final ApiResponseErrorReporter _responseErrors; + final _responseStatuses = Expando(); + + @override + Future> fetch(RequestOptions requestOptions) async { + try { + return await super.fetch(requestOptions); + } on DioException catch (error) { + final cause = error.error; + final status = _responseStatuses[error.requestOptions]; + // Dio приводит тип корневого значения до вызова fromJson в Retrofit. + if (error.type == DioExceptionType.unknown && + error.requestOptions.responseType == ResponseType.json && + cause is TypeError && + status != null) { + _responseErrors.report( + error, + cause.stackTrace ?? error.stackTrace, + method: error.requestOptions.method, + statusCode: status, + ); + } + rethrow; + } + } +} + +class _ApiResponseTransformer implements Transformer { + _ApiResponseTransformer(this._delegate, this._responseErrors, this._statuses); + + final Transformer _delegate; + final ApiResponseErrorReporter _responseErrors; + final Expando _statuses; + + @override + Future transformRequest(RequestOptions options) => + _delegate.transformRequest(options); + + @override + Future transformResponse( + RequestOptions options, + ResponseBody response, + ) async { + try { + final data = await _delegate.transformResponse(options, response); + _statuses[options] = response.statusCode; + return data; + } on FormatException catch (error, stackTrace) { + _responseErrors.report( + error, + stackTrace, + method: options.method, + statusCode: response.statusCode, + ); + rethrow; + } + } +} diff --git a/lib/core/error_reporting/api_response_error_reporter.dart b/lib/core/error_reporting/api_response_error_reporter.dart new file mode 100644 index 00000000..54077d1e --- /dev/null +++ b/lib/core/error_reporting/api_response_error_reporter.dart @@ -0,0 +1,111 @@ +import 'dart:async'; +import 'dart:developer'; + +import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/error_reporting/error_reporter.dart'; +import 'package:retrofit/retrofit.dart'; + +class ApiResponseErrorReporter implements ParseErrorLogger { + ApiResponseErrorReporter(this._reporter); + + final ErrorReporter _reporter; + static final _capturedErrors = Expando(); + + static bool wasCaptured(Object error) => + _isCaptured(error) || (error is DioException && _isCaptured(error.error)); + + static bool _isCaptured(Object? error) => + error != null && + (error is Error || error is Exception) && + _capturedErrors[error] == true; + + static T decode( + ApiResponseErrorReporter? reporter, + Response response, + String endpoint, + T Function() parse, + ) { + try { + return parse(); + } catch (error, stackTrace) { + reporter?.report( + error, + stackTrace, + method: response.requestOptions.method, + statusCode: response.statusCode, + endpoint: endpoint, + ); + rethrow; + } + } + + @override + void logError( + Object error, + StackTrace stackTrace, + RequestOptions options, { + Response? response, + }) { + report( + error, + stackTrace, + method: options.method, + statusCode: response?.statusCode, + ); + } + + void report( + Object error, + StackTrace stackTrace, { + required String method, + int? statusCode, + String? endpoint, + }) { + if (error is Error || error is Exception) { + _capturedErrors[error] = true; + } + // Сообщение исходного исключения может содержать значения из ответа API. + final cause = error is DioException ? error.error ?? error : error; + unawaited( + _send( + ApiResponseDecodeException(cause.runtimeType.toString()), + stackTrace, + { + 'http_method': method, + 'http_status_code': ?statusCode, + 'endpoint': ?endpoint, + }, + ), + ); + } + + Future _send( + ApiResponseDecodeException error, + StackTrace stackTrace, + Map context, + ) async { + try { + await _reporter.report( + error, + stackTrace, + origin: 'api_response', + extras: context, + ); + } catch (reportError, reportStackTrace) { + log( + 'Не удалось записать ошибку разбора ответа API', + error: reportError.runtimeType, + stackTrace: reportStackTrace, + ); + } + } +} + +class ApiResponseDecodeException implements Exception { + ApiResponseDecodeException(this.causeType); + + final String causeType; + + @override + String toString() => 'Could not decode API response ($causeType)'; +} diff --git a/lib/core/error_reporting/error_report_policy.dart b/lib/core/error_reporting/error_report_policy.dart index e2864af7..0bf81933 100644 --- a/lib/core/error_reporting/error_report_policy.dart +++ b/lib/core/error_reporting/error_report_policy.dart @@ -1,6 +1,7 @@ import 'dart:io'; import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart'; import 'package:eatvio_app/core/push/hms_client_error.dart'; import 'package:sentry_flutter/sentry_flutter.dart'; @@ -14,6 +15,7 @@ class ErrorReportPolicy { /// When `false`, the error is not sent via [ErrorReporter]. static bool shouldReport(Object? error) { if (error == null) return false; + if (ApiResponseErrorReporter.wasCaptured(error)) return false; if (error is String) return false; if (error is SocketException) return false; if (isHmsClientUnavailable(error)) return false; @@ -34,11 +36,23 @@ class ErrorReportPolicy { final t = event.throwable; if (t == null) return true; if (t is DioException) { - return _allowSentrySdkDio(t); + return !ApiResponseErrorReporter.wasCaptured(t) && _allowSentrySdkDio(t); } return shouldReport(t); } + static SentryEvent? prepareSentryEvent(SentryEvent event, Hint hint) { + if (!allowSentryEvent(event, hint)) return null; + if (event.throwable is ApiResponseDecodeException) { + // HTTP breadcrumbs могут содержать идентификаторы в пути и параметры запроса. + event.breadcrumbs = event.breadcrumbs + ?.where((breadcrumb) => breadcrumb.category != 'http') + .toList(); + event.request = null; + } + return event; + } + /// Cancel, timeouts, socket / connection errors — do not send (noisy, often user environment). static bool _isTransientDioFailure(DioException e) { switch (e.type) { diff --git a/lib/core/routing/other_routes.dart b/lib/core/routing/other_routes.dart index f07247dd..f06f44ef 100644 --- a/lib/core/routing/other_routes.dart +++ b/lib/core/routing/other_routes.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:dio/dio.dart'; import 'package:eatvio_app/core/app_config.dart'; +import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart'; import 'package:eatvio_app/core/firebase_api.dart'; import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/core/prefs.dart'; @@ -103,7 +104,7 @@ class OtherRoutes { redirect: (context, state) async { try { // Проверка версии с таймаутом, чтобы не блокировать запуск приложения - final versions = await sl() + final response = await sl() .get('${sl().baseUrl}/api/app_versions') .timeout( const Duration(seconds: 5), @@ -111,12 +112,8 @@ class OtherRoutes { // При таймауте пропускаем проверку и идем дальше throw TimeoutException('Version check timeout'); }, - ) - .then((response) => response.data) - .catchError((e) { - // При любой ошибке пропускаем проверку версии - return null; - }); + ); + final versions = response.data; if (versions == null) { // Если проверка не удалась, пропускаем экран обновления @@ -126,7 +123,15 @@ class OtherRoutes { PackageInfo packageInfo = await PackageInfo.fromPlatform(); String version = packageInfo.version; Version currentVersion = Version.parse(version); - Version latestVersion = Version.parse(versions['min_version']); + final responseErrors = sl.isRegistered() + ? sl() + : null; + final latestVersion = ApiResponseErrorReporter.decode( + responseErrors, + response, + '/api/app_versions', + () => Version.parse(versions['min_version']), + ); if (latestVersion > currentVersion) { return null; } else { diff --git a/lib/core/views/service/views_service.dart b/lib/core/views/service/views_service.dart index e89990fa..fb0a3cef 100644 --- a/lib/core/views/service/views_service.dart +++ b/lib/core/views/service/views_service.dart @@ -6,7 +6,11 @@ part 'views_service.g.dart'; @RestApi() abstract class ViewsService { - factory ViewsService(Dio dio, {String baseUrl}) = _ViewsService; + factory ViewsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _ViewsService; @POST('/api/views') Future viewContent({ diff --git a/lib/core/websockets/ws_service.dart b/lib/core/websockets/ws_service.dart index 92d326f0..4f962918 100644 --- a/lib/core/websockets/ws_service.dart +++ b/lib/core/websockets/ws_service.dart @@ -8,7 +8,11 @@ part 'ws_service.g.dart'; @RestApi() abstract class WsService { - factory WsService(Dio dio, {String baseUrl}) = _WsService; + factory WsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _WsService; @GET('/api/profile/ws/params') Future getWebsocket(); diff --git a/lib/features/auth/services/auth_service.dart b/lib/features/auth/services/auth_service.dart index 2c7c6249..0fe4c9df 100644 --- a/lib/features/auth/services/auth_service.dart +++ b/lib/features/auth/services/auth_service.dart @@ -12,7 +12,11 @@ part 'auth_service.g.dart'; @RestApi() abstract class AuthService { - factory AuthService(Dio dio, {String? baseUrl}) = _AuthService; + factory AuthService( + Dio dio, { + String? baseUrl, + ParseErrorLogger? errorLogger, + }) = _AuthService; @POST('/api/login') Future getTokenByCredentials({@Body() required CredentialsModel credentials}); diff --git a/lib/features/auth/services/reset_password_service.dart b/lib/features/auth/services/reset_password_service.dart index 9a7a101d..8343468e 100644 --- a/lib/features/auth/services/reset_password_service.dart +++ b/lib/features/auth/services/reset_password_service.dart @@ -5,7 +5,11 @@ part 'reset_password_service.g.dart'; @RestApi() abstract class ResetPasswordService { - factory ResetPasswordService(Dio dio, {String baseUrl}) = _ResetPasswordService; + factory ResetPasswordService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _ResetPasswordService; @POST('/api/send_password_reset_code') Future sendEmailCodeForPasswordChange({ diff --git a/lib/features/barcode/services/barcode_service.dart b/lib/features/barcode/services/barcode_service.dart index e64e2575..31990b1c 100644 --- a/lib/features/barcode/services/barcode_service.dart +++ b/lib/features/barcode/services/barcode_service.dart @@ -1,24 +1,28 @@ -import 'package:dio/dio.dart'; -import 'package:eatvio_app/features/barcode/models/barcode_product_model.dart'; -import 'package:retrofit/retrofit.dart'; - -part 'barcode_service.g.dart'; - -@RestApi() -abstract class BarcodeService { - factory BarcodeService(Dio dio, {String baseUrl}) = _BarcodeService; - - @GET('/api/gsone/barcode/{barcode}') - Future getProductByBarcode({@Path('barcode') required String barcode}); - - @GET('/api/gsone/barcode/status/{task_id}') - Future getTaskStatus({@Path('task_id') required String taskId}); -} - - - - - - - - +import 'package:dio/dio.dart'; +import 'package:eatvio_app/features/barcode/models/barcode_product_model.dart'; +import 'package:retrofit/retrofit.dart'; + +part 'barcode_service.g.dart'; + +@RestApi() +abstract class BarcodeService { + factory BarcodeService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _BarcodeService; + + @GET('/api/gsone/barcode/{barcode}') + Future getProductByBarcode({@Path('barcode') required String barcode}); + + @GET('/api/gsone/barcode/status/{task_id}') + Future getTaskStatus({@Path('task_id') required String taskId}); +} + + + + + + + + diff --git a/lib/features/blog_post_create/services/blog_post_service.dart b/lib/features/blog_post_create/services/blog_post_service.dart index 72c0be12..eadb029b 100644 --- a/lib/features/blog_post_create/services/blog_post_service.dart +++ b/lib/features/blog_post_create/services/blog_post_service.dart @@ -5,7 +5,11 @@ part 'blog_post_service.g.dart'; @RestApi() abstract class BlogPostService { - factory BlogPostService(Dio dio, {String baseUrl}) = _BlogPostService; + factory BlogPostService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _BlogPostService; @POST('/api/v2/blogPosts/create/published') @MultiPart() diff --git a/lib/features/calendar/services/calendar_service.dart b/lib/features/calendar/services/calendar_service.dart index 2974f735..b2243f21 100644 --- a/lib/features/calendar/services/calendar_service.dart +++ b/lib/features/calendar/services/calendar_service.dart @@ -6,7 +6,11 @@ part 'calendar_service.g.dart'; @RestApi() abstract class CalendarService { - factory CalendarService(Dio dio, {String baseUrl}) = _CalendarService; + factory CalendarService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _CalendarService; @GET('/api/calendar/index') Future> getCalendar(); diff --git a/lib/features/cancel_plan_bottom_sheet/service/cancel_plan_service.dart b/lib/features/cancel_plan_bottom_sheet/service/cancel_plan_service.dart index ae677280..e7e18499 100644 --- a/lib/features/cancel_plan_bottom_sheet/service/cancel_plan_service.dart +++ b/lib/features/cancel_plan_bottom_sheet/service/cancel_plan_service.dart @@ -6,7 +6,11 @@ part 'cancel_plan_service.g.dart'; @RestApi() abstract class CancelPlanService { - factory CancelPlanService(Dio dio, {String baseUrl}) = _CancelPlanService; + factory CancelPlanService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _CancelPlanService; @POST('/api/chosen_plans/{id}/cancel') Future cancelChosenPlan({ diff --git a/lib/features/chat/services/chat_service.dart b/lib/features/chat/services/chat_service.dart index 3bd6a505..e51fcf8a 100644 --- a/lib/features/chat/services/chat_service.dart +++ b/lib/features/chat/services/chat_service.dart @@ -17,7 +17,11 @@ part 'chat_service.g.dart'; @RestApi() abstract class ChatService { - factory ChatService(Dio dio, {String baseUrl}) = _ChatService; + factory ChatService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _ChatService; @GET('/api/v2/chat/index') Future getChatRooms({ diff --git a/lib/features/complaining/services/complaining_service.dart b/lib/features/complaining/services/complaining_service.dart index 276ac750..90fb78b2 100644 --- a/lib/features/complaining/services/complaining_service.dart +++ b/lib/features/complaining/services/complaining_service.dart @@ -6,7 +6,11 @@ part 'complaining_service.g.dart'; @RestApi() abstract class ComplainingService { - factory ComplainingService(Dio dio, {String baseUrl}) = _ComplainingService; + factory ComplainingService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _ComplainingService; @POST('/api/plans/{slug}/complain/{category}') Future sendPlanComplain({ diff --git a/lib/features/consultant/become_consultant/services/consultant_service.dart b/lib/features/consultant/become_consultant/services/consultant_service.dart index 8458824d..2ab5f553 100644 --- a/lib/features/consultant/become_consultant/services/consultant_service.dart +++ b/lib/features/consultant/become_consultant/services/consultant_service.dart @@ -9,7 +9,11 @@ part 'consultant_service.g.dart'; @RestApi() abstract class ConsultantService { - factory ConsultantService(Dio dio, {String baseUrl}) = _ConsultantService; + factory ConsultantService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _ConsultantService; @POST('/api/v2/consultant_request/registration') Future consultantRegistration({ diff --git a/lib/features/consultant_rating/services/consultant_rating_service.dart b/lib/features/consultant_rating/services/consultant_rating_service.dart index c4412afb..a824f457 100644 --- a/lib/features/consultant_rating/services/consultant_rating_service.dart +++ b/lib/features/consultant_rating/services/consultant_rating_service.dart @@ -8,7 +8,11 @@ part 'consultant_rating_service.g.dart'; @RestApi() abstract class ConsultantRatingService { - factory ConsultantRatingService(Dio dio, {String baseUrl}) = _ConsultantRatingService; + factory ConsultantRatingService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _ConsultantRatingService; @GET('/api/consultants/rating/statistics') Future getConsultantStatistics({@Query('filters[duration][\$gte]') String? date}); diff --git a/lib/features/create_diet/services/create_diet_service.dart b/lib/features/create_diet/services/create_diet_service.dart index cc010293..e97d418a 100644 --- a/lib/features/create_diet/services/create_diet_service.dart +++ b/lib/features/create_diet/services/create_diet_service.dart @@ -6,7 +6,11 @@ part 'create_diet_service.g.dart'; @RestApi() abstract class CreateDietService { - factory CreateDietService(Dio dio, {String baseUrl}) = _CreateDietService; + factory CreateDietService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _CreateDietService; @POST('/api/diets/create/published') @MultiPart() diff --git a/lib/features/create_plan/services/create_plan_service.dart b/lib/features/create_plan/services/create_plan_service.dart index cafcba2f..9a10e6fa 100644 --- a/lib/features/create_plan/services/create_plan_service.dart +++ b/lib/features/create_plan/services/create_plan_service.dart @@ -5,7 +5,11 @@ part 'create_plan_service.g.dart'; @RestApi() abstract class CreatePlanService { - factory CreatePlanService(Dio dio, {String baseUrl}) = _CreatePlanService; + factory CreatePlanService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _CreatePlanService; @POST('/api/plans/create/published') @MultiPart() diff --git a/lib/features/create_recipe/services/recipe_service.dart b/lib/features/create_recipe/services/recipe_service.dart index 4bed540a..0bd6e0f9 100644 --- a/lib/features/create_recipe/services/recipe_service.dart +++ b/lib/features/create_recipe/services/recipe_service.dart @@ -8,7 +8,11 @@ part 'recipe_service.g.dart'; @RestApi() abstract class CreateRecipeService { - factory CreateRecipeService(Dio dio, {String baseUrl}) = _CreateRecipeService; + factory CreateRecipeService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _CreateRecipeService; @POST('/api/recipes/{slug}/like') Future likeRecipe({ diff --git a/lib/features/diary/services/diary_service.dart b/lib/features/diary/services/diary_service.dart index 985fb885..656009e1 100644 --- a/lib/features/diary/services/diary_service.dart +++ b/lib/features/diary/services/diary_service.dart @@ -13,7 +13,11 @@ part 'diary_service.g.dart'; @RestApi() abstract class DiaryService { - factory DiaryService(Dio dio, {String baseUrl}) = _DiaryService; + factory DiaryService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _DiaryService; @GET('/api/diary/index/{date}') Future> getDiaryIndexByDate({@Path('date') required String date}); diff --git a/lib/features/diets/services/diet_service.dart b/lib/features/diets/services/diet_service.dart index b25b8054..b4c7e509 100644 --- a/lib/features/diets/services/diet_service.dart +++ b/lib/features/diets/services/diet_service.dart @@ -7,7 +7,11 @@ part 'diet_service.g.dart'; @RestApi() abstract class DietService { - factory DietService(Dio dio, {String baseUrl}) = _DietService; + factory DietService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _DietService; @POST('/api/diets/{id}/like') Future likeDiet({ diff --git a/lib/features/feed/services/feed_service.dart b/lib/features/feed/services/feed_service.dart index 22a453be..90b35e2f 100644 --- a/lib/features/feed/services/feed_service.dart +++ b/lib/features/feed/services/feed_service.dart @@ -14,7 +14,11 @@ part 'feed_service.g.dart'; @RestApi() abstract class FeedService { - factory FeedService(Dio dio, {String baseUrl}) = _FeedService; + factory FeedService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _FeedService; @GET('/api/blogPosts/index') Future getBlogPostList({@Query('page') required int page, @Query('query_search') String? query}); diff --git a/lib/features/glossary/services/glossary_service.dart b/lib/features/glossary/services/glossary_service.dart index 8c28bb16..1ed4783d 100644 --- a/lib/features/glossary/services/glossary_service.dart +++ b/lib/features/glossary/services/glossary_service.dart @@ -6,7 +6,11 @@ part 'glossary_service.g.dart'; @RestApi() abstract class GlossaryService { - factory GlossaryService(Dio dio, {String baseUrl}) = _GlossaryService; + factory GlossaryService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _GlossaryService; @GET('/api/glossaries/search') Future getGlossaryByQuery({ diff --git a/lib/features/insights/services/insights_service.dart b/lib/features/insights/services/insights_service.dart index f0e64028..c7fe04b6 100644 --- a/lib/features/insights/services/insights_service.dart +++ b/lib/features/insights/services/insights_service.dart @@ -9,7 +9,11 @@ part 'insights_service.g.dart'; /// недоступный профиль — 403. @RestApi() abstract class InsightsService { - factory InsightsService(Dio dio, {String baseUrl}) = _InsightsService; + factory InsightsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _InsightsService; /// Свои графики целиком. @GET('/api/profile/insights') diff --git a/lib/features/menu/services/blocked_users_service.dart b/lib/features/menu/services/blocked_users_service.dart index 6a4ed987..a6ed6b13 100644 --- a/lib/features/menu/services/blocked_users_service.dart +++ b/lib/features/menu/services/blocked_users_service.dart @@ -6,7 +6,11 @@ part 'blocked_users_service.g.dart'; @RestApi() abstract class BlockedUserService { - factory BlockedUserService(Dio dio, {String baseUrl}) = _BlockedUserService; + factory BlockedUserService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _BlockedUserService; @GET('/api/blocked_users') Future getBlockedUsers(); diff --git a/lib/features/menu/services/notification_settings_service.dart b/lib/features/menu/services/notification_settings_service.dart index f489267f..ee08e819 100644 --- a/lib/features/menu/services/notification_settings_service.dart +++ b/lib/features/menu/services/notification_settings_service.dart @@ -6,7 +6,11 @@ part 'notification_settings_service.g.dart'; @RestApi() abstract class NotificationSettingsService { - factory NotificationSettingsService(Dio dio, {String baseUrl}) = _NotificationSettingsService; + factory NotificationSettingsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _NotificationSettingsService; @GET('/api/profile/notification_settings') Future getNotificationSettings(); diff --git a/lib/features/my_diets/services/my_diets_service.dart b/lib/features/my_diets/services/my_diets_service.dart index 41e3174f..b7224b10 100644 --- a/lib/features/my_diets/services/my_diets_service.dart +++ b/lib/features/my_diets/services/my_diets_service.dart @@ -7,7 +7,11 @@ part 'my_diets_service.g.dart'; @RestApi() abstract class MyDietsService { - factory MyDietsService(Dio dio, {String baseUrl}) = _MyDietsService; + factory MyDietsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _MyDietsService; @GET('/api/profile/my_diets') Future getDiets({ diff --git a/lib/features/my_finance/services/cards_service.dart b/lib/features/my_finance/services/cards_service.dart index c653d1a5..e051968b 100644 --- a/lib/features/my_finance/services/cards_service.dart +++ b/lib/features/my_finance/services/cards_service.dart @@ -7,7 +7,11 @@ part 'cards_service.g.dart'; @RestApi() abstract class CardsService { - factory CardsService(Dio dio, {String baseUrl}) = _CardsService; + factory CardsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _CardsService; @GET('/api/finances/cards') Future> getCards(); diff --git a/lib/features/my_plans/services/my_plans_service.dart b/lib/features/my_plans/services/my_plans_service.dart index bc24aec8..4eb15dd8 100644 --- a/lib/features/my_plans/services/my_plans_service.dart +++ b/lib/features/my_plans/services/my_plans_service.dart @@ -6,7 +6,11 @@ part 'my_plans_service.g.dart'; @RestApi() abstract class MyPlansService { - factory MyPlansService(Dio dio, {String baseUrl}) = _MyPlansService; + factory MyPlansService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _MyPlansService; @GET('/api/profile/my_plans') Future getPlans({ diff --git a/lib/features/notifications/service/notifications_service.dart b/lib/features/notifications/service/notifications_service.dart index dbe2d16c..9d815647 100644 --- a/lib/features/notifications/service/notifications_service.dart +++ b/lib/features/notifications/service/notifications_service.dart @@ -1,13 +1,17 @@ import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart'; import 'package:eatvio_app/features/notifications/models/notification_model.dart'; class NotificationsService { final Dio dio; - NotificationsService(this.dio); + final ApiResponseErrorReporter? responseErrors; + static const _endpoint = '/api/profile/notifications'; + + NotificationsService(this.dio, {this.responseErrors}); Future?> getNotifications({required int page}) async { + final response = await dio.get('$_endpoint?page=$page'); try { - final response = await dio.get('/api/profile/notifications?page=$page'); if (response.statusCode == 200) { final data = response.data['data'] as List; @@ -493,7 +497,14 @@ class NotificationsService { ), NotificationType.unknown => UnknownNotification(type: type, createdAt: parseDate(createdAt)), }; - } catch (e) { + } catch (error, stackTrace) { + responseErrors?.report( + error, + stackTrace, + method: response.requestOptions.method, + statusCode: response.statusCode, + endpoint: _endpoint, + ); return UnknownNotification(type: NotificationType.unknown, createdAt: DateTime.now()); } }).toList(); @@ -510,7 +521,14 @@ class NotificationsService { }; } return null; - } catch (e) { + } catch (error, stackTrace) { + responseErrors?.report( + error, + stackTrace, + method: response.requestOptions.method, + statusCode: response.statusCode, + endpoint: _endpoint, + ); rethrow; } } diff --git a/lib/features/payment/repositories/payment_repository.dart b/lib/features/payment/repositories/payment_repository.dart index 00d2ca75..82736126 100644 --- a/lib/features/payment/repositories/payment_repository.dart +++ b/lib/features/payment/repositories/payment_repository.dart @@ -1,4 +1,5 @@ import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/error_reporting/api_response_error_reporter.dart'; import 'package:eatvio_app/features/chat/models/payment_model.dart'; import 'package:eatvio_app/features/chat/services/chat_service.dart'; import 'package:eatvio_app/features/payment/models/promo_applied_list_response.dart'; @@ -10,8 +11,9 @@ import 'package:eatvio_app/features/payment/models/promo_validate_response.dart' /// Репозиторий оплаты консультаций (chosen_plan) через Alfa Bank / СБП. class PaymentRepository { final ChatService chatService; + final ApiResponseErrorReporter? responseErrors; - PaymentRepository({required this.chatService}); + PaymentRepository({required this.chatService, this.responseErrors}); /// Запускает процесс оплаты: POST `/api/chosen_plans/{id}/start_payment_process` /// с `payment_provider: alfa-bank`. @@ -64,9 +66,15 @@ class PaymentRepository { body: {'promo_code': promoCode}, ); } on DioException catch (e) { - final data = e.response?.data; - if (data is Map) { - return PromoApplyResponse.fromJson(data); + final response = e.response; + final data = response?.data; + if (response != null && data is Map) { + return ApiResponseErrorReporter.decode( + responseErrors, + response, + '/api/chosen_plans/{id}/apply_promo', + () => PromoApplyResponse.fromJson(data), + ); } rethrow; } @@ -77,9 +85,15 @@ class PaymentRepository { try { return await chatService.removePromoCode(id: planId); } on DioException catch (e) { - final data = e.response?.data; - if (data is Map) { - return PromoRemoveResponse.fromJson(data); + final response = e.response; + final data = response?.data; + if (response != null && data is Map) { + return ApiResponseErrorReporter.decode( + responseErrors, + response, + '/api/chosen_plans/{id}/remove_promo_code', + () => PromoRemoveResponse.fromJson(data), + ); } rethrow; } diff --git a/lib/features/personal_diet_suggestion/services/personal_diet_suggestion_service.dart b/lib/features/personal_diet_suggestion/services/personal_diet_suggestion_service.dart index 245cbdbd..db9be06d 100644 --- a/lib/features/personal_diet_suggestion/services/personal_diet_suggestion_service.dart +++ b/lib/features/personal_diet_suggestion/services/personal_diet_suggestion_service.dart @@ -6,8 +6,11 @@ part 'personal_diet_suggestion_service.g.dart'; @RestApi() abstract class PersonalDietSuggestionService { - factory PersonalDietSuggestionService(Dio dio, {String? baseUrl}) = - _PersonalDietSuggestionService; + factory PersonalDietSuggestionService( + Dio dio, { + String? baseUrl, + ParseErrorLogger? errorLogger, + }) = _PersonalDietSuggestionService; @GET('/api/consultations') Future getConsultationWithPersonalDiets({ diff --git a/lib/features/plans/services/plan_service.dart b/lib/features/plans/services/plan_service.dart index 8a179760..6a7105c6 100644 --- a/lib/features/plans/services/plan_service.dart +++ b/lib/features/plans/services/plan_service.dart @@ -7,7 +7,11 @@ part 'plan_service.g.dart'; @RestApi() abstract class PlanService { - factory PlanService(Dio dio, {String baseUrl}) = _PlanService; + factory PlanService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _PlanService; @GET('/api/plans/show/{slug}') Future getPlan(@Path('slug') String slug); diff --git a/lib/features/plans/services/plans_service.dart b/lib/features/plans/services/plans_service.dart index 5f8769ce..10d4257d 100644 --- a/lib/features/plans/services/plans_service.dart +++ b/lib/features/plans/services/plans_service.dart @@ -6,7 +6,11 @@ part 'plans_service.g.dart'; @RestApi() abstract class PlansService { - factory PlansService(Dio dio, {String baseUrl}) = _PlansService; + factory PlansService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _PlansService; @GET('/api/plans/get_by_author/{author}') Future getPlansBySlug({ diff --git a/lib/features/profile/services/profile_service.dart b/lib/features/profile/services/profile_service.dart index 95117d36..60910256 100644 --- a/lib/features/profile/services/profile_service.dart +++ b/lib/features/profile/services/profile_service.dart @@ -14,7 +14,11 @@ part 'profile_service.g.dart'; @RestApi() abstract class ProfileService { - factory ProfileService(Dio dio, {String baseUrl}) = _ProfileService; + factory ProfileService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _ProfileService; @GET('/api/profile/show/{slug}') Future getProfileBySlug({@Path() required String slug}); diff --git a/lib/features/recipe/services/about_recipe_service.dart b/lib/features/recipe/services/about_recipe_service.dart index 21170ed4..b1edadbb 100644 --- a/lib/features/recipe/services/about_recipe_service.dart +++ b/lib/features/recipe/services/about_recipe_service.dart @@ -6,7 +6,11 @@ part 'about_recipe_service.g.dart'; @RestApi() abstract class AboutRecipeService { - factory AboutRecipeService(Dio dio, {String baseUrl}) = _AboutRecipeService; + factory AboutRecipeService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _AboutRecipeService; @POST('/api/recipes/{slug}/like') Future likeRecipe({ diff --git a/lib/features/recipe/services/my_recipes_service.dart b/lib/features/recipe/services/my_recipes_service.dart index 7500edcb..436debae 100644 --- a/lib/features/recipe/services/my_recipes_service.dart +++ b/lib/features/recipe/services/my_recipes_service.dart @@ -6,7 +6,11 @@ part 'my_recipes_service.g.dart'; @RestApi() abstract class MyRecipesService { - factory MyRecipesService(Dio dio, {String baseUrl}) = _MyRecipesService; + factory MyRecipesService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _MyRecipesService; @GET('/api/recipes/my') Future getMyRecipes(); diff --git a/lib/features/registration/services/registration_service.dart b/lib/features/registration/services/registration_service.dart index 200c2f6f..c1b1b752 100644 --- a/lib/features/registration/services/registration_service.dart +++ b/lib/features/registration/services/registration_service.dart @@ -6,7 +6,11 @@ part 'registration_service.g.dart'; @RestApi() abstract class RegistrationService { - factory RegistrationService(Dio dio, {String baseUrl}) = _RegistrationService; + factory RegistrationService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _RegistrationService; @POST('/api/register') Future> register({ diff --git a/lib/features/registration_v2/services/registration_service_v2.dart b/lib/features/registration_v2/services/registration_service_v2.dart index 2472eb40..53a0bfbf 100644 --- a/lib/features/registration_v2/services/registration_service_v2.dart +++ b/lib/features/registration_v2/services/registration_service_v2.dart @@ -5,7 +5,11 @@ part 'registration_service_v2.g.dart'; @RestApi() abstract class RegistrationServiceV2 { - factory RegistrationServiceV2(Dio dio, {String baseUrl}) = _RegistrationServiceV2; + factory RegistrationServiceV2( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _RegistrationServiceV2; @POST('/api/register') Future> register({ diff --git a/lib/features/settings/services/settings_service.dart b/lib/features/settings/services/settings_service.dart index c83f4c41..c35e617c 100644 --- a/lib/features/settings/services/settings_service.dart +++ b/lib/features/settings/services/settings_service.dart @@ -9,7 +9,11 @@ part 'settings_service.g.dart'; @RestApi() abstract class SettingsService { - factory SettingsService(Dio dio, {String baseUrl}) = _SettingsService; + factory SettingsService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _SettingsService; @GET('/api/profile/settings') Future getProfileSettings(); diff --git a/lib/features/video_calls/services/video_call_service.dart b/lib/features/video_calls/services/video_call_service.dart index 88768381..530c9ab2 100644 --- a/lib/features/video_calls/services/video_call_service.dart +++ b/lib/features/video_calls/services/video_call_service.dart @@ -7,7 +7,11 @@ part 'video_call_service.g.dart'; @RestApi() abstract class VideoCallService { - factory VideoCallService(Dio dio, {String baseUrl}) = _VideoCallService; + factory VideoCallService( + Dio dio, { + String baseUrl, + ParseErrorLogger? errorLogger, + }) = _VideoCallService; @GET('/api/v2/chat/{conversation}/video-call/token') Future getParticipantToken({ diff --git a/lib/main.dart b/lib/main.dart index bbc8e5d4..4a2c77fd 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -16,13 +16,14 @@ import 'package:flutter_portal/flutter_portal.dart'; import 'package:keyboard_dismisser/keyboard_dismisser.dart'; Future main() async { - WidgetsFlutterBinding.ensureInitialized(); - FlutterForegroundTask.initCommunicationPort(); - VideoCallForegroundBootstrap.ensureInitialized(); - await AppInitializer.initialize(buildType: AppBuildType.prod); - await sl().initialize(); - await PushNavigationHandler.initialize(); - await AppInitializer.runAppWithSentry(() => runApp(const MyApp())); + await AppInitializer.runAppWithSentry(() async { + FlutterForegroundTask.initCommunicationPort(); + VideoCallForegroundBootstrap.ensureInitialized(); + await AppInitializer.initialize(buildType: AppBuildType.prod); + await sl().initialize(); + await PushNavigationHandler.initialize(); + runApp(const MyApp()); + }); } class MyApp extends StatefulWidget { diff --git a/test/core/error_reporting/api_response_reporting_test.dart b/test/core/error_reporting/api_response_reporting_test.dart new file mode 100644 index 00000000..ad19d30d --- /dev/null +++ b/test/core/error_reporting/api_response_reporting_test.dart @@ -0,0 +1,311 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:dio/dio.dart'; +import 'package:eatvio_app/core/app_initializer.dart'; +import 'package:eatvio_app/core/di/app_config_registration.dart'; +import 'package:eatvio_app/core/di/external_registrations.dart'; +import 'package:eatvio_app/core/di/repository_registrations.dart'; +import 'package:eatvio_app/core/di/service_registrations.dart'; +import 'package:eatvio_app/core/error_reporting/error_report_policy.dart'; +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/prefs_keys.dart'; +import 'package:eatvio_app/core/routing/other_routes.dart'; +import 'package:eatvio_app/core/routing/route_constants.dart'; +import 'package:eatvio_app/core/token_storage.dart'; +import 'package:eatvio_app/features/notifications/models/notification_model.dart'; +import 'package:eatvio_app/features/notifications/service/notifications_service.dart'; +import 'package:eatvio_app/features/payment/repositories/payment_repository.dart'; +import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:eatvio_app/features/recipe/presentation/cubit/about_recipe_cubit.dart'; +import 'package:eatvio_app/features/recipe/presentation/cubit/about_recipe_state.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:sentry_flutter/sentry_flutter.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late _MemoryTransport transport; + late List events; + + setUp(() async { + transport = _MemoryTransport(); + events = []; + await Sentry.init((options) { + options.dsn = 'https://test@example.invalid/1'; + options.transport = transport; + options.sendClientReports = false; + // Проверяем дедупликацию в приложении независимо от кеша SDK. + options.enableDeduplication = false; + options.beforeSend = (event, hint) { + final prepared = ErrorReportPolicy.prepareSentryEvent(event, hint); + if (prepared != null) events.add(prepared); + return prepared; + }; + }); + + dotenv.loadFromString( + envString: 'DEV_BASE_URL=https://api.example.invalid', + ); + SharedPreferences.setMockInitialValues({ + PrefsKeys.welcomeScreenWasShowed.name: true, + 'token': 'synthetic-token', + }); + AppConfigRegistration.registerAppConfig(buildType: AppBuildType.tests); + ExternalRegistrations.registerAll(); + ServiceRegistrations.registerAll(); + RepositoryRegistrations.registerAll(); + }); + + tearDown(() async { + TokenStorage.clearCache(); + await sl.reset(); + await Sentry.close(); + }); + + test( + 'reports a missing recipe field once and keeps the original stack', + () async { + sl().httpClientAdapter = _ResponseAdapter(200, '{}'); + final cubit = AboutRecipeCubit( + recipeRepository: sl(), + profileRepository: sl(), + ); + addTearDown(cubit.close); + + await cubit.initRecipe('private-recipe-id'); + await transport.waitForEvent(); + + expect(cubit.state, isA()); + expect(events.single.tags?['origin'], 'api_response'); + expect( + events.single.exceptions!.single.stackTrace!.frames.any( + (frame) => frame.fileName?.endsWith('recipes_model.g.dart') ?? false, + ), + isTrue, + ); + expect(transport.sent, hasLength(1)); + }, + ); + + test( + 'reports a malformed profile even when the welcome redirect handles it', + () async { + final adapter = _ResponseAdapter(200, '{}'); + sl().httpClientAdapter = adapter; + final route = OtherRoutes.createRoutes().whereType().singleWhere( + (route) => route.path == RouteConstants.welcomeScreen, + ); + + expect( + await route.redirect!(_BuildContext(), _RouterState()), + RouteConstants.authScreen, + ); + await transport.waitForEvent(); + + expect(adapter.requests.single.path, '/api/profile/index'); + expect(events.single.exceptions!.single.value, contains('TypeError')); + expect(transport.sent, hasLength(1)); + }, + ); + + test( + 'reports invalid JSON without sending its contents or HTTP breadcrumbs', + () async { + const secret = 'private-patient-data'; + sl().httpClientAdapter = _ResponseAdapter(200, '{"$secret":'); + await Sentry.addBreadcrumb( + Breadcrumb.http( + url: Uri.parse('https://api.example.invalid/user/$secret'), + method: 'GET', + httpQuery: 'profile=$secret', + ), + ); + + await expectLater( + sl().getMyProfile(), + throwsA(isA()), + ); + await transport.waitForEvent(); + + final event = events.single; + expect(event.exceptions!.single.value, contains('FormatException')); + expect(event.exceptions!.single.stackTrace!.frames, isNotEmpty); + expect(event.tags?['origin'], 'api_response'); + expect( + event.contexts['report_extras'], + containsPair('http_status_code', '200'), + ); + expect(jsonEncode(event.toJson()), isNot(contains(secret))); + }, + ); + + test( + 'reports the wrong JSON root type before the Retrofit model parser', + () async { + sl().httpClientAdapter = _ResponseAdapter(200, '[]'); + + await expectLater( + sl().getMyProfile(), + throwsA(isA()), + ); + await transport.waitForEvent(); + + expect(events.single.exceptions!.single.value, contains('TypeError')); + expect( + events.single.contexts['report_extras'], + containsPair('http_status_code', '200'), + ); + }, + ); + + test( + 'reports a malformed notification and keeps the replacement item', + () async { + sl().httpClientAdapter = _ResponseAdapter( + 200, + '{"data":[17],"current_page":1,"last_page":1,"per_page":20,"total":1}', + ); + + final result = await sl().getNotifications(page: 1); + await transport.waitForEvent(); + + expect( + (result!['notifications'] as List).single, + isA(), + ); + expect( + events.single.contexts['report_extras'], + containsPair('endpoint', '/api/profile/notifications'), + ); + }, + ); + + test( + 'reports an invalid minimum version and still skips the update screen', + () async { + PackageInfo.setMockInitialValues( + appName: 'Eatvio', + packageName: 'example.invalid', + version: '1.0.0', + buildNumber: '1', + buildSignature: '', + ); + sl().httpClientAdapter = _ResponseAdapter( + 200, + '{"min_version":"invalid"}', + ); + final route = OtherRoutes.createRoutes().whereType().singleWhere( + (route) => route.path == RouteConstants.updateScreen, + ); + + expect( + await route.redirect!(_BuildContext(), _RouterState()), + RouteConstants.welcomeScreen, + ); + await transport.waitForEvent(); + + expect( + events.single.contexts['report_extras'], + containsPair('endpoint', '/api/app_versions'), + ); + }, + ); + + test( + 'reports a malformed 422 promo response after its manual parse', + () async { + sl().httpClientAdapter = _ResponseAdapter(422, '{}'); + + await expectLater( + sl().applyPromoCode( + planId: 42, + promoCode: 'private', + ), + throwsA(isA()), + ); + await transport.waitForEvent(); + + expect( + events.single.contexts['report_extras'], + containsPair('http_status_code', '422'), + ); + expect(transport.sent, hasLength(1)); + }, + ); + + test('keeps expected 4xx quiet and captures a regular 5xx once', () async { + final dio = sl(); + final cubit = AboutRecipeCubit( + recipeRepository: sl(), + profileRepository: sl(), + ); + addTearDown(cubit.close); + + dio.httpClientAdapter = _ResponseAdapter(404, '{}'); + await cubit.initRecipe('synthetic'); + expect(events, isEmpty); + + dio.httpClientAdapter = _ResponseAdapter(500, '{}'); + await cubit.initRecipe('synthetic'); + await transport.waitForEvent(); + + expect( + events.single.exceptions!.first.mechanism!.type, + 'SentryDioClientAdapter', + ); + expect(transport.sent, hasLength(1)); + }); +} + +class _ResponseAdapter implements HttpClientAdapter { + _ResponseAdapter(this.statusCode, this.body); + + final int statusCode; + final String body; + final requests = []; + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + requests.add(options); + return ResponseBody.fromString( + body, + statusCode, + headers: { + Headers.contentTypeHeader: [Headers.jsonContentType], + }, + ); + } + + @override + void close({bool force = false}) {} +} + +class _MemoryTransport implements Transport { + final sent = []; + final _firstEvent = Completer(); + + Future waitForEvent() => + _firstEvent.future.timeout(const Duration(seconds: 2)); + + @override + Future send(SentryEnvelope envelope) async { + sent.add(envelope); + if (!_firstEvent.isCompleted) _firstEvent.complete(); + return envelope.header.eventId; + } +} + +class _BuildContext extends Fake implements BuildContext {} + +class _RouterState extends Fake implements GoRouterState {} From 47b81fba5ad79d0aa15aab4ed03628b58d572fc6 Mon Sep 17 00:00:00 2001 From: misha Date: Fri, 20 Nov 2026 14:25:16 +0300 Subject: [PATCH 4/6] version changed --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index 3f5a8ec7..e020bfd2 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: eatvio_app description: A new Flutter project. -version: 1.3.74+163 +version: 1.3.75+164 publish_to: 'none' environment: From 0df474b2b583a4a081d42f0ddf4a20af49ce827a Mon Sep 17 00:00:00 2001 From: alex-chevski Date: Fri, 20 Nov 2026 16:30:13 +0300 Subject: [PATCH 5/6] fix: plans - like and bookmark in consultant profile (#582) - decouple PlanWidget from feed PlansCubit via owner-provided callbacks - add like/favorite actions to profile PlansCubit: slug lookup, optimistic update, rollback of the affected plan, per-slug debounce, isClosed guards - pass slug through like/favorite/comments events; guard out-of-range index in feed plans handlers and deep-link about_plan sync - capture post like intent before await in profile blog post widget - replace null force-unwraps in profile screen, guard indexOf == -1 - tests: profile plan like/bookmark, slug sync, bounds guards, #700 regression --- lib/core/di/cubit_registrations.dart | 5 +- lib/core/widgets/custom_popup.dart | 12 +- .../diets/repositories/diet_repository.dart | 9 + .../bloc/plans_cubit/plans_cubit.dart | 71 ++-- .../presentation/widgets/plan_widget.dart | 35 +- .../feed/presentation/widgets/plans.dart | 10 +- .../presentation/cubit/about_plan_cubit.dart | 57 +-- .../plans/repositories/plan_repository.dart | 6 +- .../bloc/plans_cubit/plans_cubit.dart | 180 ++++++++- .../bloc/profile_cubit/profile_cubit.dart | 1 + .../presentation/pages/profile_screen.dart | 53 ++- .../widgets/profile_blog_post_widget.dart | 23 +- .../plans_cubit_slug_sync_test.dart | 194 ++++++++++ .../plans_cubit_sync_guard_test.dart | 172 +++++++++ .../bloc/plans_cubit/plans_cubit_test.dart | 72 +++- .../profile_plans_cubit_like_test.dart | 363 ++++++++++++++++++ .../profile_plans_cubit_slug_sync_test.dart | 127 ++++++ ...ile_cubit_update_feed_regression_test.dart | 133 +++++++ ...ile_screen_consultant_null_links_test.dart | 211 ++++++++++ .../pages/profile_screen_plan_like_test.dart | 272 +++++++++++++ .../pages/profile_screen_smoke_test.dart | 14 +- .../profile_blog_post_widget_like_test.dart | 256 ++++++++++++ 22 files changed, 2139 insertions(+), 137 deletions(-) create mode 100644 test/features/feed/presentation/bloc/plans_cubit/plans_cubit_slug_sync_test.dart create mode 100644 test/features/feed/presentation/bloc/plans_cubit/plans_cubit_sync_guard_test.dart create mode 100644 test/features/profile/presentation/bloc/plans_cubit/profile_plans_cubit_like_test.dart create mode 100644 test/features/profile/presentation/bloc/plans_cubit/profile_plans_cubit_slug_sync_test.dart create mode 100644 test/features/profile/presentation/bloc/profile_cubit/profile_cubit_update_feed_regression_test.dart create mode 100644 test/features/profile/presentation/pages/profile_screen_consultant_null_links_test.dart create mode 100644 test/features/profile/presentation/pages/profile_screen_plan_like_test.dart create mode 100644 test/features/profile/presentation/widgets/profile_blog_post_widget_like_test.dart diff --git a/lib/core/di/cubit_registrations.dart b/lib/core/di/cubit_registrations.dart index 92ba8925..b44e2517 100644 --- a/lib/core/di/cubit_registrations.dart +++ b/lib/core/di/cubit_registrations.dart @@ -183,7 +183,10 @@ class CubitRegistrations { ), ); sl.registerFactory( - () => profile_plans.PlansCubit(plansRepository: sl()), + () => profile_plans.PlansCubit( + plansRepository: sl(), + planRepository: sl(), + ), ); sl.registerFactory(() => SubCubit(profileRepository: sl())); diff --git a/lib/core/widgets/custom_popup.dart b/lib/core/widgets/custom_popup.dart index 26033b3d..afd90fd4 100644 --- a/lib/core/widgets/custom_popup.dart +++ b/lib/core/widgets/custom_popup.dart @@ -44,6 +44,7 @@ class CustomPopup extends StatelessWidget { final PlanModel? plan; final String userSlug; final VoidCallback? onPostsChanged; + final VoidCallback? onPlanChanged; const CustomPopup({ super.key, @@ -59,6 +60,7 @@ class CustomPopup extends StatelessWidget { this.plan, required this.userSlug, this.onPostsChanged, + this.onPlanChanged, }); bool get _isAdminAuthor => @@ -166,9 +168,13 @@ class CustomPopup extends StatelessWidget { try { context.read().getPlan(slug: currentPlan.slug); } catch (_) {} - try { - context.read().loadPlans(); - } catch (_) {} + if (onPlanChanged != null) { + onPlanChanged!(); + } else { + try { + context.read().loadPlans(); + } catch (_) {} + } try { context.read().loadPlans(); } catch (_) {} diff --git a/lib/features/diets/repositories/diet_repository.dart b/lib/features/diets/repositories/diet_repository.dart index 9dc83ecb..0ffc4161 100644 --- a/lib/features/diets/repositories/diet_repository.dart +++ b/lib/features/diets/repositories/diet_repository.dart @@ -66,11 +66,13 @@ class LikesState extends Equatable { final bool wasLikedByMe; final int totalLikes; final int index; + final String? slug; const LikesState({ required this.wasLikedByMe, required this.totalLikes, required this.index, + this.slug, }); @override @@ -78,37 +80,44 @@ class LikesState extends Equatable { wasLikedByMe, totalLikes, index, + slug, ]; } class FavoriteState extends Equatable { final bool isFavorite; final int index; + final String? slug; const FavoriteState({ required this.isFavorite, required this.index, + this.slug, }); @override List get props => [ isFavorite, index, + slug, ]; } class CommentsState extends Equatable { final int index; final int totalComments; + final String? slug; const CommentsState({ required this.index, required this.totalComments, + this.slug, }); @override List get props => [ index, totalComments, + slug, ]; } diff --git a/lib/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart b/lib/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart index 20da68a0..6aa39913 100644 --- a/lib/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart +++ b/lib/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart @@ -5,6 +5,7 @@ import 'package:easy_debounce/easy_debounce.dart'; import 'package:eatvio_app/core/const.dart'; import 'package:eatvio_app/core/utils/toasts.dart'; import 'package:eatvio_app/features/diets/repositories/diet_repository.dart'; +import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_state.dart'; import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; import 'package:eatvio_app/features/plans/repositories/plan_repository.dart'; @@ -87,57 +88,51 @@ class PlansCubit extends Cubit { } void _changePlanLikeState(LikesState likesState) { - final currentPlans = state.plans; - final plansForModification = [...currentPlans]; - final currentPlan = currentPlans[likesState.index]; - - plansForModification[likesState.index] = currentPlan.copyWith( - totalLikes: likesState.totalLikes, - wasLikedByMe: likesState.wasLikedByMe, - ); - emit( - state.copyWith( - plans: [ - ...plansForModification, - ], - isLoading: isLoading, - errorMessage: null, + _updatePlanAt( + slug: likesState.slug, + index: likesState.index, + transform: (currentPlan) => currentPlan.copyWith( + totalLikes: likesState.totalLikes, + wasLikedByMe: likesState.wasLikedByMe, ), ); } void _changePlanFavoriteState(FavoriteState favoriteState) { - final currentPlans = state.plans; - final plansForModification = [...currentPlans]; - final currentPlan = currentPlans[favoriteState.index]; - - plansForModification[favoriteState.index] = currentPlan.copyWith( - isFavorite: favoriteState.isFavorite, - ); - emit( - state.copyWith( - plans: [ - ...plansForModification, - ], - isLoading: isLoading, - errorMessage: null, + _updatePlanAt( + slug: favoriteState.slug, + index: favoriteState.index, + transform: (currentPlan) => currentPlan.copyWith( + isFavorite: favoriteState.isFavorite, ), ); } void _changePlanCommentsState(CommentsState commentsState) { - final currentPlans = state.plans; - final plansForModification = [...currentPlans]; - final currentPlan = currentPlans[commentsState.index]; - - plansForModification[commentsState.index] = currentPlan.copyWith( - totalComments: commentsState.totalComments, + _updatePlanAt( + slug: commentsState.slug, + index: commentsState.index, + transform: (currentPlan) => currentPlan.copyWith( + totalComments: commentsState.totalComments, + ), ); + } + + void _updatePlanAt({ + required String? slug, + required int index, + required PlanModel Function(PlanModel currentPlan) transform, + }) { + final currentPlans = state.plans; + final targetIndex = + slug != null ? currentPlans.indexWhere((plan) => plan.slug == slug) : index; + if (targetIndex < 0 || targetIndex >= currentPlans.length) return; + + final plansForModification = [...currentPlans]; + plansForModification[targetIndex] = transform(currentPlans[targetIndex]); emit( state.copyWith( - plans: [ - ...plansForModification, - ], + plans: plansForModification, isLoading: isLoading, errorMessage: null, ), diff --git a/lib/features/feed/presentation/widgets/plan_widget.dart b/lib/features/feed/presentation/widgets/plan_widget.dart index a8a05179..d6784ead 100644 --- a/lib/features/feed/presentation/widgets/plan_widget.dart +++ b/lib/features/feed/presentation/widgets/plan_widget.dart @@ -13,10 +13,8 @@ import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/core/theme/custom_text_style.dart'; import 'package:eatvio_app/core/utils/url_utils.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; -import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:material_ui/material_ui.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; import 'package:share_plus/share_plus.dart'; @@ -24,8 +22,18 @@ import 'package:share_plus/share_plus.dart'; class PlanWidget extends StatefulWidget { final PlanModel plan; final int index; + final Future Function(String slug)? onLikeTap; + final Future Function(String slug, bool isFavorite)? onToggleFavorite; + final VoidCallback? onPlanChanged; - const PlanWidget({super.key, required this.plan, required this.index}); + const PlanWidget({ + super.key, + required this.plan, + required this.index, + this.onLikeTap, + this.onToggleFavorite, + this.onPlanChanged, + }); @override State createState() => _PlanWidgetState(); @@ -71,17 +79,10 @@ class _PlanWidgetState extends State { left: 14, child: BookmarkButton( onTap: () async { - if (widget.plan.isFavorite) { - await context.read().removePlanFromFavorite( - widget.plan.slug, - widget.index, - ); - } else { - await context.read().addPlanToFavorite( - widget.plan.slug, - widget.index, - ); - } + await widget.onToggleFavorite?.call( + widget.plan.slug, + widget.plan.isFavorite, + ); }, color: appTheme.whiteA700, isFavorite: widget.plan.isFavorite, @@ -111,6 +112,7 @@ class _PlanWidgetState extends State { plan: widget.plan, complainedContentType: ComplainedContent.plan, userSlug: widget.plan.author.authorSlug, + onPlanChanged: widget.onPlanChanged, ), ), ), @@ -255,10 +257,7 @@ class _PlanWidgetState extends State { ? appTheme.transparentBlue : null, onTap: () async { - await context.read().likePlan( - widget.plan.slug, - widget.index, - ); + await widget.onLikeTap?.call(widget.plan.slug); }, ), const SizedBox(width: 12), diff --git a/lib/features/feed/presentation/widgets/plans.dart b/lib/features/feed/presentation/widgets/plans.dart index 78bd3f65..17290e04 100644 --- a/lib/features/feed/presentation/widgets/plans.dart +++ b/lib/features/feed/presentation/widgets/plans.dart @@ -44,7 +44,15 @@ class Plans extends StatelessWidget { final id = state.plans[index].id; handleVisibility(visibleFraction: info.visibleFraction, id: id, type: ViewableContentType.plans); }, - child: PlanWidget(plan: state.plans[index], index: index), + child: PlanWidget( + plan: state.plans[index], + index: index, + onLikeTap: (slug) => context.read().likePlan(slug, index), + onToggleFavorite: (slug, isFavorite) => isFavorite + ? context.read().removePlanFromFavorite(slug, index) + : context.read().addPlanToFavorite(slug, index), + onPlanChanged: () => context.read().loadPlans(), + ), ); }, separatorBuilder: (context, index) { diff --git a/lib/features/plans/presentation/cubit/about_plan_cubit.dart b/lib/features/plans/presentation/cubit/about_plan_cubit.dart index 6cd354aa..0650097d 100644 --- a/lib/features/plans/presentation/cubit/about_plan_cubit.dart +++ b/lib/features/plans/presentation/cubit/about_plan_cubit.dart @@ -27,9 +27,9 @@ class AboutPlanCubit extends Cubit { Future getPlan({required String slug, int? index}) async { try { final plan = await planRepository.getPlan(slug); - if (index != null) { - planRepository.emitCommentsStateToFeed(CommentsState(index: index, totalComments: plan.totalComments)); - } + planRepository.emitCommentsStateToFeed( + CommentsState(index: index ?? 0, totalComments: plan.totalComments, slug: slug), + ); emit(state.copyWith(planModel: plan, error: null)); } catch (e, stackTrace) { await reportFrom(e, stackTrace, this); @@ -59,14 +59,20 @@ class AboutPlanCubit extends Cubit { if (currentPlan == null) return; if (currentPlan.wasLikedByMe) { emit(state.copyWith(planModel: currentPlan.copyWith(wasLikedByMe: false, totalLikes: currentPlan.totalLikes - 1), error: null)); - if (index != null) { - planRepository.emitLikesStateToFeed(LikesState(wasLikedByMe: false, totalLikes: currentPlan.totalLikes - 1, index: index)); - } + planRepository.emitLikesStateToFeed(LikesState( + wasLikedByMe: false, + totalLikes: currentPlan.totalLikes - 1, + index: index ?? 0, + slug: slug, + )); } else { emit(state.copyWith(planModel: currentPlan.copyWith(wasLikedByMe: true, totalLikes: currentPlan.totalLikes + 1), error: null)); - if (index != null) { - planRepository.emitLikesStateToFeed(LikesState(wasLikedByMe: true, totalLikes: currentPlan.totalLikes + 1, index: index)); - } + planRepository.emitLikesStateToFeed(LikesState( + wasLikedByMe: true, + totalLikes: currentPlan.totalLikes + 1, + index: index ?? 0, + slug: slug, + )); } EasyDebounce.debounce('like_plan_$slug', const Duration(seconds: 1), () async { @@ -75,9 +81,12 @@ class AboutPlanCubit extends Cubit { } catch (e, st) { await reportFrom(e, st, this); log(e.toString()); - if (index != null) { - planRepository.emitLikesStateToFeed(LikesState(wasLikedByMe: currentPlan.wasLikedByMe, totalLikes: currentPlan.totalLikes, index: index)); - } + planRepository.emitLikesStateToFeed(LikesState( + wasLikedByMe: currentPlan.wasLikedByMe, + totalLikes: currentPlan.totalLikes, + index: index ?? 0, + slug: slug, + )); emit(state.copyWith(planModel: currentPlan, error: null)); } }); @@ -88,9 +97,9 @@ class AboutPlanCubit extends Cubit { if (currentPlan == null) return; emit(state.copyWith(planModel: currentPlan.copyWith(isFavorite: true))); - if (index != null) { - planRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: true, index: index)); - } + planRepository.emitFavoriteStateToFeed( + FavoriteState(isFavorite: true, index: index ?? 0, slug: slug), + ); EasyDebounce.debounce('add_or_remove_plan_to_favorites', const Duration(seconds: 1), () async { try { await planRepository.addToFavorite(slug); @@ -98,9 +107,9 @@ class AboutPlanCubit extends Cubit { await reportFrom(e, st, this); log(e.toString()); showErrorToast('Произошла ошибка. Попробуйте ещё раз через некоторое время'); - if (index != null) { - planRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: currentPlan.isFavorite, index: index)); - } + planRepository.emitFavoriteStateToFeed( + FavoriteState(isFavorite: currentPlan.isFavorite, index: index ?? 0, slug: slug), + ); emit(state.copyWith(planModel: currentPlan, error: null)); } }); @@ -111,9 +120,9 @@ class AboutPlanCubit extends Cubit { if (currentPlan == null) return; emit(state.copyWith(planModel: currentPlan.copyWith(isFavorite: false))); - if (index != null) { - planRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: false, index: index)); - } + planRepository.emitFavoriteStateToFeed( + FavoriteState(isFavorite: false, index: index ?? 0, slug: slug), + ); EasyDebounce.debounce('add_or_remove_plan_to_favorites', const Duration(seconds: 1), () async { try { await planRepository.removeFromFavorite(slug); @@ -121,9 +130,9 @@ class AboutPlanCubit extends Cubit { await reportFrom(e, st, this); log(e.toString()); showErrorToast('Произошла ошибка. Попробуйте ещё раз через некоторое время'); - if (index != null) { - planRepository.emitFavoriteStateToFeed(FavoriteState(isFavorite: currentPlan.isFavorite, index: index)); - } + planRepository.emitFavoriteStateToFeed( + FavoriteState(isFavorite: currentPlan.isFavorite, index: index ?? 0, slug: slug), + ); emit(state.copyWith(planModel: currentPlan, error: null)); } }); diff --git a/lib/features/plans/repositories/plan_repository.dart b/lib/features/plans/repositories/plan_repository.dart index 67ea6003..9b6e485c 100644 --- a/lib/features/plans/repositories/plan_repository.dart +++ b/lib/features/plans/repositories/plan_repository.dart @@ -12,9 +12,9 @@ class PlanRepository { final _planLikeStateStreamController = StreamController.broadcast(); final _planFavoriteStateStreamController = StreamController.broadcast(); final _planCommentsStateStreamController = StreamController.broadcast(); - Stream get planLikeState => _planLikeStateStreamController.stream; - Stream get planFavoriteState => _planFavoriteStateStreamController.stream; - Stream get planCommentsState => _planCommentsStateStreamController.stream; + Stream get planLikeState => _planLikeStateStreamController.stream; + Stream get planFavoriteState => _planFavoriteStateStreamController.stream; + Stream get planCommentsState => _planCommentsStateStreamController.stream; Future getPlan(String slug) async { return planService.getPlan(slug); diff --git a/lib/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart b/lib/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart index a6370e48..1d7557ca 100644 --- a/lib/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart +++ b/lib/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart @@ -1,25 +1,197 @@ +import 'dart:async'; import 'dart:developer'; +import 'package:easy_debounce/easy_debounce.dart'; +import 'package:eatvio_app/core/error_reporting/report_from.dart'; +import 'package:eatvio_app/core/utils/toasts.dart'; +import 'package:eatvio_app/features/diets/repositories/diet_repository.dart'; +import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; +import 'package:eatvio_app/features/plans/repositories/plan_repository.dart'; import 'package:eatvio_app/features/plans/repositories/plans_repository.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_state.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:eatvio_app/core/error_reporting/report_from.dart'; class PlansCubit extends Cubit { final PlansRepository plansRepository; + final PlanRepository planRepository; + + static const Duration _debounceDuration = Duration(milliseconds: 200); + static const String _favoriteErrorMessage = 'Произошла ошибка. Попробуйте ещё раз через некоторое время'; + + late final StreamSubscription likesStateSubscription; + late final StreamSubscription favoriteStateSubscription; + late final StreamSubscription commentsStateSubscription; + + final Set _pendingDebounceTags = {}; PlansCubit({ required this.plansRepository, - }) : super(const PlansState()); + required this.planRepository, + }) : super(const PlansState()) { + likesStateSubscription = planRepository.planLikeState.listen(_changePlanLikeState); + favoriteStateSubscription = planRepository.planFavoriteState.listen(_changePlanFavoriteState); + commentsStateSubscription = planRepository.planCommentsState.listen(_changePlanCommentsState); + } + + @override + Future close() async { + for (final tag in _pendingDebounceTags) { + EasyDebounce.cancel(tag); + } + _pendingDebounceTags.clear(); + await likesStateSubscription.cancel(); + await favoriteStateSubscription.cancel(); + await commentsStateSubscription.cancel(); + await super.close(); + } Future getPlans(String slug) async { emit(const PlansState.loading()); try { - emit(PlansState.loaded(plansList: await plansRepository.getPlansBySlug(slug))); + final plansList = await plansRepository.getPlansBySlug(slug); + if (!isClosed) emit(PlansState.loaded(plansList: plansList)); } catch (e, st) { await reportFrom(e, st, this); log(e.toString()); - emit(PlansState.error(errorMessage: e.toString())); + if (!isClosed) emit(PlansState.error(errorMessage: e.toString())); } } + + Future likePlan(String slug) async { + final plan = _planBySlug(slug); + if (plan == null) return; + + final wasLikedByMe = plan.wasLikedByMe; + final totalLikes = plan.totalLikes; + + _updatePlanBySlug( + slug, + (plan) => plan.copyWith( + wasLikedByMe: !plan.wasLikedByMe, + totalLikes: plan.wasLikedByMe ? plan.totalLikes - 1 : plan.totalLikes + 1, + ), + ); + + _debounce('profile_like_plan_$slug', () async { + try { + await planRepository.likePlan(slug); + } catch (e, st) { + await reportFrom(e, st, this); + if (isClosed) return; + _updatePlanBySlug( + slug, + (plan) => plan.copyWith(wasLikedByMe: wasLikedByMe, totalLikes: totalLikes), + ); + } + }); + } + + Future addPlanToFavorite(String slug) => _changeFavorite(slug, true); + + Future removePlanFromFavorite(String slug) => _changeFavorite(slug, false); + + Future _changeFavorite(String slug, bool isFavorite) async { + final plan = _planBySlug(slug); + if (plan == null) return; + + final previousIsFavorite = plan.isFavorite; + + _updatePlanBySlug(slug, (plan) => plan.copyWith(isFavorite: isFavorite)); + + _debounce('profile_favorite_$slug', () async { + try { + if (isFavorite) { + await planRepository.addToFavorite(slug); + } else { + await planRepository.removeFromFavorite(slug); + } + } catch (e, st) { + await reportFrom(e, st, this); + if (isClosed) return; + _updatePlanBySlug(slug, (plan) => plan.copyWith(isFavorite: previousIsFavorite)); + showErrorToast(_favoriteErrorMessage); + } + }); + } + + void _changePlanLikeState(LikesState likesState) { + _updatePlan( + slug: likesState.slug, + index: likesState.index, + transform: (plan) => plan.copyWith( + totalLikes: likesState.totalLikes, + wasLikedByMe: likesState.wasLikedByMe, + ), + ); + } + + void _changePlanFavoriteState(FavoriteState favoriteState) { + _updatePlan( + slug: favoriteState.slug, + index: favoriteState.index, + transform: (plan) => plan.copyWith(isFavorite: favoriteState.isFavorite), + ); + } + + void _changePlanCommentsState(CommentsState commentsState) { + _updatePlan( + slug: commentsState.slug, + index: commentsState.index, + transform: (plan) => plan.copyWith(totalComments: commentsState.totalComments), + ); + } + + void _updatePlan({ + required String? slug, + required int index, + required PlanModel Function(PlanModel plan) transform, + }) { + if (slug != null) { + _updatePlanBySlug(slug, transform); + } else { + _updatePlanByIndex(index, transform); + } + } + + void _updatePlanBySlug(String slug, PlanModel Function(PlanModel plan) transform) { + final current = state; + if (current is! PlansStateLoaded || isClosed) return; + + final index = current.plansList.indexWhere((plan) => plan.slug == slug); + if (index == -1) return; + + _emitPlanAt(current, index, transform); + } + + void _updatePlanByIndex(int index, PlanModel Function(PlanModel plan) transform) { + final current = state; + if (current is! PlansStateLoaded || isClosed) return; + if (index < 0 || index >= current.plansList.length) return; + + _emitPlanAt(current, index, transform); + } + + void _emitPlanAt(PlansStateLoaded current, int index, PlanModel Function(PlanModel plan) transform) { + final plansList = [...current.plansList]; + plansList[index] = transform(plansList[index]); + emit(current.copyWith(plansList: plansList)); + } + + PlanModel? _planBySlug(String slug) { + final current = state; + if (current is! PlansStateLoaded) return null; + + for (final plan in current.plansList) { + if (plan.slug == slug) return plan; + } + return null; + } + + void _debounce(String tag, Future Function() action) { + _pendingDebounceTags.add(tag); + EasyDebounce.debounce(tag, _debounceDuration, () async { + _pendingDebounceTags.remove(tag); + await action(); + }); + } } diff --git a/lib/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart b/lib/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart index bd6bd761..46b7f06b 100644 --- a/lib/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart +++ b/lib/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart @@ -97,6 +97,7 @@ class ProfileCubit extends Cubit { void updateFeedBlogPostList(FeedBlogPostModel feedBlogPostModel, bool wasLikedByMe) { List feedBlogPostList = [...(state as ProfileStateLoaded).blogPosts]; final int index = feedBlogPostList.indexOf(feedBlogPostModel); + if (index == -1) return; feedBlogPostList[index] = feedBlogPostModel.copyWith( wasLikedByMe: wasLikedByMe, totalLikes: wasLikedByMe == false ? feedBlogPostList[index].totalLikes - 1 : feedBlogPostList[index].totalLikes + 1, diff --git a/lib/features/profile/presentation/pages/profile_screen.dart b/lib/features/profile/presentation/pages/profile_screen.dart index f1d771e2..f4b30801 100644 --- a/lib/features/profile/presentation/pages/profile_screen.dart +++ b/lib/features/profile/presentation/pages/profile_screen.dart @@ -331,6 +331,7 @@ class _ProfileScreenState extends State { } Scaffold _myProfileScreen(ProfileStateLoaded state) { + final consultantInfo = state.consultantInfo; return Scaffold( backgroundColor: Colors.grey.shade200, appBar: AppBar( @@ -360,7 +361,8 @@ class _ProfileScreenState extends State { crossAxisAlignment: CrossAxisAlignment.center, children: [ _header(state), - if (state.profile.roles.contains('consultant')) + if (state.profile.roles.contains('consultant') && + consultantInfo != null) Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -386,7 +388,7 @@ class _ProfileScreenState extends State { borderRadius: BorderRadius.circular(12), ), child: Text( - '${state.consultantInfo!.ratingPlace}-й в рейтинге', + '${consultantInfo.ratingPlace}-й в рейтинге', style: TextStyle( fontSize: 16, fontWeight: FontWeight.w600, @@ -396,11 +398,7 @@ class _ProfileScreenState extends State { ), ], ), - if (state - .consultantInfo! - .educationModel - .hasMedicalEducation == - 1) + if (consultantInfo.educationModel.hasMedicalEducation == 1) const Row( children: [ SizedBox(width: 16), @@ -451,6 +449,7 @@ class _ProfileScreenState extends State { if (!state.profile.roles.contains('consultant') || hidePlans) { return const SizedBox.shrink(); } + final profileSlug = state.profile.slug; return BlocBuilder( bloc: plansCubit, builder: (BuildContext context, PlansState state) { @@ -486,7 +485,15 @@ class _ProfileScreenState extends State { }); }, itemBuilder: (BuildContext context, int index) { - return PlanWidget(plan: state.plansList[index], index: index); + return PlanWidget( + plan: state.plansList[index], + index: index, + onLikeTap: (slug) => plansCubit.likePlan(slug), + onToggleFavorite: (slug, isFavorite) => isFavorite + ? plansCubit.removePlanFromFavorite(slug) + : plansCubit.addPlanToFavorite(slug), + onPlanChanged: () => plansCubit.getPlans(profileSlug), + ); }, ), const SizedBox(height: 8), @@ -895,10 +902,11 @@ class _ProfileScreenState extends State { } SingleChildRenderObjectWidget _socialLinks(ProfileStateLoaded state) { - if (!state.profile.roles.contains('consultant') && - state.consultantInfo != null) { + final consultantInfo = state.consultantInfo; + if (!state.profile.roles.contains('consultant') || consultantInfo == null) { return const SizedBox.shrink(); } + final educationModel = consultantInfo.educationModel; return Padding( padding: const EdgeInsets.symmetric(horizontal: 4) + @@ -913,47 +921,34 @@ class _ProfileScreenState extends State { _socialLinkButton( () { launchUrl( - Uri.parse( - state.consultantInfo!.educationModel.vkLink ?? '', - ), + Uri.parse(educationModel.vkLink ?? ''), mode: LaunchMode.externalApplication, ); }, 'assets/icons/vk.svg', - state.consultantInfo!.educationModel.vkLink!.isEmpty - ? true - : false, + educationModel.vkLink?.isEmpty ?? true, ), const SizedBox(width: 12), _socialLinkButton( () { launchUrl( - Uri.parse( - state.consultantInfo!.educationModel.tgLink ?? '', - ), + Uri.parse(educationModel.tgLink ?? ''), mode: LaunchMode.externalApplication, ); }, 'assets/icons/telegram.svg', - state.consultantInfo!.educationModel.tgLink!.isEmpty - ? true - : false, + educationModel.tgLink?.isEmpty ?? true, ), const SizedBox(width: 12), _socialLinkButton( () { launchUrl( - Uri.parse( - state.consultantInfo!.educationModel.personalSiteLink ?? - '', - ), + Uri.parse(educationModel.personalSiteLink ?? ''), mode: LaunchMode.externalApplication, ); }, 'assets/icons/web.svg', - state.consultantInfo!.educationModel.personalSiteLink!.isEmpty - ? true - : false, + educationModel.personalSiteLink?.isEmpty ?? true, ), ], ), diff --git a/lib/features/profile/presentation/widgets/profile_blog_post_widget.dart b/lib/features/profile/presentation/widgets/profile_blog_post_widget.dart index 0e266bdf..fe40e345 100644 --- a/lib/features/profile/presentation/widgets/profile_blog_post_widget.dart +++ b/lib/features/profile/presentation/widgets/profile_blog_post_widget.dart @@ -191,21 +191,24 @@ class _ProfileBlogPostWidgetState extends State { ? Colors.red.withValues(alpha: 0.8) : null, onTap: () async { + final nextLiked = !isLiked; setState(() { - isLiked = !isLiked; - isLiked ? totalLikes++ : totalLikes--; + isLiked = nextLiked; + nextLiked ? totalLikes++ : totalLikes--; }); - isLiked - ? await context.read().likePost( - post.id, - ) - : await context.read().unlikedPost( - post.id, - ); widget.profileCubit.updateFeedBlogPostList( post, - isLiked ? false : true, + nextLiked, ); + if (nextLiked) { + await context.read().likePost( + post.id, + ); + } else { + await context.read().unlikedPost( + post.id, + ); + } }, ), const SizedBox(width: 8), diff --git a/test/features/feed/presentation/bloc/plans_cubit/plans_cubit_slug_sync_test.dart b/test/features/feed/presentation/bloc/plans_cubit/plans_cubit_slug_sync_test.dart new file mode 100644 index 00000000..e2ff78a3 --- /dev/null +++ b/test/features/feed/presentation/bloc/plans_cubit/plans_cubit_slug_sync_test.dart @@ -0,0 +1,194 @@ +import 'package:easy_debounce/easy_debounce.dart'; +import 'package:eatvio_app/core/models/pagination_model.dart'; +import 'package:eatvio_app/features/diets/repositories/diet_repository.dart'; +import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; +import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; +import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart'; +import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; +import 'package:eatvio_app/features/plans/repositories/plan_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:rxdart/rxdart.dart'; + +import 'plans_cubit_slug_sync_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec(), MockSpec()]) +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('feed PlansCubit — slug-based stream sync', () { + PlanModel plan({required String slug, int totalLikes = 10}) { + return PlanModel( + id: slug.hashCode, + slug: slug, + name: slug, + image: 'https://example.com/image.jpg', + duration: 7, + state: 'active', + type: const PlanType( + fit: true, + slim: false, + behavior: false, + wellness: false, + ), + details: 'details', + packetsCount: 1, + minPriceOfOptions: 1000.0, + maxPriceOfOptions: 2000.0, + author: const Author( + authorSlug: 'author', + authorName: 'Author Name', + authorProfileIcon: 'https://example.com/icon.jpg', + authorIsMe: false, + isEntitySubscribedByMe: null, + authorPlaceInRating: null, + ), + totalLikes: totalLikes, + totalViews: 100, + totalComments: 5, + wasLikedByMe: false, + isFavorite: false, + ); + } + + PlanPaginationModel pagination(List plans) { + return PlanPaginationModel( + data: plans, + links: const Links( + first: 'https://example.com?page=1', + last: 'https://example.com?page=1', + prev: null, + next: null, + ), + meta: Meta( + currentPage: 1, + from: 1, + lastPage: 1, + links: const [], + perPage: 10, + to: plans.length, + total: plans.length, + totalMinPrice: 1000, + totalMaxPrice: 2000, + ), + ); + } + + late MockFeedRepository feedRepository; + late MockPlanRepository planRepository; + late BehaviorSubject likeState; + late BehaviorSubject favoriteState; + late BehaviorSubject commentsState; + late PlansCubit cubit; + + setUp(() async { + feedRepository = MockFeedRepository(); + planRepository = MockPlanRepository(); + likeState = BehaviorSubject(); + favoriteState = BehaviorSubject(); + commentsState = BehaviorSubject(); + + when(planRepository.planLikeState).thenAnswer((_) => likeState); + when(planRepository.planFavoriteState).thenAnswer((_) => favoriteState); + when(planRepository.planCommentsState).thenAnswer((_) => commentsState); + + when( + feedRepository.getPlans( + query: anyNamed('query'), + types: anyNamed('types'), + duration: anyNamed('duration'), + minPrice: anyNamed('minPrice'), + maxPrice: anyNamed('maxPrice'), + ), + ).thenAnswer( + (_) async => pagination([ + plan(slug: 'plan-a'), + plan(slug: 'plan-b'), + ]), + ); + + cubit = PlansCubit( + feedRepository: feedRepository, + planRepository: planRepository, + ); + await cubit.loadPlans(); + expect(cubit.state.plans.length, 2); + }); + + tearDown(() async { + EasyDebounce.cancel('loadPlans'); + EasyDebounce.cancel('like_plan'); + EasyDebounce.cancel('add_or_remove_plan_from_favorite'); + if (!cubit.isClosed) { + await cubit.close(); + } + await likeState.close(); + await favoriteState.close(); + await commentsState.close(); + }); + + test('a like event with a slug updates the matching plan, not the index', () async { + likeState.add( + const LikesState( + slug: 'plan-b', + index: 0, + totalLikes: 42, + wasLikedByMe: true, + ), + ); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(cubit.state.plans[0].wasLikedByMe, isFalse); + expect(cubit.state.plans[0].totalLikes, 10); + expect(cubit.state.plans[1].wasLikedByMe, isTrue); + expect(cubit.state.plans[1].totalLikes, 42); + }); + + test('a like event with an unknown slug is a no-op', () async { + final before = cubit.state.plans; + + likeState.add( + const LikesState( + slug: 'unknown-plan', + index: 0, + totalLikes: 42, + wasLikedByMe: true, + ), + ); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(cubit.state.plans, before); + }); + + test('a legacy like event without a slug keeps index behaviour', () async { + likeState.add( + const LikesState(index: 1, totalLikes: 42, wasLikedByMe: true), + ); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(cubit.state.plans[1].wasLikedByMe, isTrue); + expect(cubit.state.plans[1].totalLikes, 42); + }); + + test('a favorite event with a slug updates the matching plan', () async { + favoriteState.add( + const FavoriteState(slug: 'plan-b', index: 0, isFavorite: true), + ); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(cubit.state.plans[0].isFavorite, isFalse); + expect(cubit.state.plans[1].isFavorite, isTrue); + }); + + test('a comments event with a slug updates the matching plan', () async { + commentsState.add( + const CommentsState(slug: 'plan-b', index: 0, totalComments: 7), + ); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(cubit.state.plans[0].totalComments, isNot(7)); + expect(cubit.state.plans[1].totalComments, 7); + }); + }); +} \ No newline at end of file diff --git a/test/features/feed/presentation/bloc/plans_cubit/plans_cubit_sync_guard_test.dart b/test/features/feed/presentation/bloc/plans_cubit/plans_cubit_sync_guard_test.dart new file mode 100644 index 00000000..64bbb975 --- /dev/null +++ b/test/features/feed/presentation/bloc/plans_cubit/plans_cubit_sync_guard_test.dart @@ -0,0 +1,172 @@ +import 'dart:async'; + +import 'package:easy_debounce/easy_debounce.dart'; +import 'package:eatvio_app/core/models/pagination_model.dart'; +import 'package:eatvio_app/features/diets/repositories/diet_repository.dart'; +import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; +import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; +import 'package:eatvio_app/features/feed/presentation/bloc/plans_cubit/plans_cubit.dart'; +import 'package:eatvio_app/features/feed/repositories/feed_repository.dart'; +import 'package:eatvio_app/features/plans/repositories/plan_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:rxdart/rxdart.dart'; + +import 'plans_cubit_sync_guard_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec(), MockSpec()]) +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('feed PlansCubit — index bounds guard', () { + const testPlan = PlanModel( + id: 1, + slug: 'test-plan', + name: 'Test Plan', + image: 'https://example.com/image.jpg', + duration: 7, + state: 'active', + type: PlanType(fit: true, slim: false, behavior: false, wellness: false), + details: 'Test details', + packetsCount: 3, + minPriceOfOptions: 1000.0, + maxPriceOfOptions: 2000.0, + author: Author( + authorSlug: 'author', + authorName: 'Author Name', + authorProfileIcon: 'https://example.com/icon.jpg', + authorIsMe: false, + isEntitySubscribedByMe: null, + authorPlaceInRating: null, + ), + totalLikes: 10, + totalViews: 100, + totalComments: 5, + wasLikedByMe: false, + isFavorite: false, + ); + + const plansPagination = PlanPaginationModel( + data: [testPlan], + links: Links( + first: 'https://example.com?page=1', + last: 'https://example.com?page=1', + prev: null, + next: null, + ), + meta: Meta( + currentPage: 1, + from: 1, + lastPage: 1, + links: [], + perPage: 10, + to: 1, + total: 1, + totalMinPrice: 1000, + totalMaxPrice: 2000, + ), + ); + + late MockFeedRepository feedRepository; + late MockPlanRepository planRepository; + late BehaviorSubject likeState; + late BehaviorSubject favoriteState; + late BehaviorSubject commentsState; + + setUp(() { + feedRepository = MockFeedRepository(); + planRepository = MockPlanRepository(); + likeState = BehaviorSubject(); + favoriteState = BehaviorSubject(); + commentsState = BehaviorSubject(); + + when(planRepository.planLikeState).thenAnswer((_) => likeState); + when(planRepository.planFavoriteState).thenAnswer((_) => favoriteState); + when(planRepository.planCommentsState).thenAnswer((_) => commentsState); + + when( + feedRepository.getPlans( + query: anyNamed('query'), + types: anyNamed('types'), + duration: anyNamed('duration'), + minPrice: anyNamed('minPrice'), + maxPrice: anyNamed('maxPrice'), + ), + ).thenAnswer((_) async => plansPagination); + }); + + tearDown(() async { + EasyDebounce.cancel('loadPlans'); + EasyDebounce.cancel('like_plan'); + EasyDebounce.cancel('add_or_remove_plan_from_favorite'); + await likeState.close(); + await favoriteState.close(); + await commentsState.close(); + }); + + /// Runs [body] in its own error zone so an unhandled stream-listener error + /// is captured instead of failing the test at teardown. + Future> errorsFrom(Future Function() body) async { + final errors = []; + final done = Completer(); + runZonedGuarded( + () async { + try { + await body(); + } finally { + done.complete(); + } + }, + (error, stackTrace) => errors.add(error), + ); + await done.future; + return errors; + } + + Future loadedCubit() async { + final cubit = PlansCubit( + feedRepository: feedRepository, + planRepository: planRepository, + ); + await cubit.loadPlans(); + expect(cubit.state.plans.length, 1); + return cubit; + } + + test('an out-of-range like event is ignored instead of throwing', () async { + final errors = await errorsFrom(() async { + final cubit = await loadedCubit(); + likeState.add( + const LikesState(index: 5, totalLikes: 99, wasLikedByMe: true), + ); + await Future.delayed(const Duration(milliseconds: 100)); + await cubit.close(); + }); + + expect(errors, isEmpty); + }); + + test('an out-of-range favorite event is ignored instead of throwing', () async { + final errors = await errorsFrom(() async { + final cubit = await loadedCubit(); + favoriteState.add(const FavoriteState(index: 5, isFavorite: true)); + await Future.delayed(const Duration(milliseconds: 100)); + await cubit.close(); + }); + + expect(errors, isEmpty); + }); + + test('an out-of-range comments event is ignored instead of throwing', () async { + final errors = await errorsFrom(() async { + final cubit = await loadedCubit(); + commentsState.add(const CommentsState(index: 5, totalComments: 99)); + await Future.delayed(const Duration(milliseconds: 100)); + await cubit.close(); + }); + + expect(errors, isEmpty); + }); + }); +} \ No newline at end of file diff --git a/test/features/profile/presentation/bloc/plans_cubit/plans_cubit_test.dart b/test/features/profile/presentation/bloc/plans_cubit/plans_cubit_test.dart index d76b25df..5042ba76 100644 --- a/test/features/profile/presentation/bloc/plans_cubit/plans_cubit_test.dart +++ b/test/features/profile/presentation/bloc/plans_cubit/plans_cubit_test.dart @@ -1,5 +1,10 @@ +import 'dart:async'; + +import 'package:eatvio_app/core/error_reporting/error_reporter.dart'; +import 'package:eatvio_app/core/locator_service.dart'; import 'package:eatvio_app/features/feed/models/diets_pagination_model.dart'; import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; +import 'package:eatvio_app/features/plans/repositories/plan_repository.dart'; import 'package:eatvio_app/features/plans/repositories/plans_repository.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_state.dart'; @@ -9,14 +14,34 @@ import 'package:mockito/mockito.dart'; import 'plans_cubit_test.mocks.dart'; -@GenerateNiceMocks([MockSpec()]) +class _RecordingErrorReporter implements ErrorReporter { + final List errors = []; + + @override + Future report( + Object error, + StackTrace? stackTrace, { + String? origin, + Map? extras, + }) async { + errors.add(error); + } +} + +@GenerateNiceMocks([MockSpec(), MockSpec()]) void main() { group('PlansCubit', () { PlansCubit? cubit; late MockPlansRepository mockRepository; + late MockPlanRepository mockPlanRepository; - setUp(() { + setUp(() async { + await sl.reset(); mockRepository = MockPlansRepository(); + mockPlanRepository = MockPlanRepository(); + when(mockPlanRepository.planLikeState).thenAnswer((_) => const Stream.empty()); + when(mockPlanRepository.planFavoriteState).thenAnswer((_) => const Stream.empty()); + when(mockPlanRepository.planCommentsState).thenAnswer((_) => const Stream.empty()); }); tearDown(() async { @@ -24,16 +49,23 @@ void main() { await cubit!.close(); cubit = null; } + await sl.reset(); }); test('начальное состояние - пустое', () { - cubit = PlansCubit(plansRepository: mockRepository); + cubit = PlansCubit( + plansRepository: mockRepository, + planRepository: mockPlanRepository, + ); expect(cubit!.state, isA()); }); test('getPlans - успешная загрузка планов', () async { - cubit = PlansCubit(plansRepository: mockRepository); + cubit = PlansCubit( + plansRepository: mockRepository, + planRepository: mockPlanRepository, + ); final testPlans = [ const PlanModel( @@ -75,7 +107,10 @@ void main() { }); test('getPlans - обработка ошибки', () async { - cubit = PlansCubit(plansRepository: mockRepository); + cubit = PlansCubit( + plansRepository: mockRepository, + planRepository: mockPlanRepository, + ); when(mockRepository.getPlansBySlug(any)) .thenThrow(Exception('Ошибка загрузки')); @@ -84,6 +119,33 @@ void main() { expect(cubit!.state, isA()); }); + + test('getPlans - close during request does not emit loaded or report an error', () async { + final reporter = _RecordingErrorReporter(); + sl.registerSingleton(reporter); + + cubit = PlansCubit( + plansRepository: mockRepository, + planRepository: mockPlanRepository, + ); + + final response = Completer>(); + when(mockRepository.getPlansBySlug('test-user')) + .thenAnswer((_) => response.future); + + final emitted = []; + final subscription = cubit!.stream.listen(emitted.add); + + final request = cubit!.getPlans('test-user'); + await cubit!.close(); + response.complete(const []); + await request; + await subscription.cancel(); + + expect(emitted.whereType(), isEmpty); + expect(emitted.whereType(), isEmpty); + expect(reporter.errors, isEmpty); + }); }); } diff --git a/test/features/profile/presentation/bloc/plans_cubit/profile_plans_cubit_like_test.dart b/test/features/profile/presentation/bloc/plans_cubit/profile_plans_cubit_like_test.dart new file mode 100644 index 00000000..8af8345d --- /dev/null +++ b/test/features/profile/presentation/bloc/plans_cubit/profile_plans_cubit_like_test.dart @@ -0,0 +1,363 @@ +import 'dart:async'; + +import 'package:easy_debounce/easy_debounce.dart'; +import 'package:eatvio_app/core/error_reporting/error_reporter.dart'; +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/features/diets/repositories/diet_repository.dart'; +import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; +import 'package:eatvio_app/features/plans/repositories/plan_repository.dart'; +import 'package:eatvio_app/features/plans/repositories/plans_repository.dart'; +import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart'; +import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_state.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:rxdart/rxdart.dart'; + +import '../../../../../fixtures/fixture_reader.dart'; +import 'profile_plans_cubit_like_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec(), MockSpec()]) +class _RecordingReporter implements ErrorReporter { + final List errors = []; + Object? lastError; + StackTrace? lastStack; + String? lastOrigin; + + @override + Future report( + Object error, + StackTrace? stackTrace, { + String? origin, + Map? extras, + }) async { + errors.add(error); + lastError = error; + lastStack = stackTrace; + lastOrigin = origin; + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + group('profile PlansCubit — like/favorite', () { + late MockPlansRepository plansRepository; + late MockPlanRepository planRepository; + late PlansCubit cubit; + late _RecordingReporter reporter; + late List toastCalls; + + const slugA = 'plan-a'; + const slugB = 'plan-b'; + + PlanModel plan({ + String slug = slugA, + bool wasLikedByMe = false, + bool isFavorite = false, + int totalLikes = 10, + }) { + return PlanModel.fromJson( + FixtureReader.readAsMap('plans/plan_response.json'), + ).copyWith( + slug: slug, + state: 'active', + wasLikedByMe: wasLikedByMe, + isFavorite: isFavorite, + totalLikes: totalLikes, + ); + } + + setUpAll(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('PonnamKarthik/fluttertoast'), + (MethodCall methodCall) async { + toastCalls.add(methodCall); + return null; + }, + ); + }); + + setUp(() async { + await sl.reset(); + reporter = _RecordingReporter(); + sl.registerSingleton(reporter); + toastCalls = []; + + plansRepository = MockPlansRepository(); + planRepository = MockPlanRepository(); + + when( + planRepository.planLikeState, + ).thenAnswer((_) => BehaviorSubject()); + when( + planRepository.planFavoriteState, + ).thenAnswer((_) => BehaviorSubject()); + when( + planRepository.planCommentsState, + ).thenAnswer((_) => BehaviorSubject()); + + cubit = PlansCubit( + plansRepository: plansRepository, + planRepository: planRepository, + ); + }); + + tearDown(() async { + EasyDebounce.cancel('profile_like_plan_$slugA'); + EasyDebounce.cancel('profile_like_plan_$slugB'); + EasyDebounce.cancel('profile_favorite_$slugA'); + EasyDebounce.cancel('profile_favorite_$slugB'); + if (!cubit.isClosed) { + await cubit.close(); + } + await sl.reset(); + }); + + Future load(List plans) async { + when(plansRepository.getPlansBySlug(any)).thenAnswer((_) async => plans); + await cubit.getPlans('consultant'); + expect(cubit.state, isA()); + } + + PlansStateLoaded loaded() => cubit.state as PlansStateLoaded; + + test( + 'likePlan adds a like optimistically and calls the repository once', + () async { + await load([plan()]); + + await cubit.likePlan(slugA); + + expect(loaded().plansList.single.wasLikedByMe, isTrue); + expect(loaded().plansList.single.totalLikes, 11); + + await Future.delayed(const Duration(milliseconds: 1200)); + verify(planRepository.likePlan(slugA)).called(1); + }, + ); + + test('likePlan removes an existing like optimistically', () async { + await load([plan(wasLikedByMe: true, totalLikes: 10)]); + + await cubit.likePlan(slugA); + + expect(loaded().plansList.single.wasLikedByMe, isFalse); + expect(loaded().plansList.single.totalLikes, 9); + + await Future.delayed(const Duration(milliseconds: 1200)); + verify(planRepository.likePlan(slugA)).called(1); + }); + + test( + 'likePlan rolls back the optimistic change when the repository fails', + () async { + when(planRepository.likePlan(any)).thenThrow(Exception('network')); + await load([plan()]); + + await cubit.likePlan(slugA); + expect(loaded().plansList.single.wasLikedByMe, isTrue); + + await Future.delayed(const Duration(milliseconds: 1200)); + + expect(loaded().plansList.single.wasLikedByMe, isFalse); + expect(loaded().plansList.single.totalLikes, 10); + verify(planRepository.likePlan(slugA)).called(1); + }, + ); + + test( + 'likePlan does nothing when the slug is not in the loaded list', + () async { + await load([plan()]); + final before = loaded().plansList; + + await cubit.likePlan('missing-plan'); + await Future.delayed(const Duration(milliseconds: 1200)); + + expect(loaded().plansList, before); + verifyNever(planRepository.likePlan(any)); + }, + ); + + test('likePlan does nothing when state is not loaded', () async { + await cubit.likePlan(slugA); + await Future.delayed(const Duration(milliseconds: 1200)); + + expect(cubit.state, isNot(isA())); + verifyNever(planRepository.likePlan(any)); + }); + + test( + 'likePlan debounces repeated taps on the same slug into one request', + () async { + await load([plan()]); + + await cubit.likePlan(slugA); + await cubit.likePlan(slugA); + await Future.delayed(const Duration(milliseconds: 1200)); + + verify(planRepository.likePlan(slugA)).called(1); + }, + ); + + test('likePlan keeps a separate debounce per slug', () async { + await load([plan(slug: slugA), plan(slug: slugB)]); + + await cubit.likePlan(slugA); + await cubit.likePlan(slugB); + await Future.delayed(const Duration(milliseconds: 1200)); + + verify(planRepository.likePlan(slugA)).called(1); + verify(planRepository.likePlan(slugB)).called(1); + }); + + test( + 'addPlanToFavorite sets favorite optimistically and calls the repository', + () async { + await load([plan()]); + + await cubit.addPlanToFavorite(slugA); + + expect(loaded().plansList.single.isFavorite, isTrue); + + await Future.delayed(const Duration(milliseconds: 1200)); + verify(planRepository.addToFavorite(slugA)).called(1); + }, + ); + + test('addPlanToFavorite rolls back when the repository fails', () async { + when(planRepository.addToFavorite(any)).thenThrow(Exception('network')); + await load([plan()]); + + await cubit.addPlanToFavorite(slugA); + expect(loaded().plansList.single.isFavorite, isTrue); + + await Future.delayed(const Duration(milliseconds: 1200)); + + expect(loaded().plansList.single.isFavorite, isFalse); + verify(planRepository.addToFavorite(slugA)).called(1); + }); + + test( + 'removePlanFromFavorite clears favorite optimistically and calls the repository', + () async { + await load([plan(isFavorite: true)]); + + await cubit.removePlanFromFavorite(slugA); + + expect(loaded().plansList.single.isFavorite, isFalse); + + await Future.delayed(const Duration(milliseconds: 1200)); + verify(planRepository.removeFromFavorite(slugA)).called(1); + }, + ); + + test( + 'favorite actions do nothing when the slug is not in the loaded list', + () async { + await load([plan()]); + final before = loaded().plansList; + + await cubit.addPlanToFavorite('missing-plan'); + await cubit.removePlanFromFavorite('missing-plan'); + await Future.delayed(const Duration(milliseconds: 1200)); + + expect(loaded().plansList, before); + verifyNever(planRepository.addToFavorite(any)); + verifyNever(planRepository.removeFromFavorite(any)); + }, + ); + + test('close cancels a pending like request', () async { + await load([plan()]); + + await cubit.likePlan(slugA); + await cubit.close(); + await Future.delayed(const Duration(milliseconds: 1200)); + + verifyNever(planRepository.likePlan(any)); + }); + + test('a debounced failure after close does not emit or throw', () async { + when(planRepository.likePlan(any)).thenAnswer((_) async { + await Future.delayed(const Duration(milliseconds: 50)); + throw Exception('network'); + }); + await load([plan()]); + + await cubit.likePlan(slugA); + await Future.delayed(const Duration(milliseconds: 300)); + await cubit.close(); + await Future.delayed(const Duration(milliseconds: 300)); + + expect(cubit.isClosed, isTrue); + }); + + test( + 'a like that fails after close neither emits after close nor leaks a zone error', + () async { + await load([plan()]); + + final zoneErrors = []; + + await runZonedGuarded(() async { + final pending = Completer(); + when(planRepository.likePlan(any)).thenAnswer((_) => pending.future); + + await cubit.likePlan(slugA); + await Future.delayed(const Duration(milliseconds: 250)); + verify(planRepository.likePlan(slugA)).called(1); + await cubit.close(); + pending.completeError(Exception('network')); + await Future.delayed(const Duration(milliseconds: 100)); + }, (error, stackTrace) { + zoneErrors.add(error); + }); + + expect(cubit.isClosed, isTrue); + expect( + zoneErrors.whereType().where( + (error) => error.message.contains('Cannot emit new states after calling close'), + ), + isEmpty, + ); + expect(zoneErrors, isEmpty, reason: 'errors in zone: $zoneErrors'); + }, + ); + + test( + 'addPlanToFavorite rolls back and shows an error toast when the repository fails', + () async { + when(planRepository.addToFavorite(any)).thenThrow(Exception('network')); + await load([plan()]); + + await cubit.addPlanToFavorite(slugA); + await Future.delayed(const Duration(milliseconds: 1200)); + + expect(loaded().plansList.single.isFavorite, isFalse); + + final showToastCalls = toastCalls.where((call) => call.method == 'showToast').toList(); + expect(showToastCalls, isNotEmpty); + final arguments = showToastCalls.single.arguments as Map; + expect(arguments['msg'], contains('Произошла ошибка')); + }, + ); + + test('likePlan reports the failure through ErrorReporter', () async { + final error = Exception('network'); + when(planRepository.likePlan(any)).thenThrow(error); + await load([plan()]); + + await cubit.likePlan(slugA); + await Future.delayed(const Duration(milliseconds: 1200)); + + expect(reporter.errors, isNotEmpty); + expect(reporter.lastError, same(error)); + expect(reporter.lastOrigin, 'PlansCubit'); + expect(reporter.lastOrigin, isNotEmpty); + }); + }); +} diff --git a/test/features/profile/presentation/bloc/plans_cubit/profile_plans_cubit_slug_sync_test.dart b/test/features/profile/presentation/bloc/plans_cubit/profile_plans_cubit_slug_sync_test.dart new file mode 100644 index 00000000..6dde286d --- /dev/null +++ b/test/features/profile/presentation/bloc/plans_cubit/profile_plans_cubit_slug_sync_test.dart @@ -0,0 +1,127 @@ +import 'package:easy_debounce/easy_debounce.dart'; +import 'package:eatvio_app/features/diets/repositories/diet_repository.dart'; +import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; +import 'package:eatvio_app/features/plans/repositories/plan_repository.dart'; +import 'package:eatvio_app/features/plans/repositories/plans_repository.dart'; +import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart'; +import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_state.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:rxdart/rxdart.dart'; + +import '../../../../../fixtures/fixture_reader.dart'; +import 'profile_plans_cubit_slug_sync_test.mocks.dart'; + +@GenerateNiceMocks([MockSpec(), MockSpec()]) +void main() { + group('profile PlansCubit — slug-based stream sync', () { + late MockPlansRepository plansRepository; + late MockPlanRepository planRepository; + late BehaviorSubject likeState; + late BehaviorSubject favoriteState; + late BehaviorSubject commentsState; + late PlansCubit cubit; + + PlanModel plan({required String slug, int totalLikes = 10}) { + return PlanModel.fromJson( + FixtureReader.readAsMap('plans/plan_response.json'), + ).copyWith( + slug: slug, + state: 'active', + wasLikedByMe: false, + isFavorite: false, + totalLikes: totalLikes, + ); + } + + setUp(() async { + plansRepository = MockPlansRepository(); + planRepository = MockPlanRepository(); + likeState = BehaviorSubject(); + favoriteState = BehaviorSubject(); + commentsState = BehaviorSubject(); + + when(planRepository.planLikeState).thenAnswer((_) => likeState); + when(planRepository.planFavoriteState).thenAnswer((_) => favoriteState); + when(planRepository.planCommentsState).thenAnswer((_) => commentsState); + + cubit = PlansCubit( + plansRepository: plansRepository, + planRepository: planRepository, + ); + + when( + plansRepository.getPlansBySlug(any), + ).thenAnswer((_) async => [plan(slug: 'plan-a'), plan(slug: 'plan-b')]); + await cubit.getPlans('consultant'); + expect(cubit.state, isA()); + }); + + tearDown(() async { + EasyDebounce.cancel('profile_like_plan_plan-a'); + EasyDebounce.cancel('profile_like_plan_plan-b'); + if (!cubit.isClosed) { + await cubit.close(); + } + await likeState.close(); + await favoriteState.close(); + await commentsState.close(); + }); + + PlansStateLoaded loaded() => cubit.state as PlansStateLoaded; + + test('a like event with a slug updates only the matching plan', () async { + likeState.add( + const LikesState( + slug: 'plan-b', + totalLikes: 42, + wasLikedByMe: true, + index: 0, + ), + ); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(loaded().plansList[0].wasLikedByMe, isFalse); + expect(loaded().plansList[0].totalLikes, 10); + expect(loaded().plansList[1].wasLikedByMe, isTrue); + expect(loaded().plansList[1].totalLikes, 42); + }); + + test('a like event with an unknown slug is a no-op', () async { + final before = loaded().plansList; + + likeState.add( + const LikesState( + slug: 'unknown-plan', + totalLikes: 42, + wasLikedByMe: true, + index: 0, + ), + ); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(loaded().plansList, before); + }); + + test('a favorite event with a slug updates only the matching plan', () async { + favoriteState.add( + const FavoriteState(slug: 'plan-b', isFavorite: true, index: 0), + ); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(loaded().plansList[0].isFavorite, isFalse); + expect(loaded().plansList[1].isFavorite, isTrue); + }); + + test('a comments event with a slug updates only the matching plan', () async { + commentsState.add( + const CommentsState(slug: 'plan-b', totalComments: 7, index: 0), + ); + await Future.delayed(const Duration(milliseconds: 100)); + + expect(loaded().plansList[0].totalComments, isNot(7)); + expect(loaded().plansList[1].totalComments, 7); + }); + }); +} \ No newline at end of file diff --git a/test/features/profile/presentation/bloc/profile_cubit/profile_cubit_update_feed_regression_test.dart b/test/features/profile/presentation/bloc/profile_cubit/profile_cubit_update_feed_regression_test.dart new file mode 100644 index 00000000..8a5b4ccc --- /dev/null +++ b/test/features/profile/presentation/bloc/profile_cubit/profile_cubit_update_feed_regression_test.dart @@ -0,0 +1,133 @@ +import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/models/consultant_cert_photo_model.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart'; +import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; +import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_state.dart'; +import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; + +import '../../../../../fixtures/feed_fixtures.dart'; +import 'profile_cubit_update_feed_regression_test.mocks.dart'; + +@GenerateNiceMocks([ + MockSpec(), + MockSpec(), + MockSpec(), +]) +void main() { + group('ProfileCubit.updateFeedBlogPostList — regression #700', () { + late ProfileCubit cubit; + + const profile = ProfileModel( + id: 1, + name: 'Consultant', + email: 'c@e.com', + phoneConfirmationState: 'confirmed', + slug: 'consultant', + isPublicProfile: true, + isBlockedByMe: false, + isBlockedByAuthor: false, + isBlockedByUser: false, + isEntitySubscribedByMe: false, + profilePhotoUrl: '', + roles: ['consultant'], + badges: [], + subscriptions: [], + subscribers: [], + ); + + const details = ProfileDetailsModel( + firstName: 'Test', + lastName: 'User', + birthdate: '1990-01-01', + gender: 'male', + country: 'Russia', + city: 'Moscow', + lang: 'ru', + weight: 70.0, + height: 175, + chestCircumference: 100, + waistCircumference: 80, + hipCircumference: 90, + bloodPressureUp: 120, + bloodPressureDown: 80, + hasHypo: false, + hasHyper: false, + aboutAlergy: '', + aboutTakingPils: '', + aboutSportHobbies: '', + favoriteFoods: '', + unfavoriteFoods: '', + additionalInfo: '', + isMoodFillable: true, + isBedtimeFillable: true, + activityCoefficient: 1.5, + ); + + const consultantInfo = ConsultationRequestModel( + ratingPlace: 3, + educationModel: EducationModel( + hasMedicalEducation: 1, + completedCourses: null, + requestState: ModerationStatus.approved, + ), + photos: [], + ); + + const certPhotos = [ + ConsultantCertPhotoModel( + id: 7, + group: ConsultantCertPhotoModel.visibleGroup, + originalName: 'cert.jpg', + path: 'cert.jpg', + size: 100, + url: 'https://example.com/cert.jpg', + ), + ]; + + setUp(() { + cubit = ProfileCubit( + profileRepository: MockProfileRepository(), + chatRepository: MockChatRepository(), + consultantRepository: MockConsultantRepository(), + ); + }); + + tearDown(() async { + if (!cubit.isClosed) { + await cubit.close(); + } + }); + + test('preserves consultantInfo, certPhotos and isMyProfile on like emit', () { + final post = FeedFixtures.feedBlogPostModel().copyWith( + wasLikedByMe: false, + totalLikes: 10, + ); + cubit.emit( + ProfileState.loaded( + profile: profile, + profileDetails: details, + blogPosts: [post], + isMyProfile: true, + certPhotos: certPhotos, + consultantInfo: consultantInfo, + ), + ); + + cubit.updateFeedBlogPostList(post, true); + + final state = cubit.state as ProfileStateLoaded; + expect(state.isMyProfile, isTrue); + expect(state.consultantInfo, consultantInfo); + expect(state.certPhotos, certPhotos); + expect(state.profile, profile); + expect(state.profileDetails, details); + expect(state.blogPosts.single.wasLikedByMe, isTrue); + expect(state.blogPosts.single.totalLikes, 11); + }); + }); +} \ No newline at end of file diff --git a/test/features/profile/presentation/pages/profile_screen_consultant_null_links_test.dart b/test/features/profile/presentation/pages/profile_screen_consultant_null_links_test.dart new file mode 100644 index 00000000..6ff0ced0 --- /dev/null +++ b/test/features/profile/presentation/pages/profile_screen_consultant_null_links_test.dart @@ -0,0 +1,211 @@ +import 'package:eatvio_app/core/app_config.dart'; +import 'package:eatvio_app/core/app_initializer.dart'; +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart'; +import 'package:eatvio_app/features/insights/repositories/insights_repository.dart'; +import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart' + as profile_plans; +import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; +import 'package:eatvio_app/features/profile/presentation/pages/profile_screen.dart'; +import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:eatvio_app/features/plans/repositories/plan_repository.dart'; +import 'package:eatvio_app/features/plans/repositories/plans_repository.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:network_image_mock/network_image_mock.dart'; + +import '../../../../fixtures/doubles/insights_doubles.dart'; +import 'profile_screen_consultant_null_links_test.mocks.dart'; + +@GenerateNiceMocks([ + MockSpec(), + MockSpec(), + MockSpec(), + MockSpec(), + MockSpec(), +]) +void main() { + group('ProfileScreen — consultant without social links', () { + late MockProfileRepository profileRepository; + late MockChatRepository chatRepository; + late MockConsultantRepository consultantRepository; + late MockPlansRepository plansRepository; + late MockPlanRepository planRepository; + + setUpAll(() async { + dotenv.loadFromString( + envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost', + ); + }); + + setUp(() async { + await sl.reset(); + sl.registerLazySingleton( + () => + AppConfig(buildType: AppBuildType.tests) + ..setBaseUrl('http://localhost'), + ); + + profileRepository = MockProfileRepository(); + chatRepository = MockChatRepository(); + consultantRepository = MockConsultantRepository(); + plansRepository = MockPlansRepository(); + planRepository = MockPlanRepository(); + + when( + planRepository.planLikeState, + ).thenAnswer((_) => const Stream.empty()); + when( + planRepository.planFavoriteState, + ).thenAnswer((_) => const Stream.empty()); + when( + planRepository.planCommentsState, + ).thenAnswer((_) => const Stream.empty()); + + sl.registerLazySingleton(() => profileRepository); + sl.registerLazySingleton( + () => FakeInsightsRepository(), + ); + sl.registerLazySingleton(() => chatRepository); + sl.registerLazySingleton( + () => consultantRepository, + ); + sl.registerLazySingleton(() => plansRepository); + sl.registerLazySingleton(() => planRepository); + + sl.registerFactory( + () => ProfileCubit( + profileRepository: sl(), + chatRepository: sl(), + consultantRepository: sl(), + ), + ); + sl.registerFactory( + () => profile_plans.PlansCubit( + plansRepository: sl(), + planRepository: sl(), + ), + ); + }); + + tearDown(() async { + await sl.reset(); + }); + + Widget wrap(Widget child) { + return MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [ + S.delegate, + ...GlobalMaterialLocalizations.delegates, + ], + supportedLocales: const [Locale('ru')], + home: Scaffold(body: child), + ); + } + + ProfileModel profileOf(String slug, {List roles = const []}) { + return ProfileModel( + id: 1, + name: 'Test User', + email: 'test@example.com', + phoneConfirmationState: 'confirmed', + slug: slug, + isPublicProfile: true, + isBlockedByMe: false, + isBlockedByAuthor: false, + isBlockedByUser: false, + isEntitySubscribedByMe: false, + profilePhotoUrl: '', + roles: roles, + badges: const [], + subscriptions: const [], + subscribers: const [], + ); + } + + const details = ProfileDetailsModel( + firstName: 'Test', + lastName: 'User', + birthdate: '1990-01-01', + gender: 'male', + country: 'Russia', + city: 'Moscow', + lang: 'ru', + weight: 70.0, + height: 175, + chestCircumference: 100, + waistCircumference: 80, + hipCircumference: 90, + bloodPressureUp: 120, + bloodPressureDown: 80, + hasHypo: false, + hasHyper: false, + aboutAlergy: '', + aboutTakingPils: '', + aboutSportHobbies: '', + favoriteFoods: '', + unfavoriteFoods: '', + additionalInfo: '', + isMoodFillable: true, + isBedtimeFillable: true, + activityCoefficient: 1.5, + ); + + const consultantInfo = ConsultationRequestModel( + ratingPlace: 5, + educationModel: EducationModel( + hasMedicalEducation: 0, + completedCourses: null, + vkLink: null, + instaLink: null, + fbLink: null, + tgLink: null, + personalSiteLink: null, + requestState: ModerationStatus.approved, + ), + photos: [], + ); + + testWidgets( + 'a consultant with null social links renders without an ErrorWidget', + (tester) async { + when(profileRepository.getProfileBySlug(any)).thenAnswer( + (_) async => profileOf('other-consultant', roles: ['consultant']), + ); + when( + profileRepository.getMyProfile(), + ).thenAnswer((_) async => profileOf('me')); + when( + profileRepository.getProfileDetailsBySlug(any), + ).thenAnswer((_) async => details); + when( + profileRepository.getBlogPostsByAuthorSlug(slug: anyNamed('slug')), + ).thenAnswer((_) async => []); + when( + consultantRepository.getConsultantRequestStatus(any), + ).thenAnswer((_) async => consultantInfo); + when(plansRepository.getPlansBySlug(any)).thenAnswer((_) async => []); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + wrap(const ProfileScreen(slug: 'other-consultant')), + ); + await tester.pumpAndSettle(); + }); + + expect(tester.takeException(), isNull); + expect(find.byType(ErrorWidget), findsNothing); + expect(find.byType(ProfileScreen), findsOneWidget); + }, + ); + }); +} diff --git a/test/features/profile/presentation/pages/profile_screen_plan_like_test.dart b/test/features/profile/presentation/pages/profile_screen_plan_like_test.dart new file mode 100644 index 00000000..f48ec580 --- /dev/null +++ b/test/features/profile/presentation/pages/profile_screen_plan_like_test.dart @@ -0,0 +1,272 @@ +import 'package:eatvio_app/core/app_config.dart'; +import 'package:eatvio_app/core/app_initializer.dart'; +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/core/widgets/bookmark_button.dart'; +import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart'; +import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; +import 'package:eatvio_app/features/insights/repositories/insights_repository.dart'; +import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart' + as profile_plans; +import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; +import 'package:eatvio_app/features/profile/presentation/pages/profile_screen.dart'; +import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:eatvio_app/features/plans/repositories/plan_repository.dart'; +import 'package:eatvio_app/features/plans/repositories/plans_repository.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:flutter_portal/flutter_portal.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:network_image_mock/network_image_mock.dart'; + +import '../../../../fixtures/doubles/insights_doubles.dart'; +import '../../../../fixtures/fixture_reader.dart'; +import 'profile_screen_plan_like_test.mocks.dart'; + +@GenerateNiceMocks([ + MockSpec(), + MockSpec(), + MockSpec(), + MockSpec(), + MockSpec(), +]) +void main() { + group('ProfileScreen — план консультанта', () { + late MockProfileRepository profileRepository; + late MockChatRepository chatRepository; + late MockConsultantRepository consultantRepository; + late MockPlansRepository plansRepository; + late MockPlanRepository planRepository; + + setUpAll(() async { + dotenv.loadFromString( + envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost', + ); + }); + + setUp(() async { + await sl.reset(); + sl.registerLazySingleton( + () => + AppConfig(buildType: AppBuildType.tests) + ..setBaseUrl('http://localhost'), + ); + + profileRepository = MockProfileRepository(); + chatRepository = MockChatRepository(); + consultantRepository = MockConsultantRepository(); + plansRepository = MockPlansRepository(); + planRepository = MockPlanRepository(); + + when( + planRepository.planLikeState, + ).thenAnswer((_) => const Stream.empty()); + when( + planRepository.planFavoriteState, + ).thenAnswer((_) => const Stream.empty()); + when( + planRepository.planCommentsState, + ).thenAnswer((_) => const Stream.empty()); + when(planRepository.likePlan(any)).thenAnswer((_) async {}); + when(planRepository.addToFavorite(any)).thenAnswer((_) async {}); + when(planRepository.removeFromFavorite(any)).thenAnswer((_) async {}); + + sl.registerLazySingleton(() => profileRepository); + sl.registerLazySingleton( + () => FakeInsightsRepository(), + ); + sl.registerLazySingleton(() => chatRepository); + sl.registerLazySingleton( + () => consultantRepository, + ); + sl.registerLazySingleton(() => plansRepository); + sl.registerLazySingleton(() => planRepository); + + sl.registerFactory( + () => ProfileCubit( + profileRepository: sl(), + chatRepository: sl(), + consultantRepository: sl(), + ), + ); + sl.registerFactory( + () => profile_plans.PlansCubit( + plansRepository: sl(), + planRepository: sl(), + ), + ); + }); + + tearDown(() async { + await sl.reset(); + }); + + Widget wrap(Widget child) { + return Portal( + child: MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [ + S.delegate, + ...GlobalMaterialLocalizations.delegates, + ], + supportedLocales: const [Locale('ru')], + home: Scaffold(body: child), + ), + ); + } + + ProfileModel profileOf(String slug, {List roles = const []}) { + return ProfileModel( + id: 1, + name: 'Test User', + email: 'test@example.com', + phoneConfirmationState: 'confirmed', + slug: slug, + isPublicProfile: true, + isBlockedByMe: false, + isBlockedByAuthor: false, + isBlockedByUser: false, + isEntitySubscribedByMe: false, + profilePhotoUrl: '', + roles: roles, + badges: const [], + subscriptions: const [], + subscribers: const [], + ); + } + + const details = ProfileDetailsModel( + firstName: 'Test', + lastName: 'User', + birthdate: '1990-01-01', + gender: 'male', + country: 'Russia', + city: 'Moscow', + lang: 'ru', + weight: 70.0, + height: 175, + chestCircumference: 100, + waistCircumference: 80, + hipCircumference: 90, + bloodPressureUp: 120, + bloodPressureDown: 80, + hasHypo: false, + hasHyper: false, + aboutAlergy: '', + aboutTakingPils: '', + aboutSportHobbies: '', + favoriteFoods: '', + unfavoriteFoods: '', + additionalInfo: '', + isMoodFillable: true, + isBedtimeFillable: true, + activityCoefficient: 1.5, + ); + + const consultantInfo = ConsultationRequestModel( + ratingPlace: 5, + educationModel: EducationModel( + hasMedicalEducation: 0, + completedCourses: null, + vkLink: '', + instaLink: '', + fbLink: '', + tgLink: '', + personalSiteLink: '', + requestState: ModerationStatus.approved, + ), + photos: [], + ); + + PlanModel activePlan() { + return PlanModel.fromJson( + FixtureReader.readAsMap('plans/plan_response.json'), + ).copyWith( + state: 'active', + wasLikedByMe: false, + isFavorite: false, + totalLikes: 10, + ); + } + + Future pumpConsultantProfile(WidgetTester tester) async { + when(profileRepository.getProfileBySlug(any)).thenAnswer( + (_) async => profileOf('other-consultant', roles: ['consultant']), + ); + when( + profileRepository.getMyProfile(), + ).thenAnswer((_) async => profileOf('me')); + when( + profileRepository.getProfileDetailsBySlug(any), + ).thenAnswer((_) async => details); + when( + profileRepository.getBlogPostsByAuthorSlug(slug: anyNamed('slug')), + ).thenAnswer((_) async => []); + when( + consultantRepository.getConsultantRequestStatus(any), + ).thenAnswer((_) async => consultantInfo); + when( + plansRepository.getPlansBySlug(any), + ).thenAnswer((_) async => [activePlan()]); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + wrap(const ProfileScreen(slug: 'other-consultant')), + ); + await tester.pumpAndSettle(); + // ExpandablePageView measures its height in a post-frame callback, + // so the plan card appears only after an extra frame. + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + }); + } + + testWidgets( + 'tapping like on a consultant plan in someone else profile updates like state', + (tester) async { + await pumpConsultantProfile(tester); + + final likeButton = find.byIcon(Icons.favorite_border_rounded); + expect(likeButton, findsOneWidget); + await tester.ensureVisible(likeButton); + await tester.pump(); + + await tester.tap(likeButton); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + + expect(tester.takeException(), isNull); + expect(find.byIcon(Icons.favorite_rounded), findsOneWidget); + expect(find.text('11'), findsOneWidget); + }, + ); + + testWidgets( + 'tapping bookmark on a consultant plan in someone else profile updates favorite state', + (tester) async { + await pumpConsultantProfile(tester); + + final bookmark = find.descendant( + of: find.byType(BookmarkButton), + matching: find.byIcon(Icons.bookmark_border_rounded), + ); + expect(bookmark, findsOneWidget); + await tester.ensureVisible(bookmark); + await tester.pump(); + + await tester.tap(bookmark); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + + expect(tester.takeException(), isNull); + expect(find.byIcon(Icons.bookmark), findsOneWidget); + }, + ); + }); +} diff --git a/test/features/profile/presentation/pages/profile_screen_smoke_test.dart b/test/features/profile/presentation/pages/profile_screen_smoke_test.dart index 23d2eb53..0fe84694 100644 --- a/test/features/profile/presentation/pages/profile_screen_smoke_test.dart +++ b/test/features/profile/presentation/pages/profile_screen_smoke_test.dart @@ -12,6 +12,7 @@ import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_ import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/pages/profile_screen.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:eatvio_app/features/plans/repositories/plan_repository.dart'; import 'package:eatvio_app/features/plans/repositories/plans_repository.dart'; import 'package:eatvio_app/generated/l10n.dart'; import 'package:material_ui/material_ui.dart'; @@ -29,6 +30,7 @@ import 'profile_screen_smoke_test.mocks.dart'; MockSpec(), MockSpec(), MockSpec(), + MockSpec(), ]) void main() { group('ProfileScreen smoke', () { @@ -36,6 +38,7 @@ void main() { late MockChatRepository chatRepository; late MockConsultantRepository consultantRepository; late MockPlansRepository plansRepository; + late MockPlanRepository planRepository; setUpAll(() async { dotenv.loadFromString( @@ -55,6 +58,11 @@ void main() { chatRepository = MockChatRepository(); consultantRepository = MockConsultantRepository(); plansRepository = MockPlansRepository(); + planRepository = MockPlanRepository(); + + when(planRepository.planLikeState).thenAnswer((_) => const Stream.empty()); + when(planRepository.planFavoriteState).thenAnswer((_) => const Stream.empty()); + when(planRepository.planCommentsState).thenAnswer((_) => const Stream.empty()); sl.registerLazySingleton(() => profileRepository); sl.registerLazySingleton( @@ -65,6 +73,7 @@ void main() { () => consultantRepository, ); sl.registerLazySingleton(() => plansRepository); + sl.registerLazySingleton(() => planRepository); sl.registerFactory( () => ProfileCubit( @@ -74,7 +83,10 @@ void main() { ), ); sl.registerFactory( - () => profile_plans.PlansCubit(plansRepository: sl()), + () => profile_plans.PlansCubit( + plansRepository: sl(), + planRepository: sl(), + ), ); }); diff --git a/test/features/profile/presentation/widgets/profile_blog_post_widget_like_test.dart b/test/features/profile/presentation/widgets/profile_blog_post_widget_like_test.dart new file mode 100644 index 00000000..37bb4f31 --- /dev/null +++ b/test/features/profile/presentation/widgets/profile_blog_post_widget_like_test.dart @@ -0,0 +1,256 @@ +import 'dart:async'; + +import 'package:eatvio_app/core/app_config.dart'; +import 'package:eatvio_app/core/app_initializer.dart'; +import 'package:eatvio_app/core/locator_service.dart'; +import 'package:eatvio_app/core/theme/theme_helper.dart'; +import 'package:eatvio_app/features/chat/repositories/chat_repository.dart'; +import 'package:eatvio_app/features/consultant/become_consultant/repositories/consultant_repository.dart'; +import 'package:eatvio_app/features/feed/models/feed_blog_post_model.dart'; +import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart'; +import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart'; +import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_state.dart'; +import 'package:eatvio_app/features/profile/presentation/widgets/profile_blog_post_widget.dart'; +import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:eatvio_app/generated/l10n.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_dotenv/flutter_dotenv.dart'; +import 'package:flutter_portal/flutter_portal.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:network_image_mock/network_image_mock.dart'; + +import '../../../../fixtures/feed_fixtures.dart'; +import 'profile_blog_post_widget_like_test.mocks.dart'; + +@GenerateNiceMocks([ + MockSpec(), + MockSpec(), + MockSpec(), + MockSpec(), + MockSpec(), +]) +void main() { + group('ProfileBlogPostWidget — like', () { + setUpAll(() async { + dotenv.loadFromString( + envString: 'DEV_BASE_URL=http://localhost\nBASE_URL=http://localhost', + ); + }); + + setUp(() async { + await sl.reset(); + sl.registerLazySingleton( + () => + AppConfig(buildType: AppBuildType.tests) + ..setBaseUrl('http://localhost'), + ); + }); + + tearDown(() async { + await sl.reset(); + }); + + const profile = ProfileModel( + id: 1, + name: 'User', + email: 'u@e.com', + phoneConfirmationState: 'confirmed', + slug: 'user', + isPublicProfile: true, + isBlockedByMe: false, + isBlockedByAuthor: false, + isBlockedByUser: false, + isEntitySubscribedByMe: false, + profilePhotoUrl: '', + roles: [], + badges: [], + subscriptions: [], + subscribers: [], + ); + + const details = ProfileDetailsModel( + firstName: 'Test', + lastName: 'User', + birthdate: '1990-01-01', + gender: 'male', + country: 'Russia', + city: 'Moscow', + lang: 'ru', + weight: 70.0, + height: 175, + chestCircumference: 100, + waistCircumference: 80, + hipCircumference: 90, + bloodPressureUp: 120, + bloodPressureDown: 80, + hasHypo: false, + hasHyper: false, + aboutAlergy: '', + aboutTakingPils: '', + aboutSportHobbies: '', + favoriteFoods: '', + unfavoriteFoods: '', + additionalInfo: '', + isMoodFillable: true, + isBedtimeFillable: true, + activityCoefficient: 1.5, + ); + + ProfileState loadedState() { + return ProfileState.loaded( + profile: profile, + profileDetails: details, + blogPosts: [ + FeedFixtures.feedBlogPostModel().copyWith( + wasLikedByMe: false, + totalLikes: 10, + ), + ], + isMyProfile: true, + certPhotos: const [], + ); + } + + Widget wrap({ + required ProfileCubit profileCubit, + required FeedCubit feedCubit, + }) { + return Portal( + child: MaterialApp( + theme: ThemeHelper().themeData(), + localizationsDelegates: const [ + S.delegate, + ...GlobalMaterialLocalizations.delegates, + ], + supportedLocales: const [Locale('ru')], + home: Scaffold( + body: MediaQuery( + data: const MediaQueryData(size: Size(800, 1600)), + child: SingleChildScrollView( + child: BlocProvider.value( + value: feedCubit, + child: ProfileBlogPostWidget( + index: 0, + profileCubit: profileCubit, + ), + ), + ), + ), + ), + ), + ); + } + + testWidgets( + 'passes the new like value to updateFeedBlogPostList before the request completes', + (tester) async { + final profileCubit = _RecordingProfileCubit( + profileRepository: MockProfileRepository(), + chatRepository: MockChatRepository(), + consultantRepository: MockConsultantRepository(), + ); + addTearDown(profileCubit.close); + profileCubit.emit(loadedState()); + final expectedPost = + (profileCubit.state as ProfileStateLoaded).blogPosts.single; + + final feedCubit = MockFeedCubit(); + final likeCompleter = Completer(); + when(feedCubit.likePost(any)).thenAnswer((_) => likeCompleter.future); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + wrap(profileCubit: profileCubit, feedCubit: feedCubit), + ); + await tester.pumpAndSettle(); + + final likeButton = find.byIcon(Icons.favorite_border_rounded); + await tester.ensureVisible(likeButton); + await tester.pump(); + await tester.tap(likeButton); + // A frame while the HTTP request is still in flight: the rebuild resets + // the mutable isLiked field to post.wasLikedByMe (false). + await tester.pump(); + }); + + // The widget must propagate the NEW value synchronously, before the + // request completes. A broken implementation that reads the mutable + // isLiked field after the await has not called this at all yet. + expect(profileCubit.likeUpdates, hasLength(1)); + expect(profileCubit.likeUpdates.single.post.id, expectedPost.id); + expect(profileCubit.likeUpdates.single.wasLikedByMe, isTrue); + + likeCompleter.complete(); + await tester.pump(); + + // Issue #582, P1: exactly once, with the NEW value. + expect(profileCubit.likeUpdates, hasLength(1)); + expect(profileCubit.likeUpdates.single.wasLikedByMe, isTrue); + }, + ); + + testWidgets( + 'liking a post stores the new like value and keeps the heart and counter after rebuild', + (tester) async { + final feedCubit = MockFeedCubit(); + final likeCompleter = Completer(); + when(feedCubit.likePost(any)).thenAnswer((_) => likeCompleter.future); + + final profileCubit = ProfileCubit( + profileRepository: MockProfileRepository(), + chatRepository: MockChatRepository(), + consultantRepository: MockConsultantRepository(), + ); + addTearDown(profileCubit.close); + profileCubit.emit(loadedState()); + + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + wrap(profileCubit: profileCubit, feedCubit: feedCubit), + ); + await tester.pumpAndSettle(); + + final likeButton = find.byIcon(Icons.favorite_border_rounded); + await tester.ensureVisible(likeButton); + await tester.pump(); + await tester.tap(likeButton); + // A frame while the HTTP request is still in flight: the build resets + // isLiked/totalLikes from the post unless the new value was stored. + await tester.pump(); + }); + + expect(find.byIcon(Icons.favorite_rounded), findsOneWidget); + expect(find.text('11'), findsOneWidget); + + likeCompleter.complete(); + await tester.pump(); + + final state = profileCubit.state as ProfileStateLoaded; + expect(state.blogPosts.single.wasLikedByMe, isTrue); + expect(state.blogPosts.single.totalLikes, 11); + expect(find.byIcon(Icons.favorite_rounded), findsOneWidget); + expect(find.text('11'), findsOneWidget); + }, + ); + }); +} + +class _RecordingProfileCubit extends ProfileCubit { + _RecordingProfileCubit({ + required super.profileRepository, + required super.chatRepository, + required super.consultantRepository, + }); + + final List<({FeedBlogPostModel post, bool wasLikedByMe})> likeUpdates = []; + + @override + void updateFeedBlogPostList(FeedBlogPostModel post, bool wasLikedByMe) { + likeUpdates.add((post: post, wasLikedByMe: wasLikedByMe)); + super.updateFeedBlogPostList(post, wasLikedByMe); + } +} From 608016c8ada6e1d3b672b372ba403f18c93066c1 Mon Sep 17 00:00:00 2001 From: alex-chevski Date: Fri, 20 Nov 2026 17:42:03 +0300 Subject: [PATCH 6/6] feat(l10n): localize rating place and favorite error messages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - add rating_place and error_try_again_later ARB keys (ru/en) - use S.rating_place in profile screen, plan widget and author card - use S.current.error_try_again_later in profile plans cubit - hide rating badge when rating place is null instead of rendering null-й - initialize localization in profile plans cubit test --- .../presentation/widgets/author_card.dart | 5 +- .../presentation/widgets/plan_widget.dart | 33 +++++---- .../bloc/plans_cubit/plans_cubit.dart | 4 +- .../presentation/pages/profile_screen.dart | 70 ++++++++++--------- lib/generated/intl/messages_en.dart | 5 ++ lib/generated/intl/messages_ru.dart | 5 ++ lib/generated/l10n.dart | 20 ++++++ lib/l10n/intl_en.arb | 9 ++- lib/l10n/intl_ru.arb | 9 ++- .../profile_plans_cubit_like_test.dart | 5 +- 10 files changed, 112 insertions(+), 53 deletions(-) diff --git a/lib/features/diets/presentation/widgets/author_card.dart b/lib/features/diets/presentation/widgets/author_card.dart index 705c717f..71ec57c1 100644 --- a/lib/features/diets/presentation/widgets/author_card.dart +++ b/lib/features/diets/presentation/widgets/author_card.dart @@ -7,6 +7,7 @@ import 'package:eatvio_app/core/utils/url_utils.dart'; import 'package:eatvio_app/core/theme/theme_helper.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; import 'package:eatvio_app/features/user_details/presentation/user_details_screen.dart'; +import 'package:eatvio_app/generated/l10n.dart'; import 'package:material_ui/material_ui.dart'; import 'package:flutter_svg/svg.dart'; import 'package:go_router/go_router.dart'; @@ -107,7 +108,9 @@ class AuthorCard extends StatelessWidget { backgroundColor: appTheme.cardBackground, children: [ Text( - '${author.authorPlaceInRating}-й в рейтинге', + S.of(context).rating_place( + author.authorPlaceInRating!, + ), style: TextStyles.textMMediumAuto.copyWith( color: appTheme.blueA400, ), diff --git a/lib/features/feed/presentation/widgets/plan_widget.dart b/lib/features/feed/presentation/widgets/plan_widget.dart index d6784ead..b5ad3bee 100644 --- a/lib/features/feed/presentation/widgets/plan_widget.dart +++ b/lib/features/feed/presentation/widgets/plan_widget.dart @@ -202,22 +202,25 @@ class _PlanWidgetState extends State { ), subtitle: Row( children: [ - InfoBouble( - radius: 12, - backgroundColor: appTheme.gray50, - padding: const EdgeInsets.symmetric( - vertical: 4, - horizontal: 10, - ), - children: [ - Text( - '${widget.plan.author.authorPlaceInRating}-й в рейтинге', - style: TextStyles.textXSSemibold.copyWith( - color: appTheme.blueA400, - ), + if (widget.plan.author.authorPlaceInRating != null) + InfoBouble( + radius: 12, + backgroundColor: appTheme.gray50, + padding: const EdgeInsets.symmetric( + vertical: 4, + horizontal: 10, ), - ], - ), + children: [ + Text( + s.rating_place( + widget.plan.author.authorPlaceInRating!, + ), + style: TextStyles.textXSSemibold.copyWith( + color: appTheme.blueA400, + ), + ), + ], + ), const Spacer(), Text( '${widget.plan.packetsCount == 1 ? widget.plan.packet1Options?.price : '${s.from} ${widget.plan.minPriceOfOptions.toStringAsFixed(0)}'}₽', diff --git a/lib/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart b/lib/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart index 1d7557ca..ec70775b 100644 --- a/lib/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart +++ b/lib/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart @@ -9,6 +9,7 @@ import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart'; import 'package:eatvio_app/features/plans/repositories/plan_repository.dart'; import 'package:eatvio_app/features/plans/repositories/plans_repository.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_state.dart'; +import 'package:eatvio_app/generated/l10n.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class PlansCubit extends Cubit { @@ -16,7 +17,6 @@ class PlansCubit extends Cubit { final PlanRepository planRepository; static const Duration _debounceDuration = Duration(milliseconds: 200); - static const String _favoriteErrorMessage = 'Произошла ошибка. Попробуйте ещё раз через некоторое время'; late final StreamSubscription likesStateSubscription; late final StreamSubscription favoriteStateSubscription; @@ -109,7 +109,7 @@ class PlansCubit extends Cubit { await reportFrom(e, st, this); if (isClosed) return; _updatePlanBySlug(slug, (plan) => plan.copyWith(isFavorite: previousIsFavorite)); - showErrorToast(_favoriteErrorMessage); + showErrorToast(S.current.error_try_again_later); } }); } diff --git a/lib/features/profile/presentation/pages/profile_screen.dart b/lib/features/profile/presentation/pages/profile_screen.dart index f4b30801..d64421f2 100644 --- a/lib/features/profile/presentation/pages/profile_screen.dart +++ b/lib/features/profile/presentation/pages/profile_screen.dart @@ -205,24 +205,27 @@ class _ProfileScreenState extends State { ), ), const SizedBox(width: 12), - Container( - padding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 8, - ), - decoration: BoxDecoration( - color: const Color(0xFFF6FAFF), - borderRadius: BorderRadius.circular(12), - ), - child: Text( - '${state.consultantInfo!.ratingPlace}-й в рейтинге', - style: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600, - color: appTheme.blueA400, + if (state.consultantInfo!.ratingPlace != null) + Container( + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 8, + ), + decoration: BoxDecoration( + color: const Color(0xFFF6FAFF), + borderRadius: BorderRadius.circular(12), + ), + child: Text( + S.of(context).rating_place( + state.consultantInfo!.ratingPlace!, + ), + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: appTheme.blueA400, + ), ), ), - ), ], ), if (state @@ -378,24 +381,27 @@ class _ProfileScreenState extends State { ), ), const SizedBox(width: 12), - Container( - padding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 8, - ), - decoration: BoxDecoration( - color: const Color(0xFFF6FAFF), - borderRadius: BorderRadius.circular(12), - ), - child: Text( - '${consultantInfo.ratingPlace}-й в рейтинге', - style: TextStyle( - fontSize: 16, - fontWeight: FontWeight.w600, - color: appTheme.blueA400, + if (consultantInfo.ratingPlace != null) + Container( + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 8, + ), + decoration: BoxDecoration( + color: const Color(0xFFF6FAFF), + borderRadius: BorderRadius.circular(12), + ), + child: Text( + S.of(context).rating_place( + consultantInfo.ratingPlace!, + ), + style: TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + color: appTheme.blueA400, + ), ), ), - ), ], ), if (consultantInfo.educationModel.hasMedicalEducation == 1) diff --git a/lib/generated/intl/messages_en.dart b/lib/generated/intl/messages_en.dart index a7560f42..fa0b1557 100644 --- a/lib/generated/intl/messages_en.dart +++ b/lib/generated/intl/messages_en.dart @@ -99,6 +99,8 @@ class MessageLookup extends MessageLookupByLibrary { static String m31(planName) => "Вы отменили подписку на план «${planName}»"; + static String m32(place) => "#${place} in the ranking"; + final messages = _notInlinedMessages(_notInlinedMessages); static Map _notInlinedMessages(_) => { "Moscow": MessageLookupByLibrary.simpleMessage("Москва"), @@ -370,6 +372,8 @@ class MessageLookup extends MessageLookupByLibrary { MessageLookupByLibrary.simpleMessage("Enter promo code"), "error_desc": MessageLookupByLibrary.simpleMessage( "Произошла ошибка. Мы уже работаем над её устранением. Попробуйте позже"), + "error_try_again_later": MessageLookupByLibrary.simpleMessage( + "Something went wrong. Please try again later."), "exit": MessageLookupByLibrary.simpleMessage("Выйти"), "expand": MessageLookupByLibrary.simpleMessage("Показать полностью"), "explainResonOfCancelation": @@ -794,6 +798,7 @@ class MessageLookup extends MessageLookupByLibrary { MessageLookupByLibrary.simpleMessage("Рейтинг и статистика"), "rating_history": MessageLookupByLibrary.simpleMessage("Начисление рейтинга"), + "rating_place": m32, "reasonExample": MessageLookupByLibrary.simpleMessage("Заказал по ошибке"), "recipe_author": MessageLookupByLibrary.simpleMessage("Автор рецепта"), diff --git a/lib/generated/intl/messages_ru.dart b/lib/generated/intl/messages_ru.dart index ca52a88e..0729e17d 100644 --- a/lib/generated/intl/messages_ru.dart +++ b/lib/generated/intl/messages_ru.dart @@ -73,6 +73,8 @@ class MessageLookup extends MessageLookupByLibrary { static String m30(percent) => "Скачивание… ${percent}%"; + static String m31(place) => "${place}-й в рейтинге"; + final messages = _notInlinedMessages(_notInlinedMessages); static Map _notInlinedMessages(_) => { "Moscow": MessageLookupByLibrary.simpleMessage("Москва"), @@ -197,6 +199,8 @@ class MessageLookup extends MessageLookupByLibrary { MessageLookupByLibrary.simpleMessage("Введите информацию..."), "enter_promo_code": MessageLookupByLibrary.simpleMessage("Введите промокод"), + "error_try_again_later": MessageLookupByLibrary.simpleMessage( + "Произошла ошибка. Попробуйте ещё раз через некоторое время"), "exit": MessageLookupByLibrary.simpleMessage("Выйти"), "expand": MessageLookupByLibrary.simpleMessage("Показать полностью"), "fats": MessageLookupByLibrary.simpleMessage("Жиры"), @@ -486,6 +490,7 @@ class MessageLookup extends MessageLookupByLibrary { "public_diet_state": MessageLookupByLibrary.simpleMessage("Публичная"), "publish": MessageLookupByLibrary.simpleMessage("Опубликовать"), "published": MessageLookupByLibrary.simpleMessage("Опубликованные"), + "rating_place": m31, "removeFromActive": MessageLookupByLibrary.simpleMessage("Снять с публикации"), "save": MessageLookupByLibrary.simpleMessage("Сохранить"), diff --git a/lib/generated/l10n.dart b/lib/generated/l10n.dart index 76576ed6..a9946216 100644 --- a/lib/generated/l10n.dart +++ b/lib/generated/l10n.dart @@ -6411,6 +6411,26 @@ class S { args: [], ); } + + /// `{place}-й в рейтинге` + String rating_place(int place) { + return Intl.message( + '$place-й в рейтинге', + name: 'rating_place', + desc: '', + args: [place], + ); + } + + /// `Произошла ошибка. Попробуйте ещё раз через некоторое время` + String get error_try_again_later { + return Intl.message( + 'Произошла ошибка. Попробуйте ещё раз через некоторое время', + name: 'error_try_again_later', + desc: '', + args: [], + ); + } } class AppLocalizationDelegate extends LocalizationsDelegate { diff --git a/lib/l10n/intl_en.arb b/lib/l10n/intl_en.arb index 82c7d289..972fc86e 100644 --- a/lib/l10n/intl_en.arb +++ b/lib/l10n/intl_en.arb @@ -837,5 +837,12 @@ "video_call_recordings_period_week": "7 days", "video_call_recordings_period_current_month": "Current month", "video_call_recordings_period_prev_month": "Previous month", - "video_call_recordings_period_all": "All time" + "video_call_recordings_period_all": "All time", + "rating_place": "#{place} in the ranking", + "@rating_place": { + "placeholders": { + "place": {"type": "int"} + } + }, + "error_try_again_later": "Something went wrong. Please try again later." } diff --git a/lib/l10n/intl_ru.arb b/lib/l10n/intl_ru.arb index b6960122..cc469a53 100644 --- a/lib/l10n/intl_ru.arb +++ b/lib/l10n/intl_ru.arb @@ -592,5 +592,12 @@ "video_call_recordings_period_week": "7 дней", "video_call_recordings_period_current_month": "Текущий месяц", "video_call_recordings_period_prev_month": "Прошлый месяц", - "video_call_recordings_period_all": "Всё время" + "video_call_recordings_period_all": "Всё время", + "rating_place": "{place}-й в рейтинге", + "@rating_place": { + "placeholders": { + "place": {"type": "int"} + } + }, + "error_try_again_later": "Произошла ошибка. Попробуйте ещё раз через некоторое время" } diff --git a/test/features/profile/presentation/bloc/plans_cubit/profile_plans_cubit_like_test.dart b/test/features/profile/presentation/bloc/plans_cubit/profile_plans_cubit_like_test.dart index 8af8345d..30bfdefe 100644 --- a/test/features/profile/presentation/bloc/plans_cubit/profile_plans_cubit_like_test.dart +++ b/test/features/profile/presentation/bloc/plans_cubit/profile_plans_cubit_like_test.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:ui' show Locale; import 'package:easy_debounce/easy_debounce.dart'; import 'package:eatvio_app/core/error_reporting/error_reporter.dart'; @@ -9,6 +10,7 @@ import 'package:eatvio_app/features/plans/repositories/plan_repository.dart'; import 'package:eatvio_app/features/plans/repositories/plans_repository.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_cubit.dart'; import 'package:eatvio_app/features/profile/presentation/bloc/plans_cubit/plans_state.dart'; +import 'package:eatvio_app/generated/l10n.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; @@ -69,7 +71,8 @@ void main() { ); } - setUpAll(() { + setUpAll(() async { + await S.load(const Locale('ru')); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler( const MethodChannel('PonnamKarthik/fluttertoast'),