forked from eatvio/eatvio_app
Compare commits
58 Commits
issue-1089
...
issue-1122
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3db96a1969 | ||
| 0511bd2cb5 | |||
| 28ae75474a | |||
| da0ac9d396 | |||
| 22b8ef97b4 | |||
| 6c4572af55 | |||
| e1a1ce4b68 | |||
| 67920b2016 | |||
| ad70d0988e | |||
| 0241265b3c | |||
|
|
fc28062bb5 | ||
| f947182632 | |||
|
|
27b8128a19 | ||
| 924dc2c16a | |||
| 57536aba06 | |||
| 16084ee94c | |||
| bd1155233f | |||
| 53ce73b41e | |||
|
|
1829ad611d | ||
| 2b2991012d | |||
| 7a456c2d9d | |||
| 36079de81c | |||
| 3825a974f9 | |||
| 678d73932c | |||
| 8942e11be9 | |||
|
|
55e1633d1c | ||
| 2668907f60 | |||
| 56ab9b65f9 | |||
| 5b2ac4f228 | |||
| 51aff6c175 | |||
| cba2689406 | |||
| 5f0b7e026b | |||
| 85bc2c6d5c | |||
| f58892bdeb | |||
| f14f426381 | |||
| 6a31880a85 | |||
| 3a41a85f9d | |||
| 194b8d5b16 | |||
|
|
f6f9764811 | ||
| e2d287eb9e | |||
| cf5c42ff4b | |||
| 28c62bf775 | |||
| 67e6526552 | |||
| dedb55ecca | |||
| 6b4c88068e | |||
| 04dab02a6d | |||
| c45612decb | |||
| db293bf13f | |||
| 05eaa3caa9 | |||
| fe54037cef | |||
| e6601e2fe6 | |||
| c70c9beb20 | |||
| d2fc087699 | |||
| 18925fd95e | |||
| 37a787c8d0 | |||
| fb68f02ca4 | |||
| 4b72258b1f | |||
| 3b8d1bf651 |
@@ -14,7 +14,7 @@ env:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: [ubuntu-latest]
|
||||
runs-on: [debian-12]
|
||||
|
||||
steps:
|
||||
- uses: https://github.com/actions/checkout@v3
|
||||
@@ -155,10 +155,10 @@ jobs:
|
||||
|
||||
- name: Get dependencies
|
||||
run: |
|
||||
flutter clean
|
||||
flutter pub cache repair
|
||||
flutter pub get
|
||||
dart run build_runner build --delete-conflicting-outputs
|
||||
flutter clean
|
||||
flutter pub cache repair
|
||||
flutter pub get
|
||||
dart run build_runner build --delete-conflicting-outputs
|
||||
|
||||
- name: Native Analyze
|
||||
run: flutter analyze
|
||||
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -16,6 +16,8 @@
|
||||
*.mocks.dart
|
||||
android/build/
|
||||
ios/XCBuildData/
|
||||
docs/
|
||||
specs/
|
||||
env/.env
|
||||
.env
|
||||
android/key.properties
|
||||
@@ -25,4 +27,4 @@ backend/
|
||||
.fvm/
|
||||
.fvmrc
|
||||
/eatvio
|
||||
*.code-workspace
|
||||
*.code-workspace
|
||||
|
||||
@@ -43,37 +43,95 @@ platform :ios do
|
||||
end
|
||||
|
||||
UI.message "Using auth_key_path: #{auth_key_path}"
|
||||
|
||||
|
||||
# Authenticate to App Store Connect early:
|
||||
# needed here by latest_testflight_build_number, not only by upload_to_testflight.
|
||||
app_store_connect_api_key(
|
||||
key_id: "325JS9JCZH",
|
||||
issuer_id: "dfa27d1d-2bb8-4d4d-847e-0b32f9b880b3",
|
||||
key_filepath: auth_key_path,
|
||||
duration: 1200,
|
||||
in_house: false
|
||||
)
|
||||
|
||||
# Configure Flutter for release mode
|
||||
UI.message "Configuring Flutter for release mode..."
|
||||
sh("cd .. && flutter build ios --config-only --release")
|
||||
|
||||
# Read build number from Flutter Generated.xcconfig
|
||||
# Read version and build number from Flutter Generated.xcconfig.
|
||||
# They are only a floor: the actual build number is derived from TestFlight below,
|
||||
# so repeated CI runs on the same commit can never hit
|
||||
# ENTITY_ERROR.ATTRIBUTE.INVALID.DUPLICATE ("bundle version must be higher").
|
||||
generated_xcconfig_path = File.join("..", "Flutter", "Generated.xcconfig")
|
||||
flutter_build_name = nil
|
||||
flutter_build_number = nil
|
||||
|
||||
|
||||
if File.exist?(generated_xcconfig_path)
|
||||
File.foreach(generated_xcconfig_path) do |line|
|
||||
matches = line.match(/FLUTTER_BUILD_NUMBER=(.*)/)
|
||||
if matches
|
||||
flutter_build_number = matches[1].strip
|
||||
break
|
||||
if (m = line.match(/FLUTTER_BUILD_NAME=(.*)/))
|
||||
flutter_build_name = m[1].strip
|
||||
elsif (m = line.match(/FLUTTER_BUILD_NUMBER=(.*)/))
|
||||
flutter_build_number = m[1].strip
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if flutter_build_number.nil?
|
||||
UI.user_error!("Could not find FLUTTER_BUILD_NUMBER in #{generated_xcconfig_path}")
|
||||
|
||||
if flutter_build_name.nil? || flutter_build_number.nil?
|
||||
UI.user_error!("Could not find FLUTTER_BUILD_NAME/FLUTTER_BUILD_NUMBER in #{generated_xcconfig_path}")
|
||||
end
|
||||
|
||||
UI.message "Flutter build number: #{flutter_build_number}"
|
||||
|
||||
|
||||
UI.message "Flutter version from pubspec: #{flutter_build_name} (#{flutter_build_number})"
|
||||
|
||||
# Apple closes a version train once that version is approved/released.
|
||||
# Uploading into a closed train wastes a full ~8 min build and fails only
|
||||
# at the upload step with altool 90186 ("closed for new build submissions")
|
||||
# / 90062 ("must be higher than the previously approved version").
|
||||
# Fail fast here, before building.
|
||||
closed_train_states = [
|
||||
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::READY_FOR_DISTRIBUTION,
|
||||
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::PROCESSING_FOR_DISTRIBUTION,
|
||||
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::PENDING_DEVELOPER_RELEASE,
|
||||
Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::PENDING_APPLE_RELEASE
|
||||
].join(",")
|
||||
asc_app = Spaceship::ConnectAPI::App.find("com.eatvioapp.app")
|
||||
closed_train = nil
|
||||
if asc_app.nil?
|
||||
UI.important("App com.eatvioapp.app not found in App Store Connect, skipping closed-train guard")
|
||||
else
|
||||
closed_train = asc_app.get_app_store_versions(
|
||||
filter: {
|
||||
appVersionState: closed_train_states,
|
||||
platform: Spaceship::ConnectAPI::Platform::IOS
|
||||
}
|
||||
).find do |v|
|
||||
(Gem::Version.new(v.version_string) >= Gem::Version.new(flutter_build_name))
|
||||
rescue ArgumentError
|
||||
false
|
||||
end
|
||||
end
|
||||
if closed_train
|
||||
UI.user_error!(
|
||||
"Version train #{closed_train.version_string} is closed for new submissions " \
|
||||
"(#{closed_train.app_version_state}), pubspec version is #{flutter_build_name}. " \
|
||||
"Bump the version in pubspec.yaml above #{closed_train.version_string} and re-run."
|
||||
)
|
||||
end
|
||||
|
||||
asc_latest_build_number = latest_testflight_build_number(
|
||||
app_identifier: "com.eatvioapp.app",
|
||||
version: flutter_build_name,
|
||||
initial_build_number: flutter_build_number.to_i
|
||||
)
|
||||
|
||||
new_build_number = [flutter_build_number.to_i, asc_latest_build_number].max + 1
|
||||
UI.message "Latest TestFlight build number: #{asc_latest_build_number} -> uploading build #{new_build_number}"
|
||||
|
||||
match(type: "appstore", readonly: true)
|
||||
|
||||
|
||||
# Set build number explicitly instead of incrementing
|
||||
increment_build_number(
|
||||
xcodeproj: "Runner.xcodeproj",
|
||||
build_number: flutter_build_number
|
||||
build_number: new_build_number
|
||||
)
|
||||
|
||||
update_code_signing_settings(
|
||||
@@ -93,28 +151,33 @@ platform :ios do
|
||||
export_team_id: "VL68C36HYS"
|
||||
)
|
||||
|
||||
app_store_connect_api_key(
|
||||
key_id: "325JS9JCZH",
|
||||
issuer_id: "dfa27d1d-2bb8-4d4d-847e-0b32f9b880b3",
|
||||
key_filepath: auth_key_path,
|
||||
duration: 1200,
|
||||
in_house: false
|
||||
)
|
||||
|
||||
|
||||
begin
|
||||
upload_to_testflight(
|
||||
skip_waiting_for_build_processing: true,
|
||||
skip_submission: true,
|
||||
distribute_external: false,
|
||||
notify_external_testers: false,
|
||||
changelog: "TestFlight build #{flutter_build_number}",
|
||||
changelog: "TestFlight build #{new_build_number}",
|
||||
verbose: true
|
||||
)
|
||||
rescue => ex
|
||||
UI.error "Upload to TestFlight failed: #{ex.message}"
|
||||
UI.error "Full error: #{ex.backtrace.join("\n")}"
|
||||
raise ex
|
||||
# Xcode 26 altool prints a harmless "ERROR: ... CDUploaderStateInfoResumeFilePath"
|
||||
# line even when the package was delivered fine (UPLOAD SUCCEEDED appears in the
|
||||
# same output). fastlane < 2.240.0 treats every ERROR line as a failure
|
||||
# (fastlane#30130), so the lane would die after a successful upload.
|
||||
# Real Apple rejections (90186 closed train, 90062 version too low, ...) always
|
||||
# contain UPLOAD FAILED and/or iris-code - those must still fail the lane.
|
||||
if ex.message.include?("CDUploaderStateInfoResumeFilePath") &&
|
||||
!ex.message.include?("UPLOAD FAILED") &&
|
||||
!ex.message.include?("iris-code")
|
||||
UI.important("altool delivered the package but reported a bogus resume-file ERROR " \
|
||||
"(fastlane#30130). Treating upload as successful - " \
|
||||
"verify the build appears in TestFlight.")
|
||||
else
|
||||
UI.error "Upload to TestFlight failed: #{ex.message}"
|
||||
UI.error "Full error: #{ex.backtrace.join("\n")}"
|
||||
raise ex
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -33,6 +33,20 @@ class AppConfig {
|
||||
late String _baseUrl;
|
||||
String get baseUrl => _baseUrl;
|
||||
|
||||
/// Продуктовые хосты API. Сравнение по хосту целиком: поддомены
|
||||
/// (например `*-hasan.eatvio.ru`) — это стенды разработки, не прод.
|
||||
static const List<String> prodApiHosts = ['eatvio.ru', 'eatvio.com'];
|
||||
|
||||
/// Текущий base URL указывает на продуктовый API?
|
||||
bool get isProdApi {
|
||||
final host = Uri.tryParse(baseUrl)?.host.toLowerCase() ?? '';
|
||||
if (host.isEmpty) return false;
|
||||
return prodApiHosts.any((prodHost) => host == prodHost || host == 'www.$prodHost');
|
||||
}
|
||||
|
||||
/// Работаем на стенде разработки/stage (не на продуктовом API)?
|
||||
bool get isDevOrStageStand => !isProdApi;
|
||||
|
||||
void setBaseUrl(String baseUrls) {
|
||||
_baseUrl = baseUrls;
|
||||
_persistBaseUrl(baseUrls);
|
||||
|
||||
@@ -55,6 +55,7 @@ import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/se
|
||||
import 'package:eatvio_app/features/user_details/presentation/cubit/user_details_cubit.dart';
|
||||
import 'package:eatvio_app/features/video_calls/managers/video_call_manager.dart';
|
||||
import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart';
|
||||
import 'package:eatvio_app/core/comments/comments_cubit/comments_cubit.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
@@ -97,6 +98,7 @@ class CubitRegistrations {
|
||||
systemPipCoordinator: sl(),
|
||||
),
|
||||
);
|
||||
sl.registerLazySingleton<FeedCubit>(() => FeedCubit(feedRepository: sl()));
|
||||
}
|
||||
|
||||
/// Регистрация Cubit'ов как фабрик
|
||||
@@ -108,10 +110,15 @@ class CubitRegistrations {
|
||||
firebaseApi: sl(),
|
||||
prefs: sl(),
|
||||
profileRepository: sl(),
|
||||
sessionLifecycleService: sl(),
|
||||
),
|
||||
);
|
||||
sl.registerFactory<RegistrationCubit>(
|
||||
() => RegistrationCubit(registrationRepository: sl(), prefs: sl()),
|
||||
() => RegistrationCubit(
|
||||
registrationRepository: sl(),
|
||||
prefs: sl(),
|
||||
sessionLifecycleService: sl(),
|
||||
),
|
||||
);
|
||||
sl.registerFactory<ResetPasswordCubit>(
|
||||
() => ResetPasswordCubit(resetPasswordRepository: sl()),
|
||||
@@ -120,14 +127,21 @@ class CubitRegistrations {
|
||||
() => VerifyEmailCubit(profileRepository: sl(), prefs: sl()),
|
||||
);
|
||||
sl.registerFactory<OAuthCubit>(
|
||||
() => OAuthCubit(authRepository: sl(), firebaseApi: sl(), prefs: sl()),
|
||||
() => OAuthCubit(
|
||||
authRepository: sl(),
|
||||
firebaseApi: sl(),
|
||||
prefs: sl(),
|
||||
sessionLifecycleService: sl(),
|
||||
),
|
||||
);
|
||||
sl.registerFactory<RegistrationCubitV2>(
|
||||
() =>
|
||||
RegistrationCubitV2(registrationRepository: sl(), firebaseApi: sl()),
|
||||
() => RegistrationCubitV2(
|
||||
registrationRepository: sl(),
|
||||
firebaseApi: sl(),
|
||||
sessionLifecycleService: sl(),
|
||||
),
|
||||
);
|
||||
// Feed related cubits
|
||||
sl.registerFactory<FeedCubit>(() => FeedCubit(feedRepository: sl()));
|
||||
sl.registerFactory<RecipesCubit>(
|
||||
() => RecipesCubit(
|
||||
feedRepository: sl(),
|
||||
@@ -242,6 +256,7 @@ class CubitRegistrations {
|
||||
settingsRepository: sl(),
|
||||
consultantRepository: sl(),
|
||||
consultationsRepository: sl(),
|
||||
sessionLifecycleService: sl(),
|
||||
),
|
||||
);
|
||||
sl.registerFactory<RegisterConsultantCubit>(
|
||||
@@ -263,7 +278,7 @@ class CubitRegistrations {
|
||||
),
|
||||
);
|
||||
sl.registerFactory<ConsultationsCubit>(
|
||||
() => ConsultationsCubit(consultationsRepository: sl()),
|
||||
() => ConsultationsCubit(consultationsRepository: sl(), chatRepository: sl()),
|
||||
);
|
||||
sl.registerFactory<ConsultantCommentsCubit>(
|
||||
() => ConsultantCommentsCubit(diaryRepository: sl()),
|
||||
@@ -297,7 +312,7 @@ class CubitRegistrations {
|
||||
sl.registerFactory<UserDetailsCubit>(
|
||||
() => UserDetailsCubit(profileRepository: sl()),
|
||||
);
|
||||
sl.registerFactory<MenuCubit>(() => MenuCubit(sl()));
|
||||
sl.registerFactory<MenuCubit>(() => MenuCubit(sl(), sl()));
|
||||
sl.registerFactory<MarketingCubit>(() => MarketingCubit(sl()));
|
||||
sl.registerFactory<PersonalDietSuggestionCubit>(
|
||||
() => PersonalDietSuggestionCubit(
|
||||
@@ -305,5 +320,8 @@ class CubitRegistrations {
|
||||
personalDietSuggestionService: sl(),
|
||||
),
|
||||
);
|
||||
sl.registerFactory<VideoCallRecordingsCubit>(
|
||||
() => VideoCallRecordingsCubit(repository: sl()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ import 'package:eatvio_app/features/recipe/repositories/my_recipes_repository.da
|
||||
import 'package:eatvio_app/features/registration/repositories/registration_repository.dart';
|
||||
import 'package:eatvio_app/features/registration_v2/repositories/registration_repository_v2.dart';
|
||||
import 'package:eatvio_app/features/settings/repositories/service_repository.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart';
|
||||
import 'package:eatvio_app/features/video_calls/repositories/video_call_repository.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
@@ -53,6 +54,9 @@ class RepositoryRegistrations {
|
||||
// Core repositories
|
||||
sl.registerLazySingleton<ChatRepository>(() => ChatRepository(chatService: sl()));
|
||||
sl.registerLazySingleton<VideoCallRepository>(() => VideoCallRepository(videoCallService: sl()));
|
||||
sl.registerLazySingleton<VideoCallRecordingsRepository>(
|
||||
() => VideoCallRecordingsRepository(videoCallService: sl(), dio: sl()),
|
||||
);
|
||||
sl.registerLazySingleton<FeedRepository>(() => FeedRepository(feedService: sl()));
|
||||
sl.registerLazySingleton<ProfileRepository>(() => ProfileRepository(profileService: sl()));
|
||||
sl.registerLazySingleton<CalendarRepository>(() => CalendarRepository(calendarService: sl()));
|
||||
|
||||
15
lib/core/di/session_registrations.dart
Normal file
15
lib/core/di/session_registrations.dart
Normal file
@@ -0,0 +1,15 @@
|
||||
import 'package:eatvio_app/core/error_reporting/error_reporter.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
||||
|
||||
class SessionRegistrations {
|
||||
static void registerAll() {
|
||||
sl.registerLazySingleton<SessionLifecycleService>(
|
||||
() => SessionLifecycleService(
|
||||
wsManager: sl<WsManager>(),
|
||||
errorReporter: sl<ErrorReporter>(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,7 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/app_router.dart';
|
||||
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
class TokenInterceptor extends Interceptor {
|
||||
@override
|
||||
@@ -14,6 +12,7 @@ class TokenInterceptor extends Interceptor {
|
||||
final token = await TokenStorage.getTokenFromStorage();
|
||||
if (token != null && token.isNotEmpty) {
|
||||
options.headers['Authorization'] = 'Bearer $token';
|
||||
options.extra['authToken'] = token;
|
||||
}
|
||||
|
||||
super.onRequest(options, handler);
|
||||
@@ -25,9 +24,18 @@ class TokenInterceptor extends Interceptor {
|
||||
ErrorInterceptorHandler handler,
|
||||
) async {
|
||||
if (err.response?.statusCode == 401) {
|
||||
await sl<WsManager>().clear();
|
||||
await TokenStorage.removeTokenInStorage();
|
||||
AppRouter.navigatorKey.currentContext?.go('/auth-screen');
|
||||
final requestCarriedAuth = err.requestOptions.headers.containsKey(
|
||||
'Authorization',
|
||||
);
|
||||
final requestToken = err.requestOptions.extra['authToken'];
|
||||
final currentToken = await TokenStorage.getTokenFromStorage();
|
||||
if (requestCarriedAuth &&
|
||||
requestToken != null &&
|
||||
requestToken == currentToken) {
|
||||
await sl<SessionLifecycleService>().endSession(
|
||||
reason: SessionEndReason.unauthorized,
|
||||
);
|
||||
}
|
||||
}
|
||||
super.onError(err, handler);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import 'package:eatvio_app/core/di/cubit_registrations.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/di/session_registrations.dart';
|
||||
import 'package:eatvio_app/core/prefs.dart';
|
||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
@@ -38,4 +39,6 @@ Future<void> init({required AppBuildType buildType}) async {
|
||||
sl.registerLazySingleton<WsManager>(
|
||||
() => WsManager(wsService: sl(), errorReporter: sl()),
|
||||
);
|
||||
|
||||
SessionRegistrations.registerAll();
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import 'package:eatvio_app/core/routing/route_constants.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_state.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/widgets/bottom_nav_scope.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/widgets/bottom_navigation_bar_widget.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/pages/chats_screen.dart';
|
||||
@@ -24,14 +23,10 @@ class MainNavigationRoutes {
|
||||
return [
|
||||
ShellRoute(
|
||||
builder: (context, state, child) {
|
||||
// Инициализация ProfileAvatarCubit при первом использовании ShellRoute
|
||||
final profileAvatarCubit = context.read<ProfileAvatarCubit>();
|
||||
if (profileAvatarCubit.state is ProfileAvatarStateLoading) {
|
||||
// Вызываем getMyProfile() только если состояние loading (первый запуск)
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
profileAvatarCubit.getMyProfile();
|
||||
});
|
||||
}
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
profileAvatarCubit.ensureFreshForCurrentSession();
|
||||
});
|
||||
|
||||
return _MainShellWithNavScope(currentLocation: state.matchedLocation, child: child);
|
||||
},
|
||||
|
||||
@@ -16,6 +16,9 @@ import 'package:eatvio_app/features/chat/presentation/pages/payment_screen.dart'
|
||||
import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart';
|
||||
import 'package:eatvio_app/features/video_calls/presentation/pages/video_call_screen.dart';
|
||||
import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_state.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recording_player_screen.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart';
|
||||
import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/become_consultant_screen.dart';
|
||||
import 'package:eatvio_app/features/consultant/become_consultant/presentation/pages/stepper_become_consultant_screen.dart';
|
||||
import 'package:eatvio_app/features/consultant_rating/presentation/consultant_rating_screen.dart';
|
||||
@@ -140,6 +143,19 @@ class OtherRoutes {
|
||||
GoRoute(path: ConsultationsArchiveScreen.path, name: ConsultationsArchiveScreen.name, builder: (context, state) => const ConsultationsArchiveScreen()),
|
||||
GoRoute(path: ConsultantFinancesScreen.path, name: ConsultantFinancesScreen.name, builder: (context, state) => const ConsultantFinancesScreen()),
|
||||
GoRoute(path: UserPurchasesScreen.path, name: UserPurchasesScreen.name, builder: (context, state) => const UserPurchasesScreen()),
|
||||
GoRoute(
|
||||
path: VideoCallRecordingsScreen.path,
|
||||
name: VideoCallRecordingsScreen.name,
|
||||
builder: (context, state) => const VideoCallRecordingsScreen(),
|
||||
),
|
||||
GoRoute(
|
||||
path: VideoCallRecordingPlayerScreen.path,
|
||||
name: VideoCallRecordingPlayerScreen.name,
|
||||
builder: (context, state) {
|
||||
final recording = state.extra as VideoCallRecordingModel;
|
||||
return VideoCallRecordingPlayerScreen(recording: recording);
|
||||
},
|
||||
),
|
||||
|
||||
// Finance routes
|
||||
GoRoute(path: RouteConstants.userFinanceScreen, name: 'userFinanceScreen', builder: (context, state) => const UserFinanceScreen()),
|
||||
@@ -192,7 +208,18 @@ class OtherRoutes {
|
||||
return CreatePlanScreen(plan: plan);
|
||||
},
|
||||
),
|
||||
GoRoute(path: MyDietsScreen.path, name: MyDietsScreen.name, builder: (context, state) => const MyDietsScreen()),
|
||||
GoRoute(
|
||||
path: MyDietsScreen.path,
|
||||
name: MyDietsScreen.name,
|
||||
builder: (context, state) {
|
||||
final initialTabIndex = int.tryParse(
|
||||
state.uri.queryParameters['initialTabIndex'] ?? '',
|
||||
);
|
||||
return MyDietsScreen(
|
||||
initialTabIndex: initialTabIndex ?? 0,
|
||||
);
|
||||
},
|
||||
),
|
||||
GoRoute(path: MyPlansScreen.path, name: MyPlansScreen.name, builder: (context, state) => const MyPlansScreen()),
|
||||
GoRoute(path: MyRecipesScreen.path, name: MyRecipesScreen.name, builder: (context, state) => const MyRecipesScreen()),
|
||||
|
||||
|
||||
122
lib/core/session/session_lifecycle_service.dart
Normal file
122
lib/core/session/session_lifecycle_service.dart
Normal file
@@ -0,0 +1,122 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:appmetrica_plugin/appmetrica_plugin.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/app_config.dart';
|
||||
import 'package:eatvio_app/core/app_router.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/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';
|
||||
import 'package:eatvio_app/core/prefs_keys.dart';
|
||||
import 'package:eatvio_app/core/routing/route_constants.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
|
||||
import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart';
|
||||
import 'package:eatvio_app/features/notifications/presentation/notifications_cubit/notifications_cubit.dart';
|
||||
import 'package:eatvio_app/features/profile/presentation/bloc/profile_cubit/profile_cubit.dart';
|
||||
import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
enum SessionEndReason { logout, unauthorized, accountDeleted }
|
||||
|
||||
class SessionLifecycleService {
|
||||
SessionLifecycleService({
|
||||
required WsManager wsManager,
|
||||
required ErrorReporter errorReporter,
|
||||
}) : _wsManager = wsManager,
|
||||
_errorReporter = errorReporter;
|
||||
|
||||
final WsManager _wsManager;
|
||||
final ErrorReporter _errorReporter;
|
||||
|
||||
int? _authenticatedFingerprint;
|
||||
bool _endingSession = false;
|
||||
|
||||
Future<void> endSession({required SessionEndReason reason}) async {
|
||||
if (_endingSession) return;
|
||||
_endingSession = true;
|
||||
try {
|
||||
await _run(() => _wsManager.clear());
|
||||
await _run(TokenStorage.removeTokenInStorage);
|
||||
await _run(SocketIdStorage.removeSocketIdInStorage);
|
||||
await _run(() => sl<ProfileAvatarCubit>().reset());
|
||||
await _run(() => sl<ChatsCubit>().reset());
|
||||
await _run(() => sl<NotificationsCubit>().reset());
|
||||
await _run(() => sl<NewMessagesCubit>().reset());
|
||||
await _run(() => sl<FeedCubit>().reset());
|
||||
await _run(() async => ProfileCubit.clearMyProfileReference());
|
||||
await _run(() => sl<VideoCallSessionCubit>().endCall());
|
||||
await _run(() async => AppMetrica.setUserProfileID(null));
|
||||
await _run(
|
||||
() => sl<Prefs>().remove(PrefsKeys.isEmailVerificationSkipped),
|
||||
);
|
||||
await _run(() => sl<Prefs>().remove(PrefsKeys.registrationDate));
|
||||
_authenticatedFingerprint = null;
|
||||
await _run(() async {
|
||||
final context = AppRouter.navigatorKey.currentContext;
|
||||
if (context == null) return;
|
||||
final path =
|
||||
AppRouter.appRouter.routeInformationProvider.value.uri.path;
|
||||
if (path != RouteConstants.authScreen) {
|
||||
context.go(RouteConstants.authScreen);
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
_endingSession = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> onAuthenticated() async {
|
||||
String? token;
|
||||
try {
|
||||
token = await TokenStorage.getTokenFromStorage();
|
||||
} catch (e, st) {
|
||||
await _report(e, st);
|
||||
return;
|
||||
}
|
||||
if (token == null || token.isEmpty) return;
|
||||
final fingerprint = token.hashCode;
|
||||
if (_authenticatedFingerprint == fingerprint) return;
|
||||
_authenticatedFingerprint = fingerprint;
|
||||
|
||||
await _run(() async {
|
||||
await _wsManager.clear();
|
||||
await _wsManager.initialize();
|
||||
});
|
||||
await _run(() => sl<ProfileAvatarCubit>().getMyProfile());
|
||||
await _run(() => sl<ChatsCubit>().getChatRoomsWithLoading());
|
||||
await _run(() => sl<NotificationsCubit>().getNotifications());
|
||||
await _run(() => sl<FirebaseApi>().registerPushToken());
|
||||
}
|
||||
|
||||
Future<void> logout() async {
|
||||
try {
|
||||
await _run(() => sl<FirebaseApi>().unregisterPushTokens());
|
||||
await _run(
|
||||
() => sl<Dio>().post('${sl<AppConfig>().baseUrl}/api/profile/logout'),
|
||||
);
|
||||
} finally {
|
||||
await endSession(reason: SessionEndReason.logout);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _run(FutureOr<void> Function() action) async {
|
||||
try {
|
||||
await action();
|
||||
} catch (e, st) {
|
||||
await _report(e, st);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _report(Object error, StackTrace stackTrace) {
|
||||
return _errorReporter.report(
|
||||
error,
|
||||
stackTrace,
|
||||
origin: 'SessionLifecycleService',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,7 @@ class WsManager {
|
||||
|
||||
Stream<ChannelReadEvent>? _directChatStream;
|
||||
Stream<ChannelReadEvent>? _clientTypingStream;
|
||||
Stream<ChannelReadEvent>? _chosenPlanStateChangedStream;
|
||||
|
||||
Stream<ChannelReadEvent>? get newMessagesStream =>
|
||||
_privateMessagesChannel?.bind('App\\Events\\ChatMessageUpdated');
|
||||
@@ -74,6 +75,9 @@ class WsManager {
|
||||
|
||||
Stream<ChannelReadEvent>? get clientTypingStream => _clientTypingStream;
|
||||
|
||||
Stream<ChannelReadEvent>? get chosenPlanStateChangedStream =>
|
||||
_chosenPlanStateChangedStream;
|
||||
|
||||
/// Сигнал о реконнекте сокета: эмитится после повторной подписки на каналы.
|
||||
///
|
||||
/// Подписчики используют его, чтобы догрузить пропущенные за время обрыва
|
||||
@@ -222,6 +226,9 @@ class WsManager {
|
||||
'App\\Events\\ChatMessageUpdated',
|
||||
);
|
||||
_clientTypingStream = _privateDirectChatChannel?.bind('client-typing');
|
||||
_chosenPlanStateChangedStream = _privateDirectChatChannel?.bind(
|
||||
'chosen-plan-state-changed',
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> initPresenceDirectChatChannel(String chatId) async {
|
||||
@@ -367,6 +374,7 @@ class WsManager {
|
||||
_privateDirectChatChannel?.unsubscribe();
|
||||
_directChatStream = null;
|
||||
_clientTypingStream = null;
|
||||
_chosenPlanStateChangedStream = null;
|
||||
}
|
||||
|
||||
void unsubscribePresenceDirectChatChannel() {
|
||||
@@ -401,6 +409,7 @@ class WsManager {
|
||||
_privateNotificationChannel = null;
|
||||
_directChatStream = null;
|
||||
_clientTypingStream = null;
|
||||
_chosenPlanStateChangedStream = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,11 @@ import 'dart:ui';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
Future<void> showBottomSheetWithBlur({
|
||||
/// Показывает modal bottom sheet с blur-фоном.
|
||||
///
|
||||
/// Дженерик [T] пробрасывает значение, переданное в `Navigator.pop(T)`
|
||||
/// внутри шита (по умолчанию `null`).
|
||||
Future<T?> showBottomSheetWithBlur<T>({
|
||||
required BuildContext context,
|
||||
required Widget child,
|
||||
double? height = 200,
|
||||
@@ -11,7 +15,7 @@ Future<void> showBottomSheetWithBlur({
|
||||
bool enableDrag = true,
|
||||
bool userRootNavigator = false,
|
||||
}) {
|
||||
return showModalBottomSheet(
|
||||
return showModalBottomSheet<T>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
barrierColor: appTheme.transparentBlack,
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'dart:developer';
|
||||
import 'package:eatvio_app/core/firebase_api.dart';
|
||||
import 'package:eatvio_app/core/prefs.dart';
|
||||
import 'package:eatvio_app/core/prefs_keys.dart';
|
||||
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||
import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_state.dart';
|
||||
@@ -17,15 +18,26 @@ class AuthCubit extends Cubit<AuthState> {
|
||||
final ProfileRepository profileRepository;
|
||||
final FirebaseApi firebaseApi;
|
||||
final Prefs prefs;
|
||||
final SessionLifecycleService sessionLifecycleService;
|
||||
|
||||
AuthCubit({required this.authRepository, required this.prefs, required this.profileRepository, required this.firebaseApi}) : super(const AuthState());
|
||||
AuthCubit({
|
||||
required this.authRepository,
|
||||
required this.prefs,
|
||||
required this.profileRepository,
|
||||
required this.firebaseApi,
|
||||
required this.sessionLifecycleService,
|
||||
}) : super(const AuthState());
|
||||
|
||||
Future<bool> getTokenByCredentials(String email, String password) async {
|
||||
emit(const AuthState.loading());
|
||||
try {
|
||||
final token = (await authRepository.getTokenByCredentials(email, password)).token;
|
||||
final token = (await authRepository.getTokenByCredentials(
|
||||
email,
|
||||
password,
|
||||
)).token;
|
||||
emit(AuthState.loaded(token: token));
|
||||
await TokenStorage.saveTokenInStorage(token);
|
||||
await sessionLifecycleService.onAuthenticated();
|
||||
return true;
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
@@ -48,7 +60,8 @@ class AuthCubit extends Cubit<AuthState> {
|
||||
|
||||
Future<void> registerAnonymousPushToken() async {
|
||||
try {
|
||||
final hasAnonymousTokenBeenSent = prefs.getBool(PrefsKeys.hasAnonymousTokenBeenSent) ?? false;
|
||||
final hasAnonymousTokenBeenSent =
|
||||
prefs.getBool(PrefsKeys.hasAnonymousTokenBeenSent) ?? false;
|
||||
if (!hasAnonymousTokenBeenSent) {
|
||||
await firebaseApi.registerAnonymousPushToken();
|
||||
prefs.setBool(PrefsKeys.hasAnonymousTokenBeenSent, true);
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/firebase_api.dart';
|
||||
import 'package:eatvio_app/core/mixins/registration_date_cache_mixin.dart';
|
||||
import 'package:eatvio_app/core/prefs.dart';
|
||||
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/features/auth/models/oauth_verification_request_response.dart';
|
||||
import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_state.dart';
|
||||
@@ -13,10 +14,12 @@ import 'package:eatvio_app/core/error_reporting/report_from.dart';
|
||||
class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
||||
final AuthRepository authRepository;
|
||||
final FirebaseApi firebaseApi;
|
||||
final SessionLifecycleService sessionLifecycleService;
|
||||
|
||||
OAuthCubit({
|
||||
required this.authRepository,
|
||||
required this.firebaseApi,
|
||||
required this.sessionLifecycleService,
|
||||
required Prefs prefs,
|
||||
}) : super(const OAuthState()) {
|
||||
this.prefs = prefs;
|
||||
@@ -40,6 +43,7 @@ class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
||||
|
||||
log('OAuthCubit: Got token model: ${tokenModel.token}');
|
||||
await TokenStorage.saveTokenInStorage(tokenModel.token);
|
||||
await sessionLifecycleService.onAuthenticated();
|
||||
emit(OAuthState.loaded(token: tokenModel.token));
|
||||
} on DioException catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
@@ -122,7 +126,7 @@ class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
||||
clientId: clientId,
|
||||
);
|
||||
await TokenStorage.saveTokenInStorage(token);
|
||||
await firebaseApi.registerPushToken();
|
||||
await sessionLifecycleService.onAuthenticated();
|
||||
cacheRegistrationDate(DateTime.now());
|
||||
emit(OAuthState.loaded(token: token));
|
||||
} on DioException catch (e, st) {
|
||||
@@ -241,7 +245,7 @@ class OAuthCubit extends Cubit<OAuthState> with RegistrationDateCacheMixin {
|
||||
'OAuthCubit: OAuth verification confirmed successfully, token received',
|
||||
);
|
||||
await TokenStorage.saveTokenInStorage(response.token);
|
||||
await firebaseApi.registerPushToken();
|
||||
await sessionLifecycleService.onAuthenticated();
|
||||
emit(OAuthState.loaded(token: response.token));
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
|
||||
@@ -4,12 +4,10 @@ import 'package:eatvio_app/app_keys.dart';
|
||||
import 'package:eatvio_app/core/app_config.dart';
|
||||
import 'package:eatvio_app/core/app_router.dart';
|
||||
import 'package:eatvio_app/core/const.dart';
|
||||
import 'package:eatvio_app/core/firebase_api.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/utils/image_constant.dart';
|
||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
||||
import 'package:eatvio_app/core/widgets/custom_divider.dart';
|
||||
import 'package:eatvio_app/core/widgets/custom_text_form_field.dart';
|
||||
import 'package:eatvio_app/features/auth/presentation/bloc/auth_cubit/auth_cubit.dart';
|
||||
@@ -18,8 +16,6 @@ import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_cub
|
||||
import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_state.dart';
|
||||
import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart';
|
||||
import 'package:eatvio_app/core/di/cubit_registrations.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
|
||||
import 'package:eatvio_app/features/dev_tools/presentation/dev_tools_screen.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
@@ -68,23 +64,8 @@ class _AuthScreenState extends State<AuthScreen> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _reconnectWebSocket(BuildContext context) async {
|
||||
try {
|
||||
await sl<WsManager>().clear();
|
||||
await sl<WsManager>().initialize();
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
if (context.mounted) {
|
||||
try {
|
||||
await sl<ProfileAvatarCubit>().getMyProfile();
|
||||
await sl<ChatsCubit>().getChatRoomsWithLoading();
|
||||
await sl<FirebaseApi>().registerPushToken();
|
||||
showSuccessToast('Успешный вход');
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
Future<void> _reconnectWebSocket() async {
|
||||
showSuccessToast('Успешный вход');
|
||||
AppRouter.navigatorKey.currentContext?.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
|
||||
}
|
||||
|
||||
@@ -202,18 +183,7 @@ class _AuthScreenState extends State<AuthScreen> {
|
||||
}
|
||||
|
||||
Future<void> _reconnectAfterAuth() async {
|
||||
final context = AppRouter.navigatorKey.currentContext;
|
||||
if (context == null) return;
|
||||
try {
|
||||
await sl<WsManager>().clear();
|
||||
await sl<WsManager>().initialize();
|
||||
await sl<ProfileAvatarCubit>().getMyProfile();
|
||||
await sl<ChatsCubit>().getChatRoomsWithLoading();
|
||||
await sl<FirebaseApi>().registerPushToken();
|
||||
showSuccessToast('Успешный вход');
|
||||
} catch (e) {
|
||||
log(e.toString());
|
||||
}
|
||||
showSuccessToast('Успешный вход');
|
||||
AppRouter.navigatorKey.currentContext?.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
|
||||
}
|
||||
|
||||
@@ -395,7 +365,7 @@ class _AuthScreenState extends State<AuthScreen> {
|
||||
final isAuthenticated = await authCubit.getTokenByCredentials(emailController.text, passwordController.text);
|
||||
if (isAuthenticated) {
|
||||
if (context.mounted) {
|
||||
await _reconnectWebSocket(context);
|
||||
await _reconnectWebSocket();
|
||||
}
|
||||
}
|
||||
setState(() {
|
||||
|
||||
@@ -9,11 +9,7 @@ import 'package:eatvio_app/features/auth/presentation/bloc/oauth_cubit/oauth_sta
|
||||
import 'package:eatvio_app/features/auth/entities/auth_result_entity.dart';
|
||||
import 'package:eatvio_app/core/app_router.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
|
||||
import 'package:eatvio_app/features/create_diet/presentation/widgets/error_widget.dart';
|
||||
import 'package:eatvio_app/core/firebase_api.dart';
|
||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||
import 'package:eatvio_app/core/utils/validation_utils.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
@@ -62,23 +58,8 @@ class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
|
||||
_initializeFieldsFromAuthResult();
|
||||
}
|
||||
|
||||
Future<void> _reconnectWebSocket(BuildContext context) async {
|
||||
try {
|
||||
await sl<WsManager>().clear();
|
||||
await sl<WsManager>().initialize();
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
if (context.mounted) {
|
||||
try {
|
||||
await sl<ProfileAvatarCubit>().getMyProfile();
|
||||
await sl<ChatsCubit>().getChatRoomsWithLoading();
|
||||
await sl<FirebaseApi>().registerPushToken();
|
||||
showSuccessToast('Успешная регистрация');
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
Future<void> _reconnectWebSocket() async {
|
||||
showSuccessToast('Успешная регистрация');
|
||||
AppRouter.appRouter.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
|
||||
}
|
||||
|
||||
@@ -451,7 +432,7 @@ class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
|
||||
Builder(
|
||||
builder: (context) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_reconnectWebSocket(context);
|
||||
_reconnectWebSocket();
|
||||
});
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
@@ -795,7 +776,7 @@ class _RegisterViaSocialScreenState extends State<RegisterViaSocialScreen> {
|
||||
|
||||
// Перезагружаем веб-сокет и переходим на главный экран
|
||||
if (widgetContext.mounted) {
|
||||
_reconnectWebSocket(widgetContext);
|
||||
_reconnectWebSocket();
|
||||
}
|
||||
} catch (e, stackTrace) {
|
||||
log('OAuth Verification Confirm Error: $e', error: e, stackTrace: stackTrace);
|
||||
|
||||
@@ -3,13 +3,10 @@ import 'dart:io';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/app_config.dart';
|
||||
import 'package:eatvio_app/core/app_router.dart';
|
||||
import 'package:eatvio_app/core/firebase_api.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:qr_code_scanner_plus/qr_code_scanner_plus.dart';
|
||||
@@ -39,7 +36,10 @@ class _ScanQRCodeScreenState extends State<ScanQRCodeScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Сканирование QR-кода'), centerTitle: true),
|
||||
appBar: AppBar(
|
||||
title: const Text('Сканирование QR-кода'),
|
||||
centerTitle: true,
|
||||
),
|
||||
body: Column(
|
||||
children: <Widget>[
|
||||
Expanded(
|
||||
@@ -60,30 +60,33 @@ class _ScanQRCodeScreenState extends State<ScanQRCodeScreen> {
|
||||
try {
|
||||
final scannedUrl = scanData.code;
|
||||
final uri = Uri.parse(scannedUrl ?? '');
|
||||
final scannedBaseUrl = (uri.hasAuthority) ? '${uri.scheme}://${uri.host}' : '';
|
||||
final scannedBaseUrl = (uri.hasAuthority)
|
||||
? '${uri.scheme}://${uri.host}'
|
||||
: '';
|
||||
sl<AppConfig>().setBaseUrl(scannedBaseUrl);
|
||||
sl<Dio>().options.baseUrl = scannedBaseUrl;
|
||||
final response = await Dio().getUri(uri, options: Options(headers: {'accept': 'application/json', 'content-type': 'application/json'}));
|
||||
final response = await Dio().getUri(
|
||||
uri,
|
||||
options: Options(
|
||||
headers: {
|
||||
'accept': 'application/json',
|
||||
'content-type': 'application/json',
|
||||
},
|
||||
),
|
||||
);
|
||||
final token = response.data['token'];
|
||||
await TokenStorage.saveTokenInStorage(token);
|
||||
try {
|
||||
await sl<WsManager>().clear();
|
||||
await sl<WsManager>().initialize();
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
try {
|
||||
await sl<ProfileAvatarCubit>().getMyProfile();
|
||||
await sl<ChatsCubit>().getChatRoomsWithLoading();
|
||||
await sl<FirebaseApi>().registerPushToken();
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
AppRouter.navigatorKey.currentContext?.go('/feed-screen', extra: {'needToInitializeWebSocket': false});
|
||||
await sl<SessionLifecycleService>().onAuthenticated();
|
||||
AppRouter.navigatorKey.currentContext?.go(
|
||||
'/feed-screen',
|
||||
extra: {'needToInitializeWebSocket': false},
|
||||
);
|
||||
showSuccessToast('Добро пожаловать!');
|
||||
} catch (e) {
|
||||
await controller.resumeCamera();
|
||||
showErrorToast('Что-то пошло не так. Попробуйте обновить страницу с QR-кодом или войдите с помощью логина и пароля.');
|
||||
showErrorToast(
|
||||
'Что-то пошло не так. Попробуйте обновить страницу с QR-кодом или войдите с помощью логина и пароля.',
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -6,6 +6,13 @@ class NewMessagesCubit extends Cubit<NewMessagesState> {
|
||||
|
||||
NewMessagesCubit() : super(const NewMessagesState.empty());
|
||||
|
||||
void reset() {
|
||||
_messagesCount = 0;
|
||||
if (!isClosed) {
|
||||
emit(const NewMessagesState.empty());
|
||||
}
|
||||
}
|
||||
|
||||
void incrementCounter() {
|
||||
_messagesCount++;
|
||||
emit(NewMessagesState.loaded(messagesCount: _messagesCount));
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:appmetrica_plugin/appmetrica_plugin.dart';
|
||||
import 'package:eatvio_app/core/app_router.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_state.dart';
|
||||
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/report_from.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
|
||||
class ProfileAvatarCubit extends Cubit<ProfileAvatarState> {
|
||||
final ProfileRepository profileRepository;
|
||||
|
||||
ProfileAvatarCubit({required this.profileRepository}) : super(const ProfileAvatarState.loading());
|
||||
ProfileAvatarCubit({required this.profileRepository})
|
||||
: super(const ProfileAvatarState.loading());
|
||||
|
||||
int _requestId = 0;
|
||||
int? _sessionFingerprint;
|
||||
bool _ensuring = false;
|
||||
|
||||
int _calculateAge(String birthdate) {
|
||||
try {
|
||||
@@ -25,7 +29,8 @@ class ProfileAvatarCubit extends Cubit<ProfileAvatarState> {
|
||||
final now = DateTime.now();
|
||||
int age = now.year - birthYear;
|
||||
|
||||
if (now.month < birthMonth || (now.month == birthMonth && now.day < birthDay)) {
|
||||
if (now.month < birthMonth ||
|
||||
(now.month == birthMonth && now.day < birthDay)) {
|
||||
age--;
|
||||
}
|
||||
|
||||
@@ -38,30 +43,82 @@ class ProfileAvatarCubit extends Cubit<ProfileAvatarState> {
|
||||
return 0;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
_requestId++;
|
||||
_sessionFingerprint = null;
|
||||
unawaited(AppMetrica.setUserProfileID(null).catchError((Object _) {}));
|
||||
if (!isClosed) emit(const ProfileAvatarState.loading());
|
||||
}
|
||||
|
||||
Future<void> ensureFreshForCurrentSession() async {
|
||||
final token = await TokenStorage.getTokenFromStorage();
|
||||
if (token == null || token.isEmpty) {
|
||||
reset();
|
||||
return;
|
||||
}
|
||||
|
||||
final fingerprint = token.hashCode;
|
||||
if (_sessionFingerprint == fingerprint &&
|
||||
state is ProfileAvatarStateLoaded) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (_ensuring) {
|
||||
return;
|
||||
}
|
||||
|
||||
_ensuring = true;
|
||||
try {
|
||||
await getMyProfile();
|
||||
} finally {
|
||||
_ensuring = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> getMyProfile() async {
|
||||
final requestId = ++_requestId;
|
||||
final token = await TokenStorage.getTokenFromStorage();
|
||||
final fingerprint = token?.hashCode;
|
||||
if (isClosed || requestId != _requestId) return;
|
||||
|
||||
emit(const ProfileAvatarState.loading());
|
||||
try {
|
||||
final profile = await profileRepository.getMyProfile();
|
||||
if (isClosed || requestId != _requestId) return;
|
||||
|
||||
final profileDetails = await profileRepository.getMyProfileDetails();
|
||||
if (isClosed || requestId != _requestId) return;
|
||||
|
||||
_sessionFingerprint = fingerprint;
|
||||
emit(ProfileAvatarState.loaded(profile: profile));
|
||||
|
||||
try {
|
||||
final notificationStatus = await Permission.notification.status;
|
||||
if (isClosed || requestId != _requestId) return;
|
||||
final isNotificationEnabled = notificationStatus.isGranted;
|
||||
AppMetricaUserProfile userProfile = AppMetricaUserProfile([
|
||||
AppMetricaNameAttribute.withValue(profile.name),
|
||||
AppMetricaGenderAttribute.withValue(profileDetails.gender == 'male' ? AppMetricaGender.male : AppMetricaGender.female),
|
||||
AppMetricaBirthDateAttribute.withAge(_calculateAge(profileDetails.birthdate)),
|
||||
AppMetricaNotificationEnabledAttribute.withValue(isNotificationEnabled),
|
||||
AppMetricaGenderAttribute.withValue(
|
||||
profileDetails.gender == 'male'
|
||||
? AppMetricaGender.male
|
||||
: AppMetricaGender.female,
|
||||
),
|
||||
AppMetricaBirthDateAttribute.withAge(
|
||||
_calculateAge(profileDetails.birthdate),
|
||||
),
|
||||
AppMetricaNotificationEnabledAttribute.withValue(
|
||||
isNotificationEnabled,
|
||||
),
|
||||
]);
|
||||
AppMetrica.setUserProfileID(profile.slug);
|
||||
AppMetrica.reportUserProfile(userProfile);
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
// Игнорируем ошибки плагинов, профиль уже загружен
|
||||
}
|
||||
} catch (e, st) {
|
||||
if (isClosed || requestId != _requestId) return;
|
||||
await reportFrom(e, st, this);
|
||||
AppRouter.navigatorKey.currentContext?.go('/auth-screen');
|
||||
if (isClosed || requestId != _requestId) return;
|
||||
emit(ProfileAvatarState.error(errorMessage: e.toString()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,6 +39,8 @@ class BottomNavigationBarWidget extends StatefulWidget {
|
||||
class _BottomNavigationBarWidgetState extends State<BottomNavigationBarWidget> {
|
||||
int currentBottomNavBarIndex = 1;
|
||||
List<String>? pages;
|
||||
int? _pagesProfileId;
|
||||
bool? _pagesIsConsultant;
|
||||
int tapsCount = 0;
|
||||
|
||||
List<String> _getPages(bool isConsultant) {
|
||||
@@ -179,7 +181,16 @@ class _BottomNavigationBarWidgetState extends State<BottomNavigationBarWidget> {
|
||||
final isConsultant = profileModel.roles.contains('consultant');
|
||||
|
||||
// Инициализируем pages на основе profileModel
|
||||
pages ??= _getPages(isConsultant);
|
||||
if (pages == null ||
|
||||
_pagesProfileId != profileModel.id ||
|
||||
_pagesIsConsultant != isConsultant) {
|
||||
_pagesProfileId = profileModel.id;
|
||||
_pagesIsConsultant = isConsultant;
|
||||
pages = _getPages(isConsultant);
|
||||
if (currentBottomNavBarIndex >= pages!.length) {
|
||||
currentBottomNavBarIndex = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Expose tab switching to descendants (e.g. notification widget)
|
||||
final controller = BottomNavScope.maybeOf(context);
|
||||
|
||||
@@ -31,7 +31,9 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
||||
|
||||
StreamSubscription<ChannelReadEvent>? typingSubscription;
|
||||
StreamSubscription<ChannelReadEvent>? messagesSubscription;
|
||||
StreamSubscription<ChannelReadEvent>? _chosenPlanStateSubscription;
|
||||
StreamSubscription<void>? _reconnectSubscription;
|
||||
bool _isUpdatingChosenPlan = false;
|
||||
int currentPage = 1;
|
||||
late int lastPage;
|
||||
bool isLoading = false;
|
||||
@@ -171,6 +173,7 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
||||
log(e.toString());
|
||||
typingSubscription?.cancel();
|
||||
messagesSubscription?.cancel();
|
||||
_chosenPlanStateSubscription?.cancel();
|
||||
_reconnectSubscription?.cancel();
|
||||
_reconnectSubscription = null;
|
||||
wsManager.unsubscribeDirectChatChannel();
|
||||
@@ -260,19 +263,30 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
||||
}
|
||||
|
||||
Future<void> updateChosenPlanState() async {
|
||||
if (_isUpdatingChosenPlan) return;
|
||||
try {
|
||||
_isUpdatingChosenPlan = true;
|
||||
final currentState = state;
|
||||
if (currentState is! ChatRoomStateLoaded) {
|
||||
return;
|
||||
}
|
||||
final chosenPlanId = currentState.chatRoom.chosenPlanId;
|
||||
final chosenPlanId =
|
||||
currentState.chatRoom.chosenPlanId ??
|
||||
currentState.chatRoom.chosenPlan?.id;
|
||||
if (chosenPlanId == null) {
|
||||
return;
|
||||
}
|
||||
final chosenPlan = await chatRepository.getChosenPlan(id: chosenPlanId);
|
||||
_emitLoaded((latest) => latest.copyWith.chatRoom(chosenPlan: chosenPlan));
|
||||
if (isClosed) return;
|
||||
_emitLoaded(
|
||||
(latest) => latest.copyWith(
|
||||
chatRoom: latest.chatRoom.copyWith(chosenPlan: chosenPlan),
|
||||
),
|
||||
);
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
} finally {
|
||||
_isUpdatingChosenPlan = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,8 +352,10 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
||||
if (client == null) return;
|
||||
await messagesSubscription?.cancel();
|
||||
await typingSubscription?.cancel();
|
||||
await _chosenPlanStateSubscription?.cancel();
|
||||
messagesSubscription = null;
|
||||
typingSubscription = null;
|
||||
_chosenPlanStateSubscription = null;
|
||||
await wsManager.initPrivateDirectChatChannel(chatId);
|
||||
wsManager.subscribeDirectChatChannel();
|
||||
messagesSubscription = wsManager.directChatStream?.listen(
|
||||
@@ -361,6 +377,20 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
||||
),
|
||||
);
|
||||
});
|
||||
_chosenPlanStateSubscription = wsManager
|
||||
.chosenPlanStateChangedStream
|
||||
?.listen(
|
||||
(_) {
|
||||
EasyDebounce.debounce(
|
||||
'chosen-plan-state-changed',
|
||||
const Duration(milliseconds: 250),
|
||||
() => unawaited(updateChosenPlanState()),
|
||||
);
|
||||
},
|
||||
onError: (Object e, StackTrace st) {
|
||||
unawaited(reportFrom(e, st, this));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _onDirectChatEvent(ChannelReadEvent event) {
|
||||
@@ -731,6 +761,7 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
||||
Future<void> close() async {
|
||||
EasyDebounce.cancel('client-typing');
|
||||
EasyDebounce.cancel('searchChatRoom');
|
||||
EasyDebounce.cancel('chosen-plan-state-changed');
|
||||
if (_presenceOnlineListener != null) {
|
||||
wsManager.removePresenceDirectChatListener(_presenceOnlineListener!);
|
||||
_presenceOnlineListener = null;
|
||||
@@ -739,6 +770,7 @@ class ChatRoomCubit extends Cubit<ChatRoomState> {
|
||||
_timer?.cancel();
|
||||
await messagesSubscription?.cancel();
|
||||
await typingSubscription?.cancel();
|
||||
await _chosenPlanStateSubscription?.cancel();
|
||||
await _reconnectSubscription?.cancel();
|
||||
super.close();
|
||||
}
|
||||
|
||||
@@ -57,6 +57,17 @@ class ChatsCubit extends Cubit<ChatsState> {
|
||||
int page = 1;
|
||||
late int lastPage;
|
||||
|
||||
/// Clears all user-scoped state. WS subscriptions stay intact so that
|
||||
/// `getChatRoomsWithLoading` can re-load the new user's chats.
|
||||
void reset() {
|
||||
_query = null;
|
||||
page = 1;
|
||||
lastPage = 1;
|
||||
if (!isClosed) {
|
||||
emit(ChatsState());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> connectToWebSocket() async {
|
||||
try {
|
||||
await newIncomingMessagesSubscription?.cancel();
|
||||
|
||||
@@ -11,7 +11,6 @@ import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_
|
||||
import 'package:eatvio_app/features/chat/presentation/bloc/chat_room_cubit/chat_room_state.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/pages/photo_view_screen.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/widgets/about_order_button.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/widgets/chat_bubble_widget.dart';
|
||||
import 'package:eatvio_app/features/chat/models/chat_message_model.dart';
|
||||
import 'package:eatvio_app/features/chat/models/chat_user_model.dart';
|
||||
@@ -24,9 +23,11 @@ import 'package:eatvio_app/features/menu/presentation/blocked_user_cubit/blocked
|
||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/widgets/chat_user_online_status_line.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/utils/chat_banner_resolver.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/widgets/chat_consultation_header.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/widgets/notification_banner.dart';
|
||||
import 'package:eatvio_app/features/chat/utils/chat_counterpart_utils.dart';
|
||||
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
|
||||
import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart';
|
||||
import 'package:eatvio_app/features/order_info/presentation/info_by_order_screen.dart';
|
||||
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||
import 'package:eatvio_app/features/user_details/presentation/user_details_screen.dart';
|
||||
@@ -63,8 +64,6 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
final TextEditingController textEditingController = TextEditingController();
|
||||
final ChatRoomCubit chatRoomCubit = sl<ChatRoomCubit>();
|
||||
final List<int> unreadMessageIds = [];
|
||||
final showableChatBadgeStates =
|
||||
ChosenPlanStateEnum.getShowableChatBadgeStates();
|
||||
late AppLifecycleListener _listener;
|
||||
List<File> pickedFiles = [];
|
||||
|
||||
@@ -188,49 +187,24 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
ChosenPlanStateEnum.statePendingPayment,
|
||||
ChosenPlanStateEnum.stateInCoordination,
|
||||
].contains(chosenPlan?.chosenPlanState);
|
||||
PacketOptions? chosenOption;
|
||||
if (chosenPlan?.optionType == 'options1') {
|
||||
chosenOption = chosenPlan?.plan.packet1Options;
|
||||
} else if (chosenPlan?.optionType == 'options2') {
|
||||
chosenOption = chosenPlan?.plan.packet2Options;
|
||||
} else if (chosenPlan?.optionType == 'options3') {
|
||||
chosenOption = chosenPlan?.plan.packet3Options;
|
||||
}
|
||||
|
||||
final showAboutOrderButton =
|
||||
state.chatRoom.chosenPlan != null &&
|
||||
state.chatRoom.chosenPlan!.chosenPlanState !=
|
||||
final chosenOption = chosenPlan?.chosenOption;
|
||||
final progress = chosenPlan == null
|
||||
? null
|
||||
: mapConsultationProgress(
|
||||
state: chosenPlan.chosenPlanState,
|
||||
hasPersonalDiet: chosenOption?.hasPersonalDiet ?? false,
|
||||
personalDietName: chosenPlan.personalDietName,
|
||||
);
|
||||
final bannerType = resolveChatBanner(
|
||||
progress: progress,
|
||||
amIConsultant: amIConsultant,
|
||||
hasCard: state.hasCard,
|
||||
state: chosenPlan?.chosenPlanState,
|
||||
);
|
||||
final showInfoButton =
|
||||
chosenPlan != null &&
|
||||
chosenPlan.chosenPlanState !=
|
||||
ChosenPlanStateEnum.stateCanceledByTheInitiator;
|
||||
BannerType? bannerType;
|
||||
if (chosenPlan == null ||
|
||||
chosenPlan.chosenPlanState ==
|
||||
ChosenPlanStateEnum.stateCanceledByTheInitiator) {
|
||||
bannerType = null;
|
||||
} else if (amIConsultant &&
|
||||
!state.hasCard &&
|
||||
chosenPlan.chosenPlanState == ChosenPlanStateEnum.stateInCoordination) {
|
||||
bannerType = BannerType.card;
|
||||
} else if (amIConsultant &&
|
||||
chosenPlan.chosenPlanState == ChosenPlanStateEnum.stateInCoordination) {
|
||||
bannerType = BannerType.date;
|
||||
} else if (!amIConsultant &&
|
||||
(chosenPlan.chosenPlanState ==
|
||||
ChosenPlanStateEnum.stateStartDateHasBeenSet ||
|
||||
chosenPlan.chosenPlanState ==
|
||||
ChosenPlanStateEnum.statePendingPayment)) {
|
||||
bannerType = BannerType.payment;
|
||||
} else if (chosenPlan.chosenPlanState == ChosenPlanStateEnum.stateDone &&
|
||||
amIConsultant) {
|
||||
bannerType = BannerType.collectCharge;
|
||||
} else if (chosenPlan.chosenPlanState ==
|
||||
ChosenPlanStateEnum.stateLastDayFinished &&
|
||||
!amIConsultant) {
|
||||
bannerType = BannerType.finishPlan;
|
||||
} else if (chosenOption?.hasPersonalDiet == true &&
|
||||
amIConsultant &&
|
||||
chosenPlan.chosenPlanState != ChosenPlanStateEnum.stateDone) {
|
||||
bannerType = BannerType.setPersonalDiet;
|
||||
}
|
||||
|
||||
return Scaffold(
|
||||
resizeToAvoidBottomInset: true,
|
||||
@@ -340,6 +314,28 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (progress != null)
|
||||
ChatConsultationHeader(
|
||||
progress: progress,
|
||||
showInfoButton: showInfoButton,
|
||||
onInfoTap: () {
|
||||
if (amIConsultant) {
|
||||
GoRouter.of(context).push(
|
||||
InfoByOrderScreen.path,
|
||||
extra: {
|
||||
'planId': chosenPlan?.id,
|
||||
'customerSlug':
|
||||
state.chatRoom.users.receiver.slug,
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
GoRouter.of(context).push(
|
||||
InfoByOrderScreen.path,
|
||||
extra: {'planId': chosenPlan?.id},
|
||||
);
|
||||
},
|
||||
),
|
||||
Expanded(
|
||||
child: Container(
|
||||
color: appTheme.whiteA700,
|
||||
@@ -384,22 +380,9 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
final isPlanOrderMessage =
|
||||
message.type == ChatMessageType.planOrder;
|
||||
|
||||
PacketOptions? messageOption;
|
||||
if (isPlanOrderMessage &&
|
||||
chosenPlan != null) {
|
||||
if (chosenPlan.optionType == 'options1') {
|
||||
messageOption =
|
||||
chosenPlan.plan.packet1Options;
|
||||
} else if (chosenPlan.optionType ==
|
||||
'options2') {
|
||||
messageOption =
|
||||
chosenPlan.plan.packet2Options;
|
||||
} else if (chosenPlan.optionType ==
|
||||
'options3') {
|
||||
messageOption =
|
||||
chosenPlan.plan.packet3Options;
|
||||
}
|
||||
}
|
||||
final messageOption = isPlanOrderMessage
|
||||
? chosenPlan?.chosenOption
|
||||
: null;
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
@@ -450,21 +433,9 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
final isPlanOrderMessage =
|
||||
message.type == ChatMessageType.planOrder;
|
||||
|
||||
PacketOptions? messageOption;
|
||||
if (isPlanOrderMessage && chosenPlan != null) {
|
||||
if (chosenPlan.optionType == 'options1') {
|
||||
messageOption =
|
||||
chosenPlan.plan.packet1Options;
|
||||
} else if (chosenPlan.optionType ==
|
||||
'options2') {
|
||||
messageOption =
|
||||
chosenPlan.plan.packet2Options;
|
||||
} else if (chosenPlan.optionType ==
|
||||
'options3') {
|
||||
messageOption =
|
||||
chosenPlan.plan.packet3Options;
|
||||
}
|
||||
}
|
||||
final messageOption = isPlanOrderMessage
|
||||
? chosenPlan?.chosenOption
|
||||
: null;
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
@@ -804,30 +775,6 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
),
|
||||
],
|
||||
),
|
||||
if (showAboutOrderButton)
|
||||
Positioned(
|
||||
top: 8,
|
||||
right: 15,
|
||||
left: 16,
|
||||
child: AboutOrderButton(
|
||||
onTap: () async {
|
||||
if (amIConsultant) {
|
||||
GoRouter.of(context).push(
|
||||
InfoByOrderScreen.path,
|
||||
extra: {
|
||||
'planId': state.chatRoom.chosenPlan?.id,
|
||||
'customerSlug': state.chatRoom.users.receiver.slug,
|
||||
},
|
||||
);
|
||||
return;
|
||||
}
|
||||
GoRouter.of(context).push(
|
||||
InfoByOrderScreen.path,
|
||||
extra: {'planId': state.chatRoom.chosenPlan?.id},
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -135,9 +135,9 @@ class _EmptyChatScreenState extends State<EmptyChatScreen> {
|
||||
textEditingController.clear();
|
||||
});
|
||||
}
|
||||
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
||||
if (context.mounted) {
|
||||
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError});
|
||||
final chatId = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
||||
if (chatId != null && chatId.isNotEmpty && context.mounted) {
|
||||
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatId});
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -189,9 +189,9 @@ class _EmptyChatScreenState extends State<EmptyChatScreen> {
|
||||
if (images.isNotEmpty) {
|
||||
List<File> files = images.map((image) => File(image.path)).toList();
|
||||
await sl<ChatRepository>().sendMessage(files: files, slug: widget.user.slug);
|
||||
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
||||
if (mounted) {
|
||||
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError});
|
||||
final chatId = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
||||
if (chatId != null && chatId.isNotEmpty && mounted) {
|
||||
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatId});
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -205,9 +205,9 @@ class _EmptyChatScreenState extends State<EmptyChatScreen> {
|
||||
if (images.isNotEmpty) {
|
||||
List<File> files = images.map((image) => File(image.path)).toList();
|
||||
await sl<ChatRepository>().sendMessage(files: files, slug: widget.user.slug);
|
||||
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
||||
if (mounted) {
|
||||
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError});
|
||||
final chatId = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
||||
if (chatId != null && chatId.isNotEmpty && mounted) {
|
||||
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatId});
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -243,9 +243,9 @@ class _EmptyChatScreenState extends State<EmptyChatScreen> {
|
||||
if (result != null) {
|
||||
List<File> files = result.paths.map((path) => File(path!)).toList();
|
||||
await sl<ChatRepository>().sendMessage(files: files, slug: widget.user.slug);
|
||||
final chatIdOrError = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
||||
if (mounted) {
|
||||
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatIdOrError});
|
||||
final chatId = await sl<ChatRepository>().getChatByUserSlug(widget.user.slug);
|
||||
if (chatId != null && chatId.isNotEmpty && mounted) {
|
||||
AppRouter.navigatorKey.currentContext?.pushReplacementNamed('chatScreen', extra: {'uuid': chatId});
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import 'package:eatvio_app/features/chat/presentation/widgets/notification_banner.dart';
|
||||
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
|
||||
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||
|
||||
BannerType? resolveChatBanner({
|
||||
required ConsultationProgress? progress,
|
||||
required bool amIConsultant,
|
||||
required bool hasCard,
|
||||
required ChosenPlanStateEnum? state,
|
||||
}) {
|
||||
if (progress == null ||
|
||||
state == null ||
|
||||
progress.phase != ConsultationPhase.active) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (amIConsultant &&
|
||||
!hasCard &&
|
||||
state == ChosenPlanStateEnum.stateInCoordination) {
|
||||
return BannerType.card;
|
||||
}
|
||||
if (amIConsultant && state == ChosenPlanStateEnum.stateInCoordination) {
|
||||
return BannerType.date;
|
||||
}
|
||||
if (!amIConsultant &&
|
||||
(state == ChosenPlanStateEnum.stateStartDateHasBeenSet ||
|
||||
state == ChosenPlanStateEnum.statePendingPayment)) {
|
||||
return BannerType.payment;
|
||||
}
|
||||
if (state == ChosenPlanStateEnum.stateDone && amIConsultant) {
|
||||
return BannerType.collectCharge;
|
||||
}
|
||||
if (state == ChosenPlanStateEnum.stateLastDayFinished && !amIConsultant) {
|
||||
return BannerType.finishPlan;
|
||||
}
|
||||
if (!amIConsultant) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (state == ChosenPlanStateEnum.statePaid &&
|
||||
progress.dietStatus == PersonalDietStatus.notProposed) {
|
||||
return BannerType.setPersonalDiet;
|
||||
}
|
||||
if ((state == ChosenPlanStateEnum.personalDietSet ||
|
||||
state == ChosenPlanStateEnum.stateStarted ||
|
||||
state == ChosenPlanStateEnum.stateInProgress) &&
|
||||
progress.dietStatus == PersonalDietStatus.proposed) {
|
||||
return BannerType.changePersonalDiet;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
|
||||
import 'package:eatvio_app/features/consultations/presentation/widgets/consultation_progress_plank.dart';
|
||||
import 'package:eatvio_app/features/consultations/presentation/widgets/personal_diet_status_chip.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ChatConsultationHeader extends StatelessWidget {
|
||||
const ChatConsultationHeader({
|
||||
super.key,
|
||||
required this.progress,
|
||||
required this.showInfoButton,
|
||||
required this.onInfoTap,
|
||||
});
|
||||
|
||||
final ConsultationProgress progress;
|
||||
final bool showInfoButton;
|
||||
final VoidCallback onInfoTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final showPlank = progress.showProgressPlank;
|
||||
final showChip = progress.hasChip;
|
||||
if (!showPlank && !showChip && !showInfoButton) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
final s = S.of(context);
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.fromLTRB(16, 8, 16, 0),
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: appTheme.commentBg,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (progress.phase == ConsultationPhase.active || showPlank)
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
_title(s),
|
||||
style: TextStyles.textMMedium.copyWith(
|
||||
color: appTheme.black,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (showInfoButton)
|
||||
_InfoButton(
|
||||
onTap: onInfoTap,
|
||||
),
|
||||
],
|
||||
)
|
||||
else if (showInfoButton)
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: _InfoButton(
|
||||
onTap: onInfoTap,
|
||||
),
|
||||
),
|
||||
if (showPlank) ...[
|
||||
const SizedBox(height: 8),
|
||||
ConsultationProgressPlank(progress: progress),
|
||||
],
|
||||
if (showChip) ...[
|
||||
const SizedBox(height: 8),
|
||||
PersonalDietStatusChip(progress: progress),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _title(S s) {
|
||||
if (progress.isCanceled) return s.orderCanceled;
|
||||
if (progress.isPaymentFailed) return s.payment_failed;
|
||||
if (progress.isStepCompleted(ConsultationStep.finished)) return s.done;
|
||||
if (progress.showProgressPlank) return s.order_in_progress;
|
||||
return s.more_about_order;
|
||||
}
|
||||
}
|
||||
|
||||
class _InfoButton extends StatelessWidget {
|
||||
const _InfoButton({required this.onTap});
|
||||
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return InkWell(
|
||||
onTap: onTap,
|
||||
customBorder: const CircleBorder(),
|
||||
child: Container(
|
||||
width: 32,
|
||||
height: 32,
|
||||
decoration: BoxDecoration(
|
||||
color: appTheme.whiteA700,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
Icons.info_outline_rounded,
|
||||
size: 18,
|
||||
color: appTheme.blueA400,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -106,7 +106,11 @@ class _NotificationBannerState extends State<NotificationBanner> {
|
||||
onTap: () {
|
||||
final planId = (context.read<ChatRoomCubit>().state as ChatRoomStateLoaded).chatRoom.chosenPlan?.id;
|
||||
if (planId != null) {
|
||||
showConsultationPaymentFlow(context, planId: planId);
|
||||
showConsultationPaymentFlow(
|
||||
context,
|
||||
planId: planId,
|
||||
amount: widget.planPrice,
|
||||
);
|
||||
}
|
||||
},
|
||||
child: Text(s.pay, style: TextStyles.textLSemibold.copyWith(color: appTheme.blueA400)),
|
||||
@@ -142,12 +146,37 @@ class _NotificationBannerState extends State<NotificationBanner> {
|
||||
BannerType.setPersonalDiet => [
|
||||
SizedBox(
|
||||
width: size.width * 0.6,
|
||||
child: Text(s.createPersonalDiet, style: TextStyles.textMMedium.copyWith(color: appTheme.black)),
|
||||
child: Text(s.suggestDiet, style: TextStyles.textMMedium.copyWith(color: appTheme.black)),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
GestureDetector(
|
||||
onTap: () {
|
||||
GoRouter.of(context).pushNamed(MyDietsScreen.name);
|
||||
GoRouter.of(context).pushNamed(
|
||||
MyDietsScreen.name,
|
||||
queryParameters: {'initialTabIndex': '2'},
|
||||
);
|
||||
},
|
||||
child: Text(s.goToMyDiets, style: TextStyles.textLSemibold.copyWith(color: appTheme.blueA400)),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
BannerType.changePersonalDiet => [
|
||||
SizedBox(
|
||||
width: size.width * 0.6,
|
||||
child: Text(s.change_personal_diet, style: TextStyles.textMMedium.copyWith(color: appTheme.black)),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
SizedBox(
|
||||
width: size.width * 0.6,
|
||||
child: Text(s.personal_diet_replaces_tomorrow, style: TextStyles.textSMedium.copyWith(color: appTheme.black)),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
GestureDetector(
|
||||
onTap: () {
|
||||
GoRouter.of(context).pushNamed(
|
||||
MyDietsScreen.name,
|
||||
queryParameters: {'initialTabIndex': '2'},
|
||||
);
|
||||
},
|
||||
child: Text(s.goToMyDiets, style: TextStyles.textLSemibold.copyWith(color: appTheme.blueA400)),
|
||||
),
|
||||
@@ -240,4 +269,4 @@ class _StarIcon extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
enum BannerType { date, card, payment, collectCharge, finishPlan, setPersonalDiet }
|
||||
enum BannerType { date, card, payment, collectCharge, finishPlan, setPersonalDiet, changePersonalDiet }
|
||||
|
||||
@@ -137,11 +137,12 @@ class ChatRepository {
|
||||
|
||||
}
|
||||
|
||||
Future<String> getChatByUserSlug(String slug) async {
|
||||
Future<String?> getChatByUserSlug(String slug) async {
|
||||
final response = await chatService.getChatByUserSlug(slug: slug);
|
||||
if (response.response.statusCode == 404) {
|
||||
return '404';
|
||||
final data = response.data;
|
||||
if (data is Map && data['id'] is String && (data['id'] as String).isNotEmpty) {
|
||||
return data['id'] as String;
|
||||
}
|
||||
return response.data['id'];
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ class BecomeConsultantScreen extends StatefulWidget {
|
||||
class _BecomeConsultantScreenState extends State<BecomeConsultantScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Стать консультантом'),
|
||||
@@ -24,14 +26,18 @@ class _BecomeConsultantScreenState extends State<BecomeConsultantScreen> {
|
||||
icon: const Icon(Icons.close),
|
||||
),
|
||||
),
|
||||
body: const Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Text(
|
||||
body: SingleChildScrollView(
|
||||
physics: const BouncingScrollPhysics(),
|
||||
padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + 52 + 8 + bottomInset),
|
||||
child: const Text(
|
||||
'Чтобы стать консультантом необходимо пройти короткую регистрацию. Подготовьте свои дипломы и/или сертификаты в формате jpg, они Вам пригодятся для проверки и подтверждения. Также необходимо будет указать ссылки на Ваши соц. сети и указать тип лица (физ. лицо или юр. лицо). На данный момент доступна регистрация в качестве физ. лица.\n\nВнутри Итвио разница между обычным пользователем и консультантом заключается в дополнительных возможностях последнего создавать публичные диеты, рецепты и планы питания; участвовать в ежемесячных рейтингах.',
|
||||
style: TextStyle(fontSize: 16),
|
||||
),
|
||||
),
|
||||
bottomSheet: _startRegistrationButton(),
|
||||
bottomSheet: Padding(
|
||||
padding: EdgeInsets.fromLTRB(16, 0, 16, 8 + bottomInset),
|
||||
child: _startRegistrationButton(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -44,7 +50,7 @@ class _BecomeConsultantScreenState extends State<BecomeConsultantScreen> {
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
child: Ink(
|
||||
height: 52,
|
||||
width: MediaQuery.of(context).size.width - 32,
|
||||
width: double.infinity,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
color: appTheme.blueA400,
|
||||
|
||||
@@ -9,6 +9,7 @@ part 'consultation_model.g.dart';
|
||||
abstract class ConsultationModel with _$ConsultationModel {
|
||||
factory ConsultationModel({
|
||||
required int id,
|
||||
@JsonKey(name: 'chat_id') String? chatId,
|
||||
@JsonKey(name: 'last_state') required ChosenPlanStateEnum chosenPlanState,
|
||||
@JsonKey(name: 'plan_title') required String planTitle,
|
||||
@JsonKey(name: 'user_name') required String userName,
|
||||
@@ -19,10 +20,11 @@ abstract class ConsultationModel with _$ConsultationModel {
|
||||
@JsonKey(name: 'user_profile_photo_url') required String userProfilePhotoUrl,
|
||||
@JsonKey(name: 'consultation_option_price') required int consultationOptionPrice,
|
||||
@JsonKey(name: 'start_date', fromJson: parseDate) required DateTime startDate,
|
||||
@JsonKey(name: 'end_date', fromJson: parseDate) required DateTime endDate,
|
||||
@JsonKey(name: 'end_date', fromJson: parseDateOrNull) DateTime? endDate,
|
||||
@JsonKey(name: 'consultant_id') required int consultantId,
|
||||
required List<DiaryModel> diaries,
|
||||
@JsonKey(name: 'personal_diet_id') required int? personalDietId,
|
||||
@JsonKey(name: 'personal_diet_name') String? personalDietName,
|
||||
}) = _ConsultationModel;
|
||||
|
||||
factory ConsultationModel.fromJson(Map<String, dynamic> json) => _$ConsultationModelFromJson(json);
|
||||
@@ -39,6 +41,11 @@ abstract class DiaryModel with _$DiaryModel {
|
||||
factory DiaryModel.fromJson(Map<String, dynamic> json) => _$DiaryModelFromJson(json);
|
||||
}
|
||||
|
||||
DateTime? parseDateOrNull(dynamic date) {
|
||||
if (date == null) return null;
|
||||
return parseDate(date as String);
|
||||
}
|
||||
|
||||
DateTime parseUnformattedDate(String date) {
|
||||
final dateChunks = date.split('-').map(int.parse).toList();
|
||||
|
||||
|
||||
33
lib/features/consultations/models/consultation_progress.dart
Normal file
33
lib/features/consultations/models/consultation_progress.dart
Normal file
@@ -0,0 +1,33 @@
|
||||
enum ConsultationStep { startDate, paid, inProgress, finished }
|
||||
|
||||
enum PersonalDietStatus { notRequired, notProposed, proposed }
|
||||
|
||||
enum ConsultationPhase { active, canceled, paymentFailed }
|
||||
|
||||
class ConsultationProgress {
|
||||
const ConsultationProgress({
|
||||
required this.completedSteps,
|
||||
required this.showProgressPlank,
|
||||
required this.dietStatus,
|
||||
required this.phase,
|
||||
this.personalDietName,
|
||||
});
|
||||
|
||||
final Set<ConsultationStep> completedSteps;
|
||||
final bool showProgressPlank;
|
||||
final PersonalDietStatus dietStatus;
|
||||
final ConsultationPhase phase;
|
||||
final String? personalDietName;
|
||||
|
||||
bool isStepCompleted(ConsultationStep step) => completedSteps.contains(step);
|
||||
|
||||
bool get hasDietChip => dietStatus != PersonalDietStatus.notRequired;
|
||||
|
||||
bool get hasStatusChip => phase != ConsultationPhase.active;
|
||||
|
||||
bool get hasChip => hasDietChip || hasStatusChip;
|
||||
|
||||
bool get isCanceled => phase == ConsultationPhase.canceled;
|
||||
|
||||
bool get isPaymentFailed => phase == ConsultationPhase.paymentFailed;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:eatvio_app/core/enums/base_state.dart';
|
||||
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
|
||||
import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_state.dart';
|
||||
import 'package:eatvio_app/features/consultations/repositories/consultations_repository.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
@@ -8,7 +9,8 @@ import 'package:eatvio_app/core/error_reporting/report_from.dart';
|
||||
|
||||
class ConsultationsCubit extends Cubit<ConsultationsState> {
|
||||
final ConsultationsRepository consultationsRepository;
|
||||
ConsultationsCubit({required this.consultationsRepository}) : super(ConsultationsState());
|
||||
final ChatRepository chatRepository;
|
||||
ConsultationsCubit({required this.consultationsRepository, required this.chatRepository}) : super(ConsultationsState());
|
||||
|
||||
Future<void> loadConsultations() async {
|
||||
try {
|
||||
@@ -20,4 +22,14 @@ class ConsultationsCubit extends Cubit<ConsultationsState> {
|
||||
emit(state.copyWith(state: BaseState.error));
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> getChatIdByUserSlug(String slug) async {
|
||||
try {
|
||||
return await chatRepository.getChatByUserSlug(slug);
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
log(e.toString(), stackTrace: st);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,14 +3,17 @@ import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/widgets/custom_divider.dart';
|
||||
import 'package:eatvio_app/core/widgets/custom_outlined_button.dart';
|
||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||
import 'package:eatvio_app/core/widgets/show_error_dialog.dart';
|
||||
import 'package:eatvio_app/features/consultations/models/consultation_model.dart';
|
||||
import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_cubit.dart';
|
||||
import 'package:eatvio_app/features/diary/presentation/pages/diary_screen.dart';
|
||||
import 'package:eatvio_app/features/my_finance/presentation/pages/card_settings.dart';
|
||||
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||
import 'package:eatvio_app/features/user_details/presentation/user_details_screen.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';
|
||||
|
||||
class ConsultationCardWidget extends StatefulWidget {
|
||||
@@ -34,6 +37,7 @@ class _ConsultationCardWidgetState extends State<ConsultationCardWidget> {
|
||||
final List<Color> legendColors = const [Colors.white, Color(0xFFF0C497), Color(0xFFFF9500), Color(0xFF2F80ED), Color(0xFF4CD964)];
|
||||
|
||||
late final List<(int, DiaryModel)> givenDaysWithDayNumber;
|
||||
bool _isOpeningChat = false;
|
||||
final List<List<DiaryStateEnum>> legendStates = [
|
||||
[DiaryStateEnum.init],
|
||||
[DiaryStateEnum.started, DiaryStateEnum.lastDayStarted],
|
||||
@@ -81,6 +85,30 @@ class _ConsultationCardWidgetState extends State<ConsultationCardWidget> {
|
||||
widget.consultationsModel.planTitle,
|
||||
style: const TextStyle(height: 1, color: Color(0xFF88949F), fontSize: 14, fontWeight: FontWeight.w500),
|
||||
),
|
||||
if (widget.consultationsModel.personalDietId != null) ...[
|
||||
const SizedBox(height: 4),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 4,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: appTheme.transparentGreen,
|
||||
borderRadius: BorderRadius.circular(100),
|
||||
),
|
||||
child: Text(
|
||||
widget.consultationsModel.personalDietName == null ||
|
||||
widget.consultationsModel.personalDietName!.isEmpty
|
||||
? s.personal_diet_proposed
|
||||
: s.personal_diet_proposed_named(
|
||||
widget.consultationsModel.personalDietName!,
|
||||
),
|
||||
style: TextStyles.textXSSemibold.copyWith(
|
||||
color: appTheme.greenA700,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
@@ -279,7 +307,7 @@ class _ConsultationCardWidgetState extends State<ConsultationCardWidget> {
|
||||
const SizedBox(width: 8),
|
||||
InkWell(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
onTap: () {},
|
||||
onTap: _isOpeningChat ? null : _openChat,
|
||||
child: Ink(
|
||||
height: 52,
|
||||
width: 52,
|
||||
@@ -308,6 +336,22 @@ class _ConsultationCardWidgetState extends State<ConsultationCardWidget> {
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _openChat() async {
|
||||
if (_isOpeningChat) return;
|
||||
setState(() => _isOpeningChat = true);
|
||||
var chatId = widget.consultationsModel.chatId;
|
||||
if (chatId == null || chatId.isEmpty) {
|
||||
chatId = await context.read<ConsultationsCubit>().getChatIdByUserSlug(widget.consultationsModel.userSlug);
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() => _isOpeningChat = false);
|
||||
if (chatId == null || chatId.isEmpty) {
|
||||
showErrorToast(S.of(context).msg_something_went_wrong);
|
||||
return;
|
||||
}
|
||||
GoRouter.of(context).pushNamed('chatScreen', extra: {'uuid': chatId});
|
||||
}
|
||||
|
||||
Row _legendTitle(String text, Color color) {
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ConsultationProgressPlank extends StatelessWidget {
|
||||
const ConsultationProgressPlank({super.key, required this.progress});
|
||||
|
||||
final ConsultationProgress progress;
|
||||
|
||||
static const _steps = [
|
||||
ConsultationStep.startDate,
|
||||
ConsultationStep.paid,
|
||||
ConsultationStep.inProgress,
|
||||
ConsultationStep.finished,
|
||||
];
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!progress.showProgressPlank) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
for (var index = 0; index < _steps.length; index++)
|
||||
Expanded(
|
||||
child: Column(
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Container(
|
||||
height: 2,
|
||||
color: index == 0
|
||||
? Colors.transparent
|
||||
: progress.isStepCompleted(_steps[index - 1])
|
||||
? appTheme.greenA700
|
||||
: appTheme.lightGray00,
|
||||
),
|
||||
),
|
||||
_ProgressStepCircle(
|
||||
key: ValueKey('consultation_step_circle_$index'),
|
||||
index: index,
|
||||
isCompleted: progress.isStepCompleted(_steps[index]),
|
||||
),
|
||||
Expanded(
|
||||
child: Container(
|
||||
height: 2,
|
||||
color: index == _steps.length - 1
|
||||
? Colors.transparent
|
||||
: progress.isStepCompleted(_steps[index])
|
||||
? appTheme.greenA700
|
||||
: appTheme.lightGray00,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
_stepLabel(S.of(context), _steps[index]),
|
||||
key: ValueKey('consultation_step_label_$index'),
|
||||
textAlign: TextAlign.center,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyles.textFS10FW500.copyWith(
|
||||
color: progress.isStepCompleted(_steps[index])
|
||||
? appTheme.black
|
||||
: appTheme.gray,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _stepLabel(S s, ConsultationStep step) {
|
||||
switch (step) {
|
||||
case ConsultationStep.startDate:
|
||||
return s.startDateHasBeenSet;
|
||||
case ConsultationStep.paid:
|
||||
return s.order_paid;
|
||||
case ConsultationStep.inProgress:
|
||||
return s.order_in_progress;
|
||||
case ConsultationStep.finished:
|
||||
return s.done;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _ProgressStepCircle extends StatelessWidget {
|
||||
const _ProgressStepCircle({
|
||||
super.key,
|
||||
required this.index,
|
||||
required this.isCompleted,
|
||||
});
|
||||
|
||||
final int index;
|
||||
final bool isCompleted;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
width: 24,
|
||||
height: 24,
|
||||
alignment: Alignment.center,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: isCompleted ? appTheme.greenA700 : appTheme.lightGray00,
|
||||
),
|
||||
child: isCompleted
|
||||
? Icon(Icons.check, size: 14, color: appTheme.whiteA700)
|
||||
: Text(
|
||||
'${index + 1}',
|
||||
style: TextStyles.textFS10FW500.copyWith(color: appTheme.gray),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class PersonalDietStatusChip extends StatelessWidget {
|
||||
const PersonalDietStatusChip({super.key, required this.progress});
|
||||
|
||||
final ConsultationProgress progress;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!progress.hasChip) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
final s = S.of(context);
|
||||
final (label, background, foreground) = _chipStyle(s);
|
||||
|
||||
return Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: background,
|
||||
borderRadius: BorderRadius.circular(100),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyles.textXSSemibold.copyWith(color: foreground),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
(String, Color, Color) _chipStyle(S s) {
|
||||
if (progress.isCanceled) {
|
||||
return (s.orderCanceled, appTheme.lightRed, appTheme.red);
|
||||
}
|
||||
if (progress.isPaymentFailed) {
|
||||
return (s.payment_failed, appTheme.lightRed, appTheme.red);
|
||||
}
|
||||
if (progress.dietStatus == PersonalDietStatus.proposed) {
|
||||
final dietName = progress.personalDietName;
|
||||
final label = dietName == null || dietName.isEmpty
|
||||
? s.personal_diet_proposed
|
||||
: s.personal_diet_proposed_named(dietName);
|
||||
return (
|
||||
label,
|
||||
appTheme.transparentGreen,
|
||||
appTheme.greenA700,
|
||||
);
|
||||
}
|
||||
return (
|
||||
s.personal_diet_not_proposed,
|
||||
appTheme.gray100,
|
||||
appTheme.gray,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
|
||||
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||
|
||||
ConsultationProgress mapConsultationProgress({
|
||||
required ChosenPlanStateEnum state,
|
||||
required bool hasPersonalDiet,
|
||||
String? personalDietName,
|
||||
}) {
|
||||
return ConsultationProgress(
|
||||
completedSteps: _completedSteps(state),
|
||||
showProgressPlank: _showProgressPlank(state),
|
||||
dietStatus: _dietStatus(state, hasPersonalDiet),
|
||||
phase: _phase(state),
|
||||
personalDietName: personalDietName,
|
||||
);
|
||||
}
|
||||
|
||||
Set<ConsultationStep> _completedSteps(ChosenPlanStateEnum state) {
|
||||
switch (state) {
|
||||
case ChosenPlanStateEnum.stateInited:
|
||||
case ChosenPlanStateEnum.stateConfirmedByConsultant:
|
||||
case ChosenPlanStateEnum.stateInCoordination:
|
||||
case ChosenPlanStateEnum.stateCanceledByTheInitiator:
|
||||
return const {};
|
||||
case ChosenPlanStateEnum.stateStartDateHasBeenSet:
|
||||
case ChosenPlanStateEnum.statePendingPayment:
|
||||
case ChosenPlanStateEnum.statePaymentFailed:
|
||||
return const {ConsultationStep.startDate};
|
||||
case ChosenPlanStateEnum.statePaid:
|
||||
case ChosenPlanStateEnum.personalDietSet:
|
||||
return const {ConsultationStep.startDate, ConsultationStep.paid};
|
||||
case ChosenPlanStateEnum.stateStarted:
|
||||
case ChosenPlanStateEnum.stateInProgress:
|
||||
case ChosenPlanStateEnum.stateLastDayStarted:
|
||||
case ChosenPlanStateEnum.stateLastDayFinished:
|
||||
case ChosenPlanStateEnum.stateComplained:
|
||||
return const {
|
||||
ConsultationStep.startDate,
|
||||
ConsultationStep.paid,
|
||||
ConsultationStep.inProgress,
|
||||
};
|
||||
case ChosenPlanStateEnum.stateDone:
|
||||
case ChosenPlanStateEnum.stateChargeWasCollected:
|
||||
return const {
|
||||
ConsultationStep.startDate,
|
||||
ConsultationStep.paid,
|
||||
ConsultationStep.inProgress,
|
||||
ConsultationStep.finished,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
bool _showProgressPlank(ChosenPlanStateEnum state) {
|
||||
switch (state) {
|
||||
case ChosenPlanStateEnum.stateInited:
|
||||
case ChosenPlanStateEnum.stateConfirmedByConsultant:
|
||||
case ChosenPlanStateEnum.stateChargeWasCollected:
|
||||
case ChosenPlanStateEnum.stateCanceledByTheInitiator:
|
||||
case ChosenPlanStateEnum.statePaymentFailed:
|
||||
return false;
|
||||
case ChosenPlanStateEnum.stateInCoordination:
|
||||
case ChosenPlanStateEnum.stateStartDateHasBeenSet:
|
||||
case ChosenPlanStateEnum.statePendingPayment:
|
||||
case ChosenPlanStateEnum.statePaid:
|
||||
case ChosenPlanStateEnum.personalDietSet:
|
||||
case ChosenPlanStateEnum.stateStarted:
|
||||
case ChosenPlanStateEnum.stateInProgress:
|
||||
case ChosenPlanStateEnum.stateLastDayStarted:
|
||||
case ChosenPlanStateEnum.stateLastDayFinished:
|
||||
case ChosenPlanStateEnum.stateComplained:
|
||||
case ChosenPlanStateEnum.stateDone:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
PersonalDietStatus _dietStatus(
|
||||
ChosenPlanStateEnum state,
|
||||
bool hasPersonalDiet,
|
||||
) {
|
||||
if (!hasPersonalDiet) {
|
||||
return PersonalDietStatus.notRequired;
|
||||
}
|
||||
|
||||
switch (state) {
|
||||
case ChosenPlanStateEnum.personalDietSet:
|
||||
case ChosenPlanStateEnum.stateStarted:
|
||||
case ChosenPlanStateEnum.stateInProgress:
|
||||
case ChosenPlanStateEnum.stateLastDayStarted:
|
||||
case ChosenPlanStateEnum.stateLastDayFinished:
|
||||
case ChosenPlanStateEnum.stateComplained:
|
||||
case ChosenPlanStateEnum.stateDone:
|
||||
case ChosenPlanStateEnum.stateChargeWasCollected:
|
||||
return PersonalDietStatus.proposed;
|
||||
case ChosenPlanStateEnum.stateInited:
|
||||
case ChosenPlanStateEnum.stateInCoordination:
|
||||
case ChosenPlanStateEnum.stateConfirmedByConsultant:
|
||||
case ChosenPlanStateEnum.stateStartDateHasBeenSet:
|
||||
case ChosenPlanStateEnum.statePendingPayment:
|
||||
case ChosenPlanStateEnum.statePaid:
|
||||
return PersonalDietStatus.notProposed;
|
||||
case ChosenPlanStateEnum.stateCanceledByTheInitiator:
|
||||
case ChosenPlanStateEnum.statePaymentFailed:
|
||||
return PersonalDietStatus.notRequired;
|
||||
}
|
||||
}
|
||||
|
||||
ConsultationPhase _phase(ChosenPlanStateEnum state) {
|
||||
switch (state) {
|
||||
case ChosenPlanStateEnum.stateCanceledByTheInitiator:
|
||||
return ConsultationPhase.canceled;
|
||||
case ChosenPlanStateEnum.statePaymentFailed:
|
||||
return ConsultationPhase.paymentFailed;
|
||||
default:
|
||||
return ConsultationPhase.active;
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/widgets/custom_divider.dart';
|
||||
import 'package:eatvio_app/features/diary/presentation/bloc/diary_cubit.dart';
|
||||
import 'package:eatvio_app/features/diary/presentation/bloc/diary_state.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';
|
||||
@@ -19,9 +18,7 @@ class ChosenDietWidget extends StatelessWidget {
|
||||
if (state is DiaryStateLoaded) {
|
||||
if (state.diary.typeOfDiary.hasChosenDiet) {
|
||||
return ChosenDietWidgetContent(
|
||||
currentDietDay: state.diary.dayOfChosenDiet ?? 0,
|
||||
dietName: state.diary.diet?.name ?? '',
|
||||
dietDuration: state.diary.diet?.duration ?? 0,
|
||||
dietId: state.diary.diet?.id ?? 0,
|
||||
);
|
||||
}
|
||||
@@ -33,9 +30,7 @@ class ChosenDietWidget extends StatelessWidget {
|
||||
const CustomDivider(),
|
||||
const SizedBox(height: 16),
|
||||
ChosenDietWidgetContent(
|
||||
currentDietDay: state.diary.dayOfChosenDiet ?? 0,
|
||||
dietName: state.diary.diet?.name ?? '',
|
||||
dietDuration: state.diary.diet?.duration ?? 0,
|
||||
dietId: state.diary.diet?.id ?? 0,
|
||||
),
|
||||
],
|
||||
@@ -50,15 +45,11 @@ class ChosenDietWidget extends StatelessWidget {
|
||||
}
|
||||
|
||||
class ChosenDietWidgetContent extends StatelessWidget {
|
||||
const ChosenDietWidgetContent({super.key, required this.currentDietDay, required this.dietName, required this.dietDuration, required this.dietId});
|
||||
final int currentDietDay;
|
||||
const ChosenDietWidgetContent({super.key, required this.dietName, required this.dietId});
|
||||
final String dietName;
|
||||
final int dietDuration;
|
||||
final int dietId;
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final size = MediaQuery.sizeOf(context);
|
||||
final s = S.of(context);
|
||||
return GestureDetector(
|
||||
onTap: () {
|
||||
GoRouter.of(context).push(RouteConstants.aboutDietScreen, extra: {'id': dietId, 'navigateToComments': false});
|
||||
@@ -67,19 +58,12 @@ class ChosenDietWidgetContent extends StatelessWidget {
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: size.width * 0.4,
|
||||
Expanded(
|
||||
child: Text(
|
||||
dietName,
|
||||
style: TextStyles.textLMedium.copyWith(color: appTheme.black, decoration: TextDecoration.underline),
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
Container(
|
||||
decoration: BoxDecoration(color: appTheme.dividerColor, borderRadius: BorderRadius.circular(12)),
|
||||
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 12),
|
||||
child: Text('${s.day} $currentDietDay из $dietDuration', style: TextStyles.textMSemibold.copyWith(color: appTheme.gray)),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
@@ -12,9 +12,19 @@ class FeedCubit extends Cubit<FeedState> {
|
||||
bool _hasMore = true;
|
||||
bool isLoading = false;
|
||||
String? _query;
|
||||
int _requestId = 0;
|
||||
|
||||
FeedCubit({required this.feedRepository}) : super(const FeedState.loading());
|
||||
|
||||
void reset() {
|
||||
_requestId++;
|
||||
_nextCursor = null;
|
||||
_hasMore = true;
|
||||
isLoading = false;
|
||||
_query = null;
|
||||
if (!isClosed) emit(const FeedState.loading());
|
||||
}
|
||||
|
||||
void updateFeedBlogPostList(FeedBlogPostModel? feedBlogPostModel, bool wasLikedByMe) {
|
||||
if (feedBlogPostModel == null || isClosed || state is! FeedStateLoaded) return;
|
||||
final List<FeedBlogPostModel> feedBlogPostList = [...(state as FeedStateLoaded).feedBlogPostList];
|
||||
@@ -39,17 +49,18 @@ class FeedCubit extends Cubit<FeedState> {
|
||||
}
|
||||
|
||||
Future<void> loadFeedBlogPostList({String? query, int? currentUserId}) async {
|
||||
final requestId = ++_requestId;
|
||||
try {
|
||||
_query = query;
|
||||
_nextCursor = null;
|
||||
_hasMore = true;
|
||||
final feed = await feedRepository.getFeed(search: query, currentUserId: currentUserId);
|
||||
if (isClosed || requestId != _requestId) return;
|
||||
_nextCursor = feed.nextCursor;
|
||||
_hasMore = _nextCursor != null;
|
||||
if (!isClosed) {
|
||||
emit(FeedState.loaded(feedBlogPostList: feed.posts, isLoading: false));
|
||||
}
|
||||
emit(FeedState.loaded(feedBlogPostList: feed.posts, isLoading: false));
|
||||
} catch (e, st) {
|
||||
if (isClosed || requestId != _requestId) return;
|
||||
await reportFrom(e, st, this);
|
||||
if (!isClosed) {
|
||||
emit(FeedState.error(errorMessage: e.toString()));
|
||||
@@ -62,14 +73,16 @@ class FeedCubit extends Cubit<FeedState> {
|
||||
return;
|
||||
}
|
||||
|
||||
final requestId = _requestId;
|
||||
isLoading = true;
|
||||
emit((state as FeedStateLoaded).copyWith(isLoading: true));
|
||||
|
||||
try {
|
||||
final feed = await feedRepository.getFeed(search: _query, cursor: _nextCursor, currentUserId: currentUserId);
|
||||
if (isClosed || requestId != _requestId) return;
|
||||
_nextCursor = feed.nextCursor;
|
||||
_hasMore = _nextCursor != null;
|
||||
if (!isClosed && state is FeedStateLoaded) {
|
||||
if (state is FeedStateLoaded) {
|
||||
emit(
|
||||
FeedState.loaded(
|
||||
feedBlogPostList: [...(state as FeedStateLoaded).feedBlogPostList, ...feed.posts],
|
||||
@@ -78,14 +91,15 @@ class FeedCubit extends Cubit<FeedState> {
|
||||
);
|
||||
}
|
||||
} catch (e, st) {
|
||||
if (isClosed || requestId != _requestId) return;
|
||||
await reportFrom(e, st, this);
|
||||
if (!isClosed && state is FeedStateLoaded) {
|
||||
if (state is FeedStateLoaded) {
|
||||
emit((state as FeedStateLoaded).copyWith(isLoading: false));
|
||||
} else if (!isClosed) {
|
||||
} else {
|
||||
emit(FeedState.error(errorMessage: e.toString()));
|
||||
}
|
||||
} finally {
|
||||
isLoading = false;
|
||||
if (requestId == _requestId) isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||
import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_state.dart';
|
||||
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
@@ -7,7 +8,11 @@ import 'package:eatvio_app/core/error_reporting/report_from.dart';
|
||||
|
||||
class MenuCubit extends Cubit<MenuState> {
|
||||
final ProfileRepository profileRepository;
|
||||
MenuCubit(this.profileRepository) : super(const MenuState.initial());
|
||||
final SessionLifecycleService sessionLifecycleService;
|
||||
MenuCubit(this.profileRepository, this.sessionLifecycleService)
|
||||
: super(const MenuState.initial());
|
||||
|
||||
Future<void> logout() => sessionLifecycleService.logout();
|
||||
|
||||
Future<void> getMyProfile() async {
|
||||
emit(const MenuState.loading());
|
||||
@@ -23,7 +28,10 @@ class MenuCubit extends Cubit<MenuState> {
|
||||
|
||||
Future<String?> makePassKey() async {
|
||||
try {
|
||||
final passKey = await profileRepository.getPassKey(routeName: 'product_nutritional_value.index', routeParams: {});
|
||||
final passKey = await profileRepository.getPassKey(
|
||||
routeName: 'product_nutritional_value.index',
|
||||
routeParams: {},
|
||||
);
|
||||
return passKey;
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
|
||||
@@ -1,26 +1,20 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/app_config.dart';
|
||||
import 'package:eatvio_app/core/error_reporting/error_reporter.dart';
|
||||
import 'package:eatvio_app/core/const.dart';
|
||||
import 'package:eatvio_app/core/firebase_api.dart';
|
||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/core/utils/image_constant.dart';
|
||||
import 'package:eatvio_app/core/utils/date_time_utils.dart';
|
||||
import 'package:eatvio_app/core/widgets/data_error_widget.dart';
|
||||
import 'package:eatvio_app/core/widgets/loader.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
||||
import 'package:eatvio_app/features/consultant_rating/presentation/consultant_rating_screen.dart';
|
||||
import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/consultant_finances_screen.dart';
|
||||
import 'package:eatvio_app/features/finances_and_consultations_archive/presentation/user_purchases_screen.dart';
|
||||
import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_cubit.dart';
|
||||
import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart';
|
||||
import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_state.dart';
|
||||
import 'package:eatvio_app/features/my_diets/presentation/my_diets_screen.dart';
|
||||
import 'package:eatvio_app/features/my_plans/presentation/my_plans_screen.dart';
|
||||
import 'package:eatvio_app/features/recipe/presentation/pages/my_recipes_screen.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recordings_screen.dart';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
@@ -56,6 +50,12 @@ class MenuScreen extends StatelessWidget {
|
||||
if (profileModel.roles.contains('consultant')) _divider(context),
|
||||
if (profileModel.roles.contains('consultant'))
|
||||
_tile(leading: ImageConstant.icnPlans, title: 'Мои планы', onTap: () => GoRouter.of(context).push(MyPlansScreen.path)),
|
||||
_divider(context),
|
||||
_tile(
|
||||
leading: ImageConstant.icnConsultation,
|
||||
title: 'Мои консультации',
|
||||
onTap: () => GoRouter.of(context).push(VideoCallRecordingsScreen.path),
|
||||
),
|
||||
if (!hidePlans) ...[
|
||||
_divider(context),
|
||||
_tile(
|
||||
@@ -155,6 +155,7 @@ class MenuScreen extends StatelessWidget {
|
||||
|
||||
Future<Null> Function() _onTapLogout(BuildContext context) {
|
||||
return () async {
|
||||
final menuCubit = context.read<MenuCubit>();
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => CupertinoAlertDialog(
|
||||
@@ -162,25 +163,8 @@ class MenuScreen extends StatelessWidget {
|
||||
actions: [
|
||||
CupertinoDialogAction(
|
||||
onPressed: () async {
|
||||
try {
|
||||
// Logout revokes the Sanctum token. Unregister first, or
|
||||
// FCM / VoIP tokens stay on the server and calls still ring.
|
||||
await sl<FirebaseApi>().unregisterPushTokens();
|
||||
} catch (e, s) {
|
||||
await sl<ErrorReporter>().report(e, s, origin: 'MenuScreen');
|
||||
}
|
||||
try {
|
||||
await sl<Dio>().post('${sl<AppConfig>().baseUrl}/api/profile/logout');
|
||||
} catch (e, s) {
|
||||
await sl<ErrorReporter>().report(e, s, origin: 'MenuScreen');
|
||||
} finally {
|
||||
await sl<VideoCallSessionCubit>().endCall();
|
||||
await sl<WsManager>().clear();
|
||||
await TokenStorage.removeTokenInStorage();
|
||||
if (context.mounted) {
|
||||
GoRouter.of(context).go('/auth-screen', extra: true);
|
||||
}
|
||||
}
|
||||
Navigator.of(context).pop();
|
||||
await menuCubit.logout();
|
||||
},
|
||||
isDestructiveAction: true,
|
||||
child: const Text("Выйти"),
|
||||
|
||||
@@ -136,6 +136,11 @@ class MyDietsCubit extends Cubit<MyDietsState> {
|
||||
}
|
||||
}
|
||||
|
||||
void selectInitialTab(int index) {
|
||||
if (index < 0 || index > 2) return;
|
||||
emit(state.copyWith(selectedStateIndex: index));
|
||||
}
|
||||
|
||||
void changeSelectedStateIndex(int index) {
|
||||
emit(state.copyWith(selectedStateIndex: index));
|
||||
if (state.activeDiets.isEmpty) {
|
||||
|
||||
@@ -19,12 +19,19 @@ import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
class MyDietsScreen extends StatelessWidget {
|
||||
const MyDietsScreen({super.key});
|
||||
const MyDietsScreen({super.key, this.initialTabIndex = 0});
|
||||
static const name = 'myDietsScreen';
|
||||
static const path = '/my-diets-screen';
|
||||
final int initialTabIndex;
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocProvider(create: (context) => sl<MyDietsCubit>()..loadAllDiets(), child: MyDietsScreenContent());
|
||||
return BlocProvider(
|
||||
create: (context) =>
|
||||
sl<MyDietsCubit>()
|
||||
..selectInitialTab(initialTabIndex)
|
||||
..loadAllDiets(),
|
||||
child: MyDietsScreenContent(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2174,6 +2174,56 @@ class PersonalDietIsDefinedToCustomerNotification implements BaseNotificationMod
|
||||
}
|
||||
}
|
||||
|
||||
class PersonalDietIsDefinedToAuthorNotification implements BaseNotificationModel {
|
||||
@override
|
||||
final NotificationType type;
|
||||
@override
|
||||
final bool isRead;
|
||||
@override
|
||||
final DateTime createdAt;
|
||||
final int chosenPlanId;
|
||||
final int dietId;
|
||||
final String planName;
|
||||
final String userName;
|
||||
final String consultantName;
|
||||
final String dietName;
|
||||
final String role;
|
||||
final String peerSlug;
|
||||
final String peerImagePath;
|
||||
|
||||
PersonalDietIsDefinedToAuthorNotification({
|
||||
required this.type,
|
||||
required this.isRead,
|
||||
required this.createdAt,
|
||||
required this.chosenPlanId,
|
||||
required this.dietId,
|
||||
required this.planName,
|
||||
required this.userName,
|
||||
required this.consultantName,
|
||||
required this.dietName,
|
||||
required this.role,
|
||||
required this.peerSlug,
|
||||
required this.peerImagePath,
|
||||
});
|
||||
|
||||
factory PersonalDietIsDefinedToAuthorNotification.fromJson(Map<String, dynamic> json, NotificationType type, {bool? isRead, String? createdAt}) {
|
||||
return PersonalDietIsDefinedToAuthorNotification(
|
||||
type: type,
|
||||
isRead: isRead ?? false,
|
||||
createdAt: parseDate(createdAt ?? json['created_at'] ?? DateTime.now().toIso8601String()),
|
||||
chosenPlanId: json['chosen_plan_id'] ?? 0,
|
||||
dietId: json['diet_id'] ?? 0,
|
||||
planName: json['plan_name'] ?? '',
|
||||
userName: json['user_name'] ?? '',
|
||||
consultantName: json['consultant_name'] ?? '',
|
||||
dietName: json['diet_name'] ?? '',
|
||||
role: json['role']?.toString() ?? '',
|
||||
peerSlug: json['peer_slug'] ?? '',
|
||||
peerImagePath: json['peer_image_path'] ?? '',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// New Model Classes for Comprehensive Support
|
||||
|
||||
class ConsultantEducationUpdatedNotification implements BaseNotificationModel {
|
||||
@@ -2480,6 +2530,7 @@ enum NotificationType {
|
||||
chosenPlanFinishedToConsultant,
|
||||
stayOnTrackToCustomer,
|
||||
personalDietIsDefinedToCustomer,
|
||||
personalDietIsDefinedToAuthor,
|
||||
|
||||
// Comments
|
||||
entityCommented,
|
||||
@@ -2602,6 +2653,7 @@ enum NotificationType {
|
||||
'stay-on-track-to-customer' => NotificationType.stayOnTrackToCustomer,
|
||||
'diary-reminder-for-users' => NotificationType.diaryReminderForUsers,
|
||||
'personal-diet-is-defined-to-customer' => NotificationType.personalDietIsDefinedToCustomer,
|
||||
'personal-diet-is-defined-to-author' => NotificationType.personalDietIsDefinedToAuthor,
|
||||
|
||||
// New additions
|
||||
'consultant-education-updated' => NotificationType.consultantEducationUpdated,
|
||||
|
||||
@@ -16,6 +16,11 @@ class NotificationsCubit extends Cubit<NotificationsState> {
|
||||
StreamSubscription? _newNotificationsSubscription;
|
||||
NotificationsCubit({required this.wsManager, required this.notificationsRepository}) : super(const NotificationsState.empty());
|
||||
|
||||
void reset() {
|
||||
_notifications.clear();
|
||||
if (!isClosed) emit(const NotificationsState.empty());
|
||||
}
|
||||
|
||||
Future<void> connectToWebSocket() async {
|
||||
try {
|
||||
await _newNotificationsSubscription?.cancel();
|
||||
@@ -272,6 +277,12 @@ class NotificationsCubit extends Cubit<NotificationsState> {
|
||||
isRead: isRead,
|
||||
createdAt: createdAt,
|
||||
),
|
||||
NotificationType.personalDietIsDefinedToAuthor => PersonalDietIsDefinedToAuthorNotification.fromJson(
|
||||
notificationJson,
|
||||
type,
|
||||
isRead: isRead,
|
||||
createdAt: createdAt,
|
||||
),
|
||||
NotificationType.consultantEducationUpdated => ConsultantEducationUpdatedNotification.fromJson(
|
||||
notificationJson,
|
||||
type,
|
||||
|
||||
@@ -122,6 +122,9 @@ class NotificationWidget extends StatelessWidget {
|
||||
PersonalDietIsDefinedToCustomerNotification() => _PersonalDietIsDefinedToCustomerWidget(
|
||||
notification: notification as PersonalDietIsDefinedToCustomerNotification,
|
||||
),
|
||||
PersonalDietIsDefinedToAuthorNotification() => _PersonalDietIsDefinedToAuthorWidget(
|
||||
notification: notification as PersonalDietIsDefinedToAuthorNotification,
|
||||
),
|
||||
// New Widgets
|
||||
ConsultantEducationUpdatedNotification() => _ConsultantEducationUpdatedWidget(notification: notification as ConsultantEducationUpdatedNotification),
|
||||
ComplaintRegisteredNotification() => _ComplaintRegisteredWidget(notification: notification as ComplaintRegisteredNotification),
|
||||
@@ -1273,6 +1276,30 @@ class _PersonalDietIsDefinedToCustomerWidget extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
class _PersonalDietIsDefinedToAuthorWidget extends StatelessWidget {
|
||||
const _PersonalDietIsDefinedToAuthorWidget({required this.notification});
|
||||
final PersonalDietIsDefinedToAuthorNotification notification;
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = S.of(context);
|
||||
final userName = notification.userName.isNotEmpty ? notification.userName : s.default_user_name;
|
||||
final notificationsText = notification.dietName.isEmpty
|
||||
? s.personal_diet_defined_to_author(userName)
|
||||
: s.personal_diet_defined_to_author_named(userName, notification.dietName);
|
||||
|
||||
return _BaseNotificationWidget(
|
||||
isRead: notification.isRead,
|
||||
notificationsText: notificationsText,
|
||||
createdAt: notification.createdAt,
|
||||
onTap: notification.peerSlug.isEmpty
|
||||
? null
|
||||
: () {
|
||||
context.push(RouteConstants.profileScreen, extra: notification.peerSlug);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ConsultantEducationUpdatedWidget extends StatelessWidget {
|
||||
const _ConsultantEducationUpdatedWidget({required this.notification});
|
||||
final ConsultantEducationUpdatedNotification notification;
|
||||
|
||||
@@ -413,6 +413,12 @@ class NotificationsService {
|
||||
isRead: readDate != null,
|
||||
createdAt: createdAt,
|
||||
),
|
||||
NotificationType.personalDietIsDefinedToAuthor => PersonalDietIsDefinedToAuthorNotification.fromJson(
|
||||
notificationJson['data'],
|
||||
type,
|
||||
isRead: readDate != null,
|
||||
createdAt: createdAt,
|
||||
),
|
||||
NotificationType.consultantEducationUpdated => ConsultantEducationUpdatedNotification.fromJson(
|
||||
notificationJson['data'],
|
||||
type,
|
||||
|
||||
@@ -6,7 +6,6 @@ import 'package:eatvio_app/features/cancel_plan_bottom_sheet/cancel_plan_bottom_
|
||||
import 'package:eatvio_app/core/widgets/custom_outlined_button.dart';
|
||||
import 'package:eatvio_app/core/widgets/loader.dart';
|
||||
import 'package:eatvio_app/features/diets/presentation/widgets/author_card.dart';
|
||||
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
|
||||
import 'package:eatvio_app/features/order_info/cubit/order_info_cubit.dart';
|
||||
import 'package:eatvio_app/features/order_info/cubit/order_info_state.dart';
|
||||
import 'package:eatvio_app/features/order_info/presentation/widgets/collect_charge_banner.dart';
|
||||
@@ -106,14 +105,7 @@ class _InfoByOrderScreenContentState extends State<InfoByOrderScreenContent> {
|
||||
),
|
||||
);
|
||||
}
|
||||
PacketOptions? chosenOption;
|
||||
if (plan.optionType == 'options1') {
|
||||
chosenOption = plan.plan.packet1Options;
|
||||
} else if (plan.optionType == 'options2') {
|
||||
chosenOption = plan.plan.packet2Options;
|
||||
} else {
|
||||
chosenOption = plan.plan.packet3Options;
|
||||
}
|
||||
final chosenOption = plan.chosenOption;
|
||||
|
||||
PlanStatusValues planStatus;
|
||||
if (widget.successfulPayment == true) {
|
||||
@@ -164,7 +156,7 @@ class _InfoByOrderScreenContentState extends State<InfoByOrderScreenContent> {
|
||||
const SizedBox(height: 8),
|
||||
PlanState(state: plan.chosenPlanState, hasPersonalDiet: chosenOption?.hasPersonalDiet ?? false),
|
||||
const SizedBox(height: 20),
|
||||
if (widget.successfulPayment == null)
|
||||
if (widget.successfulPayment == null && plan.chosenPlanState.canShowCancelAction)
|
||||
CustomOutlinedButton(
|
||||
text: s.cancelConsultation,
|
||||
height: 52,
|
||||
@@ -173,7 +165,7 @@ class _InfoByOrderScreenContentState extends State<InfoByOrderScreenContent> {
|
||||
onPressed: () async {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
builder: (context) => CancelPlanBottomSheet(enableForm: plan.chosenPlanState.isStateAfterPaidState(), planId: plan.id),
|
||||
builder: (context) => CancelPlanBottomSheet(enableForm: plan.chosenPlanState.isCancelAfterPaidState, planId: plan.id),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
@@ -14,6 +14,7 @@ import 'package:flutter/material.dart';
|
||||
Future<void> showConsultationPaymentFlow(
|
||||
BuildContext context, {
|
||||
required int planId,
|
||||
double? amount,
|
||||
Future<bool?> Function(BuildContext)? showGate,
|
||||
Future<PromoCodeResult?> Function(
|
||||
BuildContext, {
|
||||
@@ -21,7 +22,7 @@ Future<void> showConsultationPaymentFlow(
|
||||
Future<bool> Function()? onRemove,
|
||||
PromoCodeModel? initialPromo,
|
||||
})? showForm,
|
||||
Future<void> Function(BuildContext, {required int planId})? showSbp,
|
||||
Future<void> Function(BuildContext, {required int planId, double? amount})? showSbp,
|
||||
Future<PromoValidateResponse> Function({
|
||||
required int planId,
|
||||
required String promoCode,
|
||||
@@ -65,7 +66,7 @@ Future<void> showConsultationPaymentFlow(
|
||||
}
|
||||
|
||||
if (!context.mounted) return;
|
||||
await sbp(context, planId: planId);
|
||||
await sbp(context, planId: planId, amount: amount);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -92,7 +93,7 @@ Future<void> showConsultationPaymentFlow(
|
||||
}
|
||||
|
||||
if (!context.mounted) return;
|
||||
await sbp(context, planId: planId);
|
||||
await sbp(context, planId: planId, amount: amount);
|
||||
}
|
||||
|
||||
Future<bool?> _showGate(BuildContext context) {
|
||||
@@ -113,8 +114,8 @@ Future<PromoCodeResult?> _showForm(
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showSbp(BuildContext context, {required int planId}) {
|
||||
return showSbpBanksBottomSheet(context, planId: planId);
|
||||
Future<void> _showSbp(BuildContext context, {required int planId, double? amount}) {
|
||||
return showSbpBanksBottomSheet(context, planId: planId, amount: amount);
|
||||
}
|
||||
|
||||
Future<PromoValidateResponse> _defaultValidatePromo({
|
||||
|
||||
@@ -8,18 +8,23 @@ import 'package:eatvio_app/core/widgets/custom_outlined_button.dart';
|
||||
import 'package:eatvio_app/core/widgets/loader.dart';
|
||||
import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_cubit.dart';
|
||||
import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_state.dart';
|
||||
import 'package:eatvio_app/features/payment/presentation/widgets/sbp_qr_bottom_sheet.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:sbp/models/c2bmembers_model.dart';
|
||||
|
||||
/// Показывает bottom sheet выбора банка СБП для оплаты консультации.
|
||||
Future<void> showSbpBanksBottomSheet(BuildContext context, {required int planId}) {
|
||||
Future<void> showSbpBanksBottomSheet(
|
||||
BuildContext context, {
|
||||
required int planId,
|
||||
double? amount,
|
||||
}) {
|
||||
final height = MediaQuery.sizeOf(context).height * 0.55;
|
||||
return showBottomSheetWithBlur(
|
||||
context: context,
|
||||
height: height,
|
||||
child: SbpBanksBottomSheet(planId: planId),
|
||||
child: SbpBanksBottomSheet(planId: planId, amount: amount),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -28,9 +33,13 @@ Future<void> showSbpBanksBottomSheet(BuildContext context, {required int planId}
|
||||
/// При открытии вызывает [ConsultationPaymentCubit.startPayment] с [planId]
|
||||
/// и показывает [Loader], пока загружаются checkout_url и список банков.
|
||||
class SbpBanksBottomSheet extends StatefulWidget {
|
||||
const SbpBanksBottomSheet({super.key, required this.planId, this.cubit});
|
||||
const SbpBanksBottomSheet({super.key, required this.planId, this.amount, this.cubit});
|
||||
|
||||
final int planId;
|
||||
|
||||
/// Сумма к оплате в рублях — передаётся в QR-шит для отображения.
|
||||
final double? amount;
|
||||
|
||||
final ConsultationPaymentCubit? cubit;
|
||||
|
||||
@override
|
||||
@@ -77,6 +86,32 @@ class _SbpBanksBottomSheetState extends State<SbpBanksBottomSheet> {
|
||||
style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
// QR-кнопка доступна сразу после получения checkout_url,
|
||||
// не дожидаясь списка банков: на устройствах без банковских
|
||||
// приложений (iOS в РФ) это единственный путь оплаты.
|
||||
BlocBuilder<ConsultationPaymentCubit, ConsultationPaymentState>(
|
||||
buildWhen: (previous, current) =>
|
||||
previous.checkoutUrl != current.checkoutUrl,
|
||||
builder: (context, state) {
|
||||
final checkoutUrl = state.checkoutUrl;
|
||||
if (checkoutUrl == null || checkoutUrl.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 16),
|
||||
child: CustomOutlinedButton(
|
||||
text: s.pay_by_qr_code,
|
||||
height: 52,
|
||||
buttonTextStyle: TextStyles.textMSemibold.copyWith(color: appTheme.whiteA700),
|
||||
buttonStyle: ButtonStyle(
|
||||
side: const WidgetStatePropertyAll(BorderSide.none),
|
||||
backgroundColor: WidgetStatePropertyAll(appTheme.blueA400),
|
||||
),
|
||||
onPressed: _onShowQrTap,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Expanded(
|
||||
child: BlocBuilder<ConsultationPaymentCubit, ConsultationPaymentState>(
|
||||
@@ -122,6 +157,23 @@ class _SbpBanksBottomSheetState extends State<SbpBanksBottomSheet> {
|
||||
);
|
||||
}
|
||||
|
||||
/// Открывает QR-шит поверх шита банков; при подтверждённой оплате
|
||||
/// закрывает и родительский шит.
|
||||
Future<void> _onShowQrTap() async {
|
||||
final paid = await showSbpQrBottomSheet(
|
||||
context,
|
||||
planId: widget.planId,
|
||||
cubit: _cubit,
|
||||
amount: widget.amount,
|
||||
);
|
||||
if (paid == true && mounted) {
|
||||
final navigator = Navigator.of(context);
|
||||
if (navigator.canPop()) {
|
||||
navigator.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _onBankTap(C2bmemberModel bank) async {
|
||||
final opened = await _cubit.openBank(bank: bank);
|
||||
if (opened && mounted) {
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:eatvio_app/core/app_config.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart';
|
||||
import 'package:eatvio_app/core/widgets/bottom_sheet_with_blur.dart';
|
||||
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
|
||||
import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_cubit.dart';
|
||||
import 'package:eatvio_app/features/payment/presentation/cubit/consultation_payment_cubit/consultation_payment_state.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:qr_flutter/qr_flutter.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
/// Тестовый симулятор оплаты СБП (только для стендов разработки/stage).
|
||||
const String _testPayUrlBase = 'https://testpay.alfabank.ru/sbp-page?qrcId=';
|
||||
const String _nspkUrlPrefix = 'https://qr.nspk.ru/';
|
||||
const Duration _pollInterval = Duration(seconds: 3);
|
||||
const Duration _autoCloseDelay = Duration(seconds: 2);
|
||||
|
||||
/// Показывает bottom sheet с QR-кодом СБП для оплаты консультации
|
||||
/// с другого устройства.
|
||||
///
|
||||
/// Возвращает `true`, если оплата подтверждена polling-ом статуса плана.
|
||||
Future<bool?> showSbpQrBottomSheet(
|
||||
BuildContext context, {
|
||||
required int planId,
|
||||
required ConsultationPaymentCubit cubit,
|
||||
double? amount,
|
||||
}) {
|
||||
return showBottomSheetWithBlur<bool>(
|
||||
context: context,
|
||||
height: null,
|
||||
child: SbpQrBottomSheet(
|
||||
planId: planId,
|
||||
cubit: cubit,
|
||||
amount: amount,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// QR-код оплаты СБП: рендерит [ConsultationPaymentState.checkoutUrl]
|
||||
/// (payload вида `https://qr.nspk.ru/{qrcId}`), ожидает оплату через
|
||||
/// polling статуса chosen_plan и показывает успех.
|
||||
class SbpQrBottomSheet extends StatefulWidget {
|
||||
const SbpQrBottomSheet({
|
||||
super.key,
|
||||
required this.planId,
|
||||
required this.cubit,
|
||||
this.amount,
|
||||
this.chatRepository,
|
||||
this.pollInterval = _pollInterval,
|
||||
});
|
||||
|
||||
final int planId;
|
||||
final ConsultationPaymentCubit cubit;
|
||||
|
||||
/// Сумма к оплате в рублях (показывается над QR, если передана).
|
||||
final double? amount;
|
||||
|
||||
/// Переопределяется в тестах; по умолчанию берётся из DI.
|
||||
final ChatRepository? chatRepository;
|
||||
|
||||
final Duration pollInterval;
|
||||
|
||||
@override
|
||||
State<SbpQrBottomSheet> createState() => _SbpQrBottomSheetState();
|
||||
}
|
||||
|
||||
class _SbpQrBottomSheetState extends State<SbpQrBottomSheet> {
|
||||
late final ChatRepository _chatRepository;
|
||||
late final Timer _pollTimer;
|
||||
bool _paid = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_chatRepository = widget.chatRepository ?? sl<ChatRepository>();
|
||||
_pollTimer = Timer.periodic(widget.pollInterval, (_) => _pollStatus());
|
||||
_pollStatus();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_pollTimer.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _pollStatus() async {
|
||||
if (_paid || !mounted) return;
|
||||
try {
|
||||
final plan = await _chatRepository.getChosenPlan(id: widget.planId);
|
||||
if (plan.chosenPlanState.isStateAfterPaidState()) {
|
||||
_onPaid();
|
||||
}
|
||||
} catch (_) {
|
||||
// Сетевые сбои polling-а игнорируем — следующий тик повторит проверку.
|
||||
}
|
||||
}
|
||||
|
||||
void _onPaid() {
|
||||
if (_paid || !mounted) return;
|
||||
setState(() => _paid = true);
|
||||
Future.delayed(_autoCloseDelay, () {
|
||||
if (!mounted) return;
|
||||
Navigator.of(context).pop(true);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = S.of(context);
|
||||
return BlocProvider<ConsultationPaymentCubit>.value(
|
||||
value: widget.cubit,
|
||||
child: BlocBuilder<ConsultationPaymentCubit, ConsultationPaymentState>(
|
||||
builder: (context, state) {
|
||||
final checkoutUrl = state.checkoutUrl;
|
||||
if (checkoutUrl == null || checkoutUrl.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const SizedBox(height: 8),
|
||||
const BottomSheetHandlerBar(),
|
||||
const SizedBox(height: 20),
|
||||
Text(
|
||||
_paid ? s.sbp_qr_paid_title : s.sbp_qr_title,
|
||||
style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (_paid)
|
||||
_PaidContent(description: s.sbp_qr_paid_description)
|
||||
else ...[
|
||||
if (widget.amount != null) ...[
|
||||
Text(
|
||||
s.sbp_qr_amount_label,
|
||||
style: TextStyles.textMMedium.copyWith(color: appTheme.gray600),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'${widget.amount!.toStringAsFixed(0)} ₽',
|
||||
style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
_QrCodeCard(checkoutUrl: checkoutUrl),
|
||||
const SizedBox(height: 16),
|
||||
_HowToPay(
|
||||
step1: s.sbp_qr_step1,
|
||||
step2: s.sbp_qr_step2,
|
||||
step3: s.sbp_qr_step3,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_TestPayButton(checkoutUrl: checkoutUrl),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
s.sbp_qr_waiting_payment,
|
||||
style: TextStyles.textMMedium.copyWith(color: appTheme.gray600),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 24),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _QrCodeCard extends StatelessWidget {
|
||||
const _QrCodeCard({required this.checkoutUrl});
|
||||
|
||||
final String checkoutUrl;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: appTheme.blueGray300),
|
||||
),
|
||||
child: QrImageView(
|
||||
key: const ValueKey('sbp_qr_code'),
|
||||
data: checkoutUrl,
|
||||
size: 200,
|
||||
backgroundColor: Colors.white,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _HowToPay extends StatelessWidget {
|
||||
const _HowToPay({required this.step1, required this.step2, required this.step3});
|
||||
|
||||
final String step1;
|
||||
final String step2;
|
||||
final String step3;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: appTheme.blueA400.withValues(alpha: 0.08),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(step1, style: TextStyles.textSMedium.copyWith(color: appTheme.black)),
|
||||
const SizedBox(height: 4),
|
||||
Text(step2, style: TextStyles.textSMedium.copyWith(color: appTheme.black)),
|
||||
const SizedBox(height: 4),
|
||||
Text(step3, style: TextStyles.textSMedium.copyWith(color: appTheme.black)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Кнопка открытия тестового симулятора оплаты Альфа-Банка.
|
||||
///
|
||||
/// Видна только когда QR выдан непродовым бэкендом: тестовый qrcId от
|
||||
/// продового в приложении не отличить (формат одинаковый), различает их
|
||||
/// именно то, какой бэкенд выдал checkout_url — на стендах разработки/stage
|
||||
/// Альфа подключена в sandbox и выдаёт QR тестового терминала. Поэтому
|
||||
/// критерий — текущий base URL API не продуктовый (см. [AppConfig.isProdApi]).
|
||||
class _TestPayButton extends StatelessWidget {
|
||||
const _TestPayButton({required this.checkoutUrl});
|
||||
|
||||
final String checkoutUrl;
|
||||
|
||||
bool get _visible {
|
||||
if (sl<AppConfig>().isProdApi) return false;
|
||||
return checkoutUrl.startsWith(_nspkUrlPrefix);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!_visible) return const SizedBox.shrink();
|
||||
final s = S.of(context);
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFFFF3E0),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(
|
||||
s.sbp_qr_test_hint,
|
||||
style: TextStyles.textXSSemibold.copyWith(color: appTheme.gray600),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
OutlinedButton(
|
||||
onPressed: () => _openTestPayment(),
|
||||
child: Text(s.sbp_qr_open_test_payment),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _openTestPayment() async {
|
||||
final qrcId = checkoutUrl.replaceFirst(_nspkUrlPrefix, '');
|
||||
final uri = Uri.parse('$_testPayUrlBase$qrcId');
|
||||
try {
|
||||
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
} catch (_) {
|
||||
// Не смогли открыть браузер — пользователь оплатит по QR.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _PaidContent extends StatelessWidget {
|
||||
const _PaidContent({required this.description});
|
||||
|
||||
final String description;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
children: [
|
||||
const SizedBox(height: 8),
|
||||
Container(
|
||||
width: 64,
|
||||
height: 64,
|
||||
decoration: const BoxDecoration(color: Color(0xFFE8F5E9), shape: BoxShape.circle),
|
||||
child: const Icon(Icons.check_rounded, color: Color(0xFF4CAF50), size: 40),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
description,
|
||||
style: TextStyles.textMMedium.copyWith(color: appTheme.gray600),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -9,38 +9,54 @@ import 'package:eatvio_app/core/error_reporting/report_from.dart';
|
||||
class PersonalDietSuggestionCubit extends Cubit<PersonalDietSuggestionState> {
|
||||
final DietRepository dietRepository;
|
||||
final PersonalDietSuggestionRepository personalDietSuggestionService;
|
||||
late final int dietId;
|
||||
late int dietId;
|
||||
PersonalDietSuggestionCubit({required this.dietRepository, required this.personalDietSuggestionService}) : super(PersonalDietSuggestionState());
|
||||
|
||||
Future<void> setDietName(int dietId) async {
|
||||
try {
|
||||
emit(state.copyWith(isLoading: true, error: null));
|
||||
if (!isClosed) {
|
||||
emit(state.copyWith(isLoading: true, error: null));
|
||||
}
|
||||
final diet = await dietRepository.getDiet(dietId);
|
||||
emit(state.copyWith(isLoading: false, dietName: diet.name));
|
||||
if (!isClosed) {
|
||||
emit(state.copyWith(
|
||||
isLoading: false,
|
||||
dietName: diet.name,
|
||||
dietDuration: diet.duration,
|
||||
));
|
||||
}
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
log(e.toString(), stackTrace: st);
|
||||
emit(state.copyWith(isLoading: false, error: e.toString()));
|
||||
if (!isClosed) {
|
||||
emit(state.copyWith(isLoading: false, error: e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> getConsultationWithPersonalDiets(int dietId) async {
|
||||
try {
|
||||
this.dietId = dietId;
|
||||
emit(state.copyWith(isLoading: true, error: null));
|
||||
setDietName(dietId);
|
||||
if (!isClosed) {
|
||||
emit(state.copyWith(isLoading: true, error: null));
|
||||
}
|
||||
await setDietName(dietId);
|
||||
final consultations = await personalDietSuggestionService.getConsultationWithPersonalDiets();
|
||||
final consultationWithDiet = consultations.where((consultation) => consultation.personalDietId != null).toList();
|
||||
final consultationWithoutDiet = consultations.where((consultation) => consultation.personalDietId == null).toList();
|
||||
emit(state.copyWith(
|
||||
isLoading: false,
|
||||
consultationsWithDiet: consultationWithDiet,
|
||||
consultationsWithoutDiet: consultationWithoutDiet,
|
||||
));
|
||||
if (!isClosed) {
|
||||
emit(state.copyWith(
|
||||
isLoading: false,
|
||||
consultationsWithDiet: consultationWithDiet,
|
||||
consultationsWithoutDiet: consultationWithoutDiet,
|
||||
));
|
||||
}
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
log(e.toString(), stackTrace: st);
|
||||
emit(state.copyWith(isLoading: false, error: e.toString()));
|
||||
if (!isClosed) {
|
||||
emit(state.copyWith(isLoading: false, error: e.toString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,6 +65,7 @@ class PersonalDietSuggestionCubit extends Cubit<PersonalDietSuggestionState> {
|
||||
}) async {
|
||||
try {
|
||||
await personalDietSuggestionService.attachPersonalDiet(consultationId: consultationId, dietId: dietId);
|
||||
await getConsultationWithPersonalDiets(dietId);
|
||||
return true;
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
@@ -62,6 +79,7 @@ class PersonalDietSuggestionCubit extends Cubit<PersonalDietSuggestionState> {
|
||||
}) async {
|
||||
try {
|
||||
await personalDietSuggestionService.reattachPersonalDiet(consultationId: consultationId, dietId: dietId);
|
||||
await getConsultationWithPersonalDiets(dietId);
|
||||
return true;
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
|
||||
@@ -9,8 +9,8 @@ abstract class PersonalDietSuggestionState with _$PersonalDietSuggestionState {
|
||||
@Default([]) List<ConsultationModel> consultationsWithDiet,
|
||||
@Default([]) List<ConsultationModel> consultationsWithoutDiet,
|
||||
@Default('') String dietName,
|
||||
@Default(0) int dietDuration,
|
||||
@Default(false) bool isLoading,
|
||||
@Default(null) String? error,
|
||||
}) = _PersonalDietSuggestionState;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import 'package:eatvio_app/core/app_router.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/utils/localization_utils.dart';
|
||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||
import 'package:eatvio_app/core/widgets/bottom_sheet_handler_bar.dart';
|
||||
import 'package:eatvio_app/core/widgets/bottom_sheet_with_blur.dart';
|
||||
import 'package:eatvio_app/core/widgets/custom_outlined_button.dart';
|
||||
@@ -11,6 +13,7 @@ import 'package:eatvio_app/features/consultations/models/consultation_model.dart
|
||||
import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
@@ -19,9 +22,15 @@ class ConsultationWidget extends StatelessWidget {
|
||||
super.key,
|
||||
required this.consultationModel,
|
||||
required this.dietName,
|
||||
this.dietDuration = 0,
|
||||
});
|
||||
final ConsultationModel consultationModel;
|
||||
final String dietName;
|
||||
final int dietDuration;
|
||||
|
||||
bool get _isDurationMismatch =>
|
||||
dietDuration > 0 && consultationModel.duration != dietDuration;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = S.of(context);
|
||||
@@ -64,7 +73,20 @@ class ConsultationWidget extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'Старт: ${consultationModel.userName}',
|
||||
s.plan_duration_label(
|
||||
consultationModel.duration,
|
||||
getDayForm(consultationModel.duration, s),
|
||||
),
|
||||
style: TextStyles.textMMedium.copyWith(
|
||||
color: const Color(0xFF88949F),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
s.start_date_label(
|
||||
DateFormat('dd.MM.yyyy').format(
|
||||
consultationModel.startDate,
|
||||
),
|
||||
),
|
||||
style: TextStyles.textMMedium.copyWith(
|
||||
color: const Color(0xFF88949F),
|
||||
),
|
||||
@@ -103,15 +125,47 @@ class ConsultationWidget extends StatelessWidget {
|
||||
color: const Color(0xFF88949F),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
s.plan_duration_label(
|
||||
consultationModel.duration,
|
||||
getDayForm(consultationModel.duration, s),
|
||||
),
|
||||
style: TextStyles.textMMedium.copyWith(
|
||||
color: const Color(0xFF88949F),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
if (_isDurationMismatch)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(Icons.error_outline, size: 18, color: appTheme.red),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
s.personal_diet_duration_mismatch(
|
||||
dietDuration,
|
||||
getDayForm(dietDuration, s),
|
||||
consultationModel.duration,
|
||||
getDayForm(consultationModel.duration, s),
|
||||
),
|
||||
style: TextStyles.textSMedium.copyWith(color: appTheme.red),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (consultationModel.personalDietId != null)
|
||||
CustomOutlinedButton(
|
||||
text: s.changeDiet,
|
||||
height: 52,
|
||||
isDisabled: _isDurationMismatch,
|
||||
buttonTextStyle: TextStyles.textMSemibold.copyWith(
|
||||
color: appTheme.gray,
|
||||
),
|
||||
@@ -128,35 +182,8 @@ class ConsultationWidget extends StatelessWidget {
|
||||
userName: consultationModel.userName,
|
||||
dietName: dietName,
|
||||
onTap: () async {
|
||||
final result = await context
|
||||
.read<PersonalDietSuggestionCubit>()
|
||||
.attachDietToConsultation(
|
||||
consultationId: consultationModel.id,
|
||||
);
|
||||
AppRouter.navigatorKey.currentContext?.pop();
|
||||
if (result) {
|
||||
if (!context.mounted) return;
|
||||
showBottomSheetWithBlur(
|
||||
userRootNavigator: true,
|
||||
context: context,
|
||||
height: null,
|
||||
child: SuggestionSuccessBottomSheet(
|
||||
userName: consultationModel.userName,
|
||||
dietName: dietName,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!context.mounted) return;
|
||||
showBottomSheetWithBlur(
|
||||
userRootNavigator: true,
|
||||
context: context,
|
||||
height: null,
|
||||
child: SuggestionFailureBottomSheet(
|
||||
userName: consultationModel.userName,
|
||||
dietName: dietName,
|
||||
),
|
||||
);
|
||||
await _attachDiet(context, reattach: true);
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -166,12 +193,17 @@ class ConsultationWidget extends StatelessWidget {
|
||||
CustomOutlinedButton(
|
||||
text: s.suggestDiet,
|
||||
height: 52,
|
||||
isDisabled: _isDurationMismatch,
|
||||
buttonTextStyle: TextStyles.textMSemibold.copyWith(
|
||||
color: appTheme.whiteA700,
|
||||
color: _isDurationMismatch ? appTheme.gray : appTheme.whiteA700,
|
||||
),
|
||||
buttonStyle: ButtonStyle(
|
||||
side: const WidgetStatePropertyAll(BorderSide.none),
|
||||
backgroundColor: WidgetStatePropertyAll(appTheme.blueA400),
|
||||
backgroundColor: WidgetStatePropertyAll(
|
||||
_isDurationMismatch
|
||||
? appTheme.dividerColor
|
||||
: appTheme.blueA400,
|
||||
),
|
||||
),
|
||||
onPressed: () async {
|
||||
showBottomSheetWithBlur(
|
||||
@@ -183,34 +215,7 @@ class ConsultationWidget extends StatelessWidget {
|
||||
dietName: dietName,
|
||||
onTap: () async {
|
||||
AppRouter.navigatorKey.currentContext?.pop();
|
||||
final result = await context
|
||||
.read<PersonalDietSuggestionCubit>()
|
||||
.attachDietToConsultation(
|
||||
consultationId: consultationModel.id,
|
||||
);
|
||||
if (result) {
|
||||
if (!context.mounted) return;
|
||||
showBottomSheetWithBlur(
|
||||
userRootNavigator: true,
|
||||
context: context,
|
||||
height: null,
|
||||
child: SuggestionSuccessBottomSheet(
|
||||
userName: consultationModel.userName,
|
||||
dietName: dietName,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!context.mounted) return;
|
||||
showBottomSheetWithBlur(
|
||||
userRootNavigator: true,
|
||||
context: context,
|
||||
height: null,
|
||||
child: SuggestionFailureBottomSheet(
|
||||
userName: consultationModel.userName,
|
||||
dietName: dietName,
|
||||
),
|
||||
);
|
||||
await _attachDiet(context, reattach: false);
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -220,6 +225,41 @@ class ConsultationWidget extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _attachDiet(
|
||||
BuildContext context, {
|
||||
required bool reattach,
|
||||
}) async {
|
||||
final router = GoRouter.of(context);
|
||||
final chatId = consultationModel.chatId;
|
||||
final noChatMessage = S.of(context).msg_something_went_wrong;
|
||||
final cubit = context.read<PersonalDietSuggestionCubit>();
|
||||
final result = reattach
|
||||
? await cubit.reattachDietToConsultation(
|
||||
consultationId: consultationModel.id,
|
||||
)
|
||||
: await cubit.attachDietToConsultation(
|
||||
consultationId: consultationModel.id,
|
||||
);
|
||||
if (!result) {
|
||||
if (!context.mounted) return;
|
||||
showBottomSheetWithBlur(
|
||||
userRootNavigator: true,
|
||||
context: context,
|
||||
height: null,
|
||||
child: SuggestionFailureBottomSheet(
|
||||
userName: consultationModel.userName,
|
||||
dietName: dietName,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (chatId == null || chatId.isEmpty) {
|
||||
showErrorToast(noChatMessage);
|
||||
return;
|
||||
}
|
||||
router.goNamed('chatScreen', queryParameters: {'uuid': chatId});
|
||||
}
|
||||
}
|
||||
|
||||
class SuggestDietBottomSheet extends StatefulWidget {
|
||||
@@ -278,65 +318,6 @@ class _SuggestDietBottomSheet extends State<SuggestDietBottomSheet> {
|
||||
}
|
||||
}
|
||||
|
||||
class SuggestionSuccessBottomSheet extends StatefulWidget {
|
||||
const SuggestionSuccessBottomSheet({
|
||||
super.key,
|
||||
required this.userName,
|
||||
required this.dietName,
|
||||
});
|
||||
final String userName;
|
||||
final String dietName;
|
||||
|
||||
@override
|
||||
State<SuggestionSuccessBottomSheet> createState() =>
|
||||
_SuggestionSuccessBottomSheet();
|
||||
}
|
||||
|
||||
class _SuggestionSuccessBottomSheet
|
||||
extends State<SuggestionSuccessBottomSheet> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = S.of(context);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const SizedBox(height: 8),
|
||||
const BottomSheetHandlerBar(),
|
||||
const SizedBox(height: 20),
|
||||
Text(
|
||||
'Предложение диеты',
|
||||
style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'«${widget.dietName}» предложена пользователю ${widget.userName}',
|
||||
style: TextStyles.textSMedium.copyWith(color: appTheme.black),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
CustomOutlinedButton(
|
||||
text: s.ok,
|
||||
height: 52,
|
||||
buttonTextStyle: TextStyles.textMSemibold.copyWith(
|
||||
color: appTheme.whiteA700,
|
||||
),
|
||||
buttonStyle: ButtonStyle(
|
||||
side: const WidgetStatePropertyAll(BorderSide.none),
|
||||
backgroundColor: WidgetStatePropertyAll(appTheme.blueA400),
|
||||
),
|
||||
onPressed: () async {
|
||||
AppRouter.navigatorKey.currentContext?.pop();
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 40),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class SuggestionFailureBottomSheet extends StatefulWidget {
|
||||
const SuggestionFailureBottomSheet({
|
||||
super.key,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/utils/localization_utils.dart';
|
||||
import 'package:eatvio_app/core/widgets/loader.dart';
|
||||
import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart';
|
||||
import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_state.dart';
|
||||
@@ -17,7 +18,9 @@ class PersonalDietSuggestionScreen extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocProvider(
|
||||
create: (context) => sl<PersonalDietSuggestionCubit>()..getConsultationWithPersonalDiets(dietId),
|
||||
create: (context) =>
|
||||
sl<PersonalDietSuggestionCubit>()
|
||||
..getConsultationWithPersonalDiets(dietId),
|
||||
child: const PersonalDietSuggestionScreenContent(),
|
||||
);
|
||||
}
|
||||
@@ -28,7 +31,10 @@ class PersonalDietSuggestionScreenContent extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = S.of(context);
|
||||
return BlocBuilder<PersonalDietSuggestionCubit, PersonalDietSuggestionState>(
|
||||
return BlocBuilder<
|
||||
PersonalDietSuggestionCubit,
|
||||
PersonalDietSuggestionState
|
||||
>(
|
||||
builder: (context, state) {
|
||||
return Scaffold(
|
||||
backgroundColor: appTheme.gray100,
|
||||
@@ -36,45 +42,97 @@ class PersonalDietSuggestionScreenContent extends StatelessWidget {
|
||||
centerTitle: true,
|
||||
title: Text(
|
||||
'${s.dietSuggestion}\n«${state.dietName}»',
|
||||
style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black),
|
||||
style: TextStyles.headingXLSemibold.copyWith(
|
||||
color: appTheme.black,
|
||||
),
|
||||
),
|
||||
),
|
||||
body: state.isLoading
|
||||
? const Center(child: Loader())
|
||||
: (state.consultationsWithDiet.isEmpty && state.consultationsWithoutDiet.isEmpty)
|
||||
? Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32.0),
|
||||
child: Text(
|
||||
'Нет активных консультаций с персональной диетой',
|
||||
style: TextStyles.textMSemibold.copyWith(color: appTheme.gray),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
)
|
||||
: SingleChildScrollView(
|
||||
child: Column(
|
||||
children: [
|
||||
...List.generate(state.consultationsWithDiet.length, (index) {
|
||||
return ConsultationWidget(
|
||||
consultationModel: state.consultationsWithDiet[index],
|
||||
dietName: state.dietName,
|
||||
);
|
||||
}),
|
||||
const SizedBox(
|
||||
height: 12,
|
||||
: SingleChildScrollView(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (state.dietDuration > 0)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
|
||||
child: _PersonalDietDurationHint(
|
||||
duration: state.dietDuration,
|
||||
),
|
||||
...List.generate(state.consultationsWithoutDiet.length, (index) {
|
||||
),
|
||||
if (state.consultationsWithDiet.isEmpty &&
|
||||
state.consultationsWithoutDiet.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Text(
|
||||
s.no_active_personal_diet_consultations,
|
||||
style: TextStyles.textMSemibold.copyWith(
|
||||
color: appTheme.gray,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
)
|
||||
else ...[
|
||||
...List.generate(state.consultationsWithDiet.length, (
|
||||
index,
|
||||
) {
|
||||
return ConsultationWidget(
|
||||
consultationModel:
|
||||
state.consultationsWithDiet[index],
|
||||
dietName: state.dietName,
|
||||
dietDuration: state.dietDuration,
|
||||
);
|
||||
}),
|
||||
const SizedBox(height: 12),
|
||||
...List.generate(
|
||||
state.consultationsWithoutDiet.length,
|
||||
(index) {
|
||||
return ConsultationWidget(
|
||||
consultationModel: state.consultationsWithoutDiet[index],
|
||||
consultationModel:
|
||||
state.consultationsWithoutDiet[index],
|
||||
dietName: state.dietName,
|
||||
dietDuration: state.dietDuration,
|
||||
);
|
||||
})
|
||||
],
|
||||
),
|
||||
),
|
||||
},
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PersonalDietDurationHint extends StatelessWidget {
|
||||
const _PersonalDietDurationHint({required this.duration});
|
||||
|
||||
final int duration;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = S.of(context);
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: appTheme.gray50,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: appTheme.dividerColor),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(Icons.info_outline, size: 20, color: appTheme.blueA400),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
s.personal_diet_duration_hint(duration, getDayForm(duration, s)),
|
||||
style: TextStyles.textSMedium.copyWith(color: appTheme.gray),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,13 +11,23 @@ class PersonalDietSuggestionRepository {
|
||||
|
||||
}
|
||||
|
||||
Future<void> attachPersonalDiet({required int consultationId, required int dietId}) async {
|
||||
return personalDietSuggestionService.attachPersonalDiet(consultationId: consultationId, dietId: dietId);
|
||||
|
||||
Future<void> attachPersonalDiet({
|
||||
required int consultationId,
|
||||
required int dietId,
|
||||
}) async {
|
||||
await personalDietSuggestionService.attachPersonalDiet(
|
||||
consultationId,
|
||||
{'diet_id': dietId},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> reattachPersonalDiet({required int consultationId, required int dietId}) async {
|
||||
return await personalDietSuggestionService.reattachPersonalDiet(consultationId: consultationId, dietId: dietId);
|
||||
|
||||
Future<void> reattachPersonalDiet({
|
||||
required int consultationId,
|
||||
required int dietId,
|
||||
}) async {
|
||||
await personalDietSuggestionService.reattachPersonalDiet(
|
||||
consultationId,
|
||||
{'diet_id': dietId},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,36 +1,40 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/features/consultations/models/consultation_model.dart';
|
||||
import 'package:retrofit/retrofit.dart';
|
||||
|
||||
class PersonalDietSuggestionService {
|
||||
final Dio dio;
|
||||
PersonalDietSuggestionService(this.dio);
|
||||
part 'personal_diet_suggestion_service.g.dart';
|
||||
|
||||
Future<ConsultationPaginationModel> getConsultationWithPersonalDiets() async {
|
||||
try {
|
||||
final response = await dio.get('/api/consultations', queryParameters: {
|
||||
'filters[plan][has_personal_diet][\$personal_diet]': '1',
|
||||
'filters[last_state][\$notIn][]': ['done', 'charge_was_collected', 'complained', 'last_day_finished', 'canceled_by_the_initiator', 'inited'],
|
||||
'sort[]': 'start_date:desc',
|
||||
});
|
||||
return ConsultationPaginationModel.fromJson(response.data);
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
@RestApi()
|
||||
abstract class PersonalDietSuggestionService {
|
||||
factory PersonalDietSuggestionService(Dio dio, {String? baseUrl}) =
|
||||
_PersonalDietSuggestionService;
|
||||
|
||||
Future<void> attachPersonalDiet({required int consultationId, required int dietId}) async {
|
||||
try {
|
||||
await dio.post('/api/chosen_plans/$consultationId/attach_diet', data: {'diet_id': dietId});
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
@GET('/api/consultations')
|
||||
Future<ConsultationPaginationModel> getConsultationWithPersonalDiets({
|
||||
@Query('filters[plan][has_personal_diet][\$personal_diet]')
|
||||
String hasPersonalDiet = '1',
|
||||
@Query('filters[last_state][\$notIn][]')
|
||||
List<String> notIn = const [
|
||||
'done',
|
||||
'charge_was_collected',
|
||||
'complained',
|
||||
'last_day_finished',
|
||||
'last_day_started',
|
||||
'canceled_by_the_initiator',
|
||||
'inited',
|
||||
],
|
||||
@Query('sort[]') List<String> sort = const ['start_date:desc'],
|
||||
});
|
||||
|
||||
Future<void> reattachPersonalDiet({required int consultationId, required int dietId}) async {
|
||||
try {
|
||||
await dio.post('/api/chosen_plans/$consultationId/re_attach_diet', data: {'diet_id': dietId});
|
||||
} catch (e) {
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
@POST('/api/chosen_plans/{id}/attach_diet')
|
||||
Future<void> attachPersonalDiet(
|
||||
@Path('id') int consultationId,
|
||||
@Body() Map<String, dynamic> body,
|
||||
);
|
||||
|
||||
@POST('/api/chosen_plans/{id}/re_attach_diet')
|
||||
Future<void> reattachPersonalDiet(
|
||||
@Path('id') int consultationId,
|
||||
@Body() Map<String, dynamic> body,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -62,6 +62,32 @@ enum ChosenPlanStateEnum {
|
||||
}
|
||||
}
|
||||
|
||||
bool get canShowCancelAction {
|
||||
switch (this) {
|
||||
case ChosenPlanStateEnum.stateInited:
|
||||
case ChosenPlanStateEnum.stateInCoordination:
|
||||
case ChosenPlanStateEnum.stateStartDateHasBeenSet:
|
||||
case ChosenPlanStateEnum.statePendingPayment:
|
||||
case ChosenPlanStateEnum.statePaid:
|
||||
case ChosenPlanStateEnum.stateStarted:
|
||||
case ChosenPlanStateEnum.stateInProgress:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool get isCancelAfterPaidState {
|
||||
switch (this) {
|
||||
case ChosenPlanStateEnum.statePaid:
|
||||
case ChosenPlanStateEnum.stateStarted:
|
||||
case ChosenPlanStateEnum.stateInProgress:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static List<ChosenPlanStateEnum> getActiveStates() {
|
||||
return [
|
||||
ChosenPlanStateEnum.statePaid,
|
||||
|
||||
29
lib/features/plans/enums/plan_option_type_enum.dart
Normal file
29
lib/features/plans/enums/plan_option_type_enum.dart
Normal file
@@ -0,0 +1,29 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
enum PlanOptionType {
|
||||
@JsonValue('options1')
|
||||
options1('options1'),
|
||||
@JsonValue('options2')
|
||||
options2('options2'),
|
||||
@JsonValue('options3')
|
||||
options3('options3');
|
||||
|
||||
const PlanOptionType(this.apiValue);
|
||||
|
||||
final String apiValue;
|
||||
|
||||
static PlanOptionType? tryParse(String? raw) {
|
||||
for (final option in values) {
|
||||
if (option.apiValue == raw) {
|
||||
return option;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static PlanOptionType fromIndex(int index) => switch (index) {
|
||||
1 => PlanOptionType.options2,
|
||||
2 => PlanOptionType.options3,
|
||||
_ => PlanOptionType.options1,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:eatvio_app/features/feed/models/plan_pagination_model.dart';
|
||||
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||
import 'package:eatvio_app/features/plans/enums/plan_option_type_enum.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'chosen_plan_model.freezed.dart';
|
||||
@@ -7,6 +8,7 @@ part 'chosen_plan_model.g.dart';
|
||||
|
||||
@freezed
|
||||
abstract class ChosenPlanModel with _$ChosenPlanModel {
|
||||
const ChosenPlanModel._();
|
||||
|
||||
factory ChosenPlanModel({
|
||||
@JsonKey() required int id,
|
||||
@@ -15,10 +17,24 @@ abstract class ChosenPlanModel with _$ChosenPlanModel {
|
||||
@JsonKey(name: 'last_state') required ChosenPlanStateEnum chosenPlanState,
|
||||
@JsonKey(name: 'chat_id') required String chatId,
|
||||
@JsonKey(name: 'consultant_id') required int consultantId,
|
||||
@JsonKey(name: 'personal_diet_name') String? personalDietName,
|
||||
@JsonKey(name: 'plan') required PlanModel plan,
|
||||
}) = _ChosenPlanModel;
|
||||
|
||||
factory ChosenPlanModel.fromJson(Map<String, dynamic> json) => _$ChosenPlanModelFromJson(json);
|
||||
|
||||
PacketOptions? get chosenOption {
|
||||
switch (PlanOptionType.tryParse(optionType)) {
|
||||
case PlanOptionType.options1:
|
||||
return plan.packet1Options;
|
||||
case PlanOptionType.options2:
|
||||
return plan.packet2Options;
|
||||
case PlanOptionType.options3:
|
||||
return plan.packet3Options;
|
||||
case null:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ChosenPlanModel? parseChosenPlan(dynamic json) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import 'package:dio/dio.dart';
|
||||
import 'package:easy_debounce/easy_debounce.dart';
|
||||
import 'package:eatvio_app/core/utils/toasts.dart';
|
||||
import 'package:eatvio_app/features/diets/repositories/diet_repository.dart';
|
||||
import 'package:eatvio_app/features/plans/enums/plan_option_type_enum.dart';
|
||||
import 'package:eatvio_app/features/plans/models/chosen_plan_model.dart';
|
||||
import 'package:eatvio_app/features/plans/presentation/cubit/about_plan_state.dart';
|
||||
import 'package:eatvio_app/features/plans/repositories/plan_repository.dart';
|
||||
@@ -133,7 +134,7 @@ class AboutPlanCubit extends Cubit<AboutPlanState> {
|
||||
final slug = state.planModel?.slug;
|
||||
final optionIndex = state.chosenOptionIndex;
|
||||
if (slug != null) {
|
||||
final optionName = _getOptionNameFromIndex(optionIndex);
|
||||
final optionName = PlanOptionType.fromIndex(optionIndex).apiValue;
|
||||
final body = {'options_type': optionName};
|
||||
return (await planRepository.chosePlan(slug, body), null);
|
||||
}
|
||||
@@ -181,10 +182,4 @@ class AboutPlanCubit extends Cubit<AboutPlanState> {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
String _getOptionNameFromIndex(int index) => switch (index) {
|
||||
1 => 'options2',
|
||||
2 => 'options3',
|
||||
_ => 'options1',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -22,6 +22,10 @@ class ProfileCubit extends Cubit<ProfileState> {
|
||||
/// Bottom-nav / own profile instance, used to refresh posts after create/update/delete.
|
||||
static ProfileCubit? myProfileCubit;
|
||||
|
||||
static void clearMyProfileReference() {
|
||||
myProfileCubit = null;
|
||||
}
|
||||
|
||||
ProfileCubit({required this.profileRepository, required this.chatRepository, required this.consultantRepository}) : super(const ProfileState.loading());
|
||||
|
||||
Future<void> getProfileBySlug(String slug) async {
|
||||
@@ -141,13 +145,13 @@ class ProfileCubit extends Cubit<ProfileState> {
|
||||
|
||||
Future<String?> getChatRoomIdBySlug({required String slug}) async {
|
||||
try {
|
||||
final chatIdOrError = await chatRepository.getChatByUserSlug(slug);
|
||||
final userProfile = await profileRepository.getProfileBySlug(slug);
|
||||
if (chatIdOrError == '404') {
|
||||
final chatId = await chatRepository.getChatByUserSlug(slug);
|
||||
if (chatId == null || chatId.isEmpty) {
|
||||
final userProfile = await profileRepository.getProfileBySlug(slug);
|
||||
AppRouter.navigatorKey.currentContext?.pushNamed('emptyChatScreen', extra: userProfile);
|
||||
} else {
|
||||
AppRouter.navigatorKey.currentContext?.pushNamed('chatScreen', extra: {'uuid': chatIdOrError});
|
||||
return chatIdOrError;
|
||||
AppRouter.navigatorKey.currentContext?.pushNamed('chatScreen', extra: {'uuid': chatId});
|
||||
return chatId;
|
||||
}
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:eatvio_app/core/app_router.dart';
|
||||
import 'package:eatvio_app/core/firebase_api.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/mixins/registration_date_cache_mixin.dart';
|
||||
import 'package:eatvio_app/core/prefs.dart';
|
||||
|
||||
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/features/registration/models/user_registration_model.dart';
|
||||
import 'package:eatvio_app/features/registration/presentation/bloc/registration_cubit/registration_state.dart';
|
||||
@@ -18,7 +16,8 @@ import 'package:go_router/go_router.dart';
|
||||
|
||||
class RegistrationCubit extends Cubit<RegistrationState> with RegistrationDateCacheMixin {
|
||||
final RegistrationRepository registrationRepository;
|
||||
RegistrationCubit({required this.registrationRepository, required Prefs prefs})
|
||||
final SessionLifecycleService sessionLifecycleService;
|
||||
RegistrationCubit({required this.registrationRepository, required this.sessionLifecycleService, required Prefs prefs})
|
||||
: super(
|
||||
const RegistrationState(
|
||||
sheet: UserRegistrationSheet(
|
||||
@@ -62,7 +61,7 @@ class RegistrationCubit extends Cubit<RegistrationState> with RegistrationDateCa
|
||||
state.sheet.copyWith(phone: state.sheet.phone.replaceAll(' ', '').replaceAll('(', '').replaceAll(')', ''), responseBody: '{}'),
|
||||
);
|
||||
await TokenStorage.saveTokenInStorage(token);
|
||||
await sl<FirebaseApi>().registerPushToken();
|
||||
await sessionLifecycleService.onAuthenticated();
|
||||
RegistrationAnalyticsService.reportRegistrationComplete();
|
||||
cacheRegistrationDate(DateTime.now());
|
||||
AppRouter.navigatorKey.currentContext?.replaceNamed('verifyEmailScreen');
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'dart:developer';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/firebase_api.dart';
|
||||
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/core/utils/date_time_utils.dart';
|
||||
import 'package:eatvio_app/core/utils/validation_utils.dart';
|
||||
@@ -15,9 +16,11 @@ import 'package:gpassword/gpassword.dart';
|
||||
class RegistrationCubitV2 extends Cubit<RegistrationStateV2> {
|
||||
final RegistrationRepositoryV2 registrationRepository;
|
||||
final FirebaseApi firebaseApi;
|
||||
final SessionLifecycleService sessionLifecycleService;
|
||||
RegistrationCubitV2({
|
||||
required this.registrationRepository,
|
||||
required this.firebaseApi,
|
||||
required this.sessionLifecycleService,
|
||||
}) : super(const RegistrationStateV2());
|
||||
|
||||
void setFirstName(String firstName) {
|
||||
@@ -204,7 +207,7 @@ class RegistrationCubitV2 extends Cubit<RegistrationStateV2> {
|
||||
);
|
||||
if (token != null) {
|
||||
await TokenStorage.saveTokenInStorage(token);
|
||||
await firebaseApi.registerPushToken();
|
||||
await sessionLifecycleService.onAuthenticated();
|
||||
emit(state.copyWith(registrationError: null));
|
||||
return (true, false);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/session/session_lifecycle_service.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/consultations/repositories/consultations_repository.dart';
|
||||
@@ -17,12 +19,14 @@ class SettingsCubit extends Cubit<SettingsState> {
|
||||
final SettingsRepository settingsRepository;
|
||||
final ConsultantRepository consultantRepository;
|
||||
final ConsultationsRepository consultationsRepository;
|
||||
final SessionLifecycleService sessionLifecycleService;
|
||||
|
||||
SettingsCubit({
|
||||
required this.profileRepository,
|
||||
required this.settingsRepository,
|
||||
required this.profileRepository,
|
||||
required this.settingsRepository,
|
||||
required this.consultantRepository,
|
||||
required this.consultationsRepository,
|
||||
required this.sessionLifecycleService,
|
||||
}) : super(const SettingsState.loading());
|
||||
|
||||
Future<void> init() async {
|
||||
@@ -30,10 +34,12 @@ class SettingsCubit extends Cubit<SettingsState> {
|
||||
late final ConsultationRequestModel? consultantInfo;
|
||||
late final bool hasActiveConsultation;
|
||||
late final OAuthAccountsDataModel? oauthAccounts;
|
||||
|
||||
|
||||
try {
|
||||
if (profile.phoneConfirmationState.contains('confirmed')) {
|
||||
consultantInfo = await consultantRepository.getMyRequestStatus(profile.slug);
|
||||
consultantInfo = await consultantRepository.getMyRequestStatus(
|
||||
profile.slug,
|
||||
);
|
||||
} else {
|
||||
consultantInfo = null;
|
||||
}
|
||||
@@ -41,14 +47,14 @@ class SettingsCubit extends Cubit<SettingsState> {
|
||||
await reportFrom(e, st, this);
|
||||
consultantInfo = null;
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
hasActiveConsultation = await _checkActiveConsultation();
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
hasActiveConsultation = false;
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
final oauthResponse = await settingsRepository.getOAuthAccounts();
|
||||
oauthAccounts = oauthResponse.data;
|
||||
@@ -56,7 +62,7 @@ class SettingsCubit extends Cubit<SettingsState> {
|
||||
await reportFrom(e, st, this);
|
||||
oauthAccounts = null;
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
emit(
|
||||
SettingsState.loaded(
|
||||
@@ -74,9 +80,13 @@ class SettingsCubit extends Cubit<SettingsState> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateProfileDetails({required ProfileDetailsModel profileDetailsModel}) async {
|
||||
Future<void> updateProfileDetails({
|
||||
required ProfileDetailsModel profileDetailsModel,
|
||||
}) async {
|
||||
try {
|
||||
await settingsRepository.updateProfileDetails(profileDetailsModel: profileDetailsModel);
|
||||
await settingsRepository.updateProfileDetails(
|
||||
profileDetailsModel: profileDetailsModel,
|
||||
);
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
} finally {
|
||||
@@ -84,9 +94,13 @@ class SettingsCubit extends Cubit<SettingsState> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> updateProfileSettings({required ProfileSettingsModel profileSettingsModel}) async {
|
||||
Future<void> updateProfileSettings({
|
||||
required ProfileSettingsModel profileSettingsModel,
|
||||
}) async {
|
||||
try {
|
||||
await settingsRepository.updateProfileSettings(profileSettingsModel: profileSettingsModel);
|
||||
await settingsRepository.updateProfileSettings(
|
||||
profileSettingsModel: profileSettingsModel,
|
||||
);
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
} finally {
|
||||
@@ -97,9 +111,15 @@ class SettingsCubit extends Cubit<SettingsState> {
|
||||
Future<bool> deleteAccount() async {
|
||||
try {
|
||||
await profileRepository.deleteAccount();
|
||||
await sessionLifecycleService.endSession(
|
||||
reason: SessionEndReason.accountDeleted,
|
||||
);
|
||||
return true;
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
if (e is DioException && e.response?.statusCode == 401) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -135,11 +155,14 @@ class SettingsCubit extends Cubit<SettingsState> {
|
||||
|
||||
Future<bool> _checkActiveConsultation() async {
|
||||
try {
|
||||
final userPurchases = await consultationsRepository.getUserPurchases(null, null);
|
||||
final userPurchases = await consultationsRepository.getUserPurchases(
|
||||
null,
|
||||
null,
|
||||
);
|
||||
final activeStates = ChosenPlanStateEnum.getActiveStates();
|
||||
|
||||
return userPurchases.any((purchase) =>
|
||||
activeStates.contains(purchase.chosenPlanState)
|
||||
|
||||
return userPurchases.any(
|
||||
(purchase) => activeStates.contains(purchase.chosenPlanState),
|
||||
);
|
||||
} catch (e, st) {
|
||||
await reportFrom(e, st, this);
|
||||
|
||||
@@ -698,7 +698,6 @@ class _DeleteAccountBottomSheet extends State<DeleteAccountBottomSheet> {
|
||||
onPressed: () async {
|
||||
final result = await widget.cubit.deleteAccount();
|
||||
if (result == true) {
|
||||
AppRouter.navigatorKey.currentContext?.go('/auth-screen');
|
||||
return;
|
||||
}
|
||||
AppRouter.navigatorKey.currentContext?.pop();
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
String formatRecordingDuration(int? durationSeconds) {
|
||||
if (durationSeconds == null || durationSeconds < 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
final hours = durationSeconds ~/ 3600;
|
||||
final minutes = (durationSeconds % 3600) ~/ 60;
|
||||
final seconds = durationSeconds % 60;
|
||||
|
||||
final mm = minutes.toString().padLeft(2, '0');
|
||||
final ss = seconds.toString().padLeft(2, '0');
|
||||
|
||||
if (hours > 0) {
|
||||
return '$hours:$mm:$ss';
|
||||
}
|
||||
|
||||
return '$mm:$ss';
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
class RecordingNotReadyException implements Exception {
|
||||
const RecordingNotReadyException({this.message});
|
||||
|
||||
final String? message;
|
||||
|
||||
static const code = 'recording_not_ready';
|
||||
|
||||
@override
|
||||
String toString() => message ?? 'Recording is not ready';
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/// Период фильтра списка записей.
|
||||
/// Значение совпадает с `filters[created_at][$date_range]`.
|
||||
enum RecordingPeriod {
|
||||
today('today'),
|
||||
week('week'),
|
||||
currentMonth('current_month'),
|
||||
prevMonth('prev_month'),
|
||||
all('all');
|
||||
|
||||
const RecordingPeriod(this.apiValue);
|
||||
|
||||
final String apiValue;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import 'package:eatvio_app/core/models/pagination_model.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'video_call_recording_model.freezed.dart';
|
||||
part 'video_call_recording_model.g.dart';
|
||||
|
||||
@freezed
|
||||
abstract class VideoCallRecordingsPagination with _$VideoCallRecordingsPagination {
|
||||
const factory VideoCallRecordingsPagination({
|
||||
@JsonKey(name: 'data') required List<VideoCallRecordingModel> data,
|
||||
@JsonKey(name: 'links') required Links links,
|
||||
@JsonKey(name: 'meta') required Meta meta,
|
||||
}) = _VideoCallRecordingsPagination;
|
||||
|
||||
factory VideoCallRecordingsPagination.fromJson(Map<String, dynamic> json) =>
|
||||
_$VideoCallRecordingsPaginationFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class VideoCallRecordingModel with _$VideoCallRecordingModel {
|
||||
const VideoCallRecordingModel._();
|
||||
|
||||
const factory VideoCallRecordingModel({
|
||||
@JsonKey(name: 'id') required int id,
|
||||
@JsonKey(name: 'status') required String status,
|
||||
@JsonKey(name: 'duration_seconds') int? durationSeconds,
|
||||
@JsonKey(name: 'size_bytes') int? sizeBytes,
|
||||
@JsonKey(name: 'created_at') required DateTime createdAt,
|
||||
@JsonKey(name: 'preview_url') required String previewUrl,
|
||||
@JsonKey(name: 'file_url') String? fileUrl,
|
||||
@JsonKey(name: 'counterpart') VideoCallRecordingCounterpartModel? counterpart,
|
||||
}) = _VideoCallRecordingModel;
|
||||
|
||||
factory VideoCallRecordingModel.fromJson(Map<String, dynamic> json) =>
|
||||
_$VideoCallRecordingModelFromJson(json);
|
||||
|
||||
bool get isReady => status == 'ready';
|
||||
|
||||
bool get isInProgress => status == 'in_progress';
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class VideoCallRecordingCounterpartModel with _$VideoCallRecordingCounterpartModel {
|
||||
const factory VideoCallRecordingCounterpartModel({
|
||||
@JsonKey(name: 'name') required String name,
|
||||
@JsonKey(name: 'slug') required String slug,
|
||||
@JsonKey(name: 'profile_photo_url') String? profilePhotoUrl,
|
||||
}) = _VideoCallRecordingCounterpartModel;
|
||||
|
||||
factory VideoCallRecordingCounterpartModel.fromJson(Map<String, dynamic> json) =>
|
||||
_$VideoCallRecordingCounterpartModelFromJson(json);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import 'dart:developer';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:eatvio_app/core/error_reporting/report_from.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/recording_period.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_state.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
class VideoCallRecordingsCubit extends Cubit<VideoCallRecordingsState> {
|
||||
VideoCallRecordingsCubit({required this.repository})
|
||||
: super(const VideoCallRecordingsState());
|
||||
|
||||
final VideoCallRecordingsRepository repository;
|
||||
|
||||
Future<void> load({bool refresh = false}) async {
|
||||
if (state.isLoading && !refresh && state.recordings.isNotEmpty) {
|
||||
return;
|
||||
}
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
isLoading: true,
|
||||
error: null,
|
||||
currentPage: 1,
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
final page = await repository.getRecordings(
|
||||
page: 1,
|
||||
period: state.period == RecordingPeriod.all ? null : state.period,
|
||||
);
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
isLoading: false,
|
||||
recordings: page.data,
|
||||
currentPage: page.meta.currentPage,
|
||||
lastPage: page.meta.lastPage,
|
||||
error: null,
|
||||
),
|
||||
);
|
||||
} catch (error, stackTrace) {
|
||||
await reportFrom(error, stackTrace, this);
|
||||
log(error.toString(), stackTrace: stackTrace);
|
||||
emit(
|
||||
state.copyWith(
|
||||
isLoading: false,
|
||||
error: error.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setPeriod(RecordingPeriod period) async {
|
||||
if (state.period == period) {
|
||||
return;
|
||||
}
|
||||
|
||||
emit(state.copyWith(period: period));
|
||||
await load(refresh: true);
|
||||
}
|
||||
|
||||
Future<void> loadNextPage() async {
|
||||
if (state.isLoading || state.isLoadingMore || state.currentPage >= state.lastPage) {
|
||||
return;
|
||||
}
|
||||
|
||||
final nextPage = state.currentPage + 1;
|
||||
emit(state.copyWith(isLoadingMore: true, error: null));
|
||||
|
||||
try {
|
||||
final page = await repository.getRecordings(
|
||||
page: nextPage,
|
||||
period: state.period == RecordingPeriod.all ? null : state.period,
|
||||
);
|
||||
|
||||
emit(
|
||||
state.copyWith(
|
||||
isLoadingMore: false,
|
||||
recordings: [...state.recordings, ...page.data],
|
||||
currentPage: page.meta.currentPage,
|
||||
lastPage: page.meta.lastPage,
|
||||
),
|
||||
);
|
||||
} catch (error, stackTrace) {
|
||||
await reportFrom(error, stackTrace, this);
|
||||
log(error.toString(), stackTrace: stackTrace);
|
||||
emit(
|
||||
state.copyWith(
|
||||
isLoadingMore: false,
|
||||
error: error.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<File?> downloadRecording({
|
||||
required int recordingId,
|
||||
required String fileUrl,
|
||||
}) async {
|
||||
emit(state.copyWith(isDownloading: true, downloadError: null));
|
||||
|
||||
try {
|
||||
final file = await repository.downloadRecordingFile(
|
||||
fileUrl: fileUrl,
|
||||
recordingId: recordingId,
|
||||
);
|
||||
emit(state.copyWith(isDownloading: false));
|
||||
return file;
|
||||
} catch (error, stackTrace) {
|
||||
await reportFrom(error, stackTrace, this);
|
||||
log(error.toString(), stackTrace: stackTrace);
|
||||
emit(
|
||||
state.copyWith(
|
||||
isDownloading: false,
|
||||
downloadError: error.toString(),
|
||||
),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/recording_period.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'video_call_recordings_state.freezed.dart';
|
||||
|
||||
@freezed
|
||||
abstract class VideoCallRecordingsState with _$VideoCallRecordingsState {
|
||||
const factory VideoCallRecordingsState({
|
||||
@Default(true) bool isLoading,
|
||||
@Default(false) bool isLoadingMore,
|
||||
@Default(false) bool isDownloading,
|
||||
@Default(<VideoCallRecordingModel>[]) List<VideoCallRecordingModel> recordings,
|
||||
@Default(RecordingPeriod.all) RecordingPeriod period,
|
||||
@Default(1) int currentPage,
|
||||
@Default(1) int lastPage,
|
||||
String? error,
|
||||
String? downloadError,
|
||||
}) = _VideoCallRecordingsState;
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/core/widgets/loader.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:fluttertoast/fluttertoast.dart';
|
||||
import 'package:share_plus/share_plus.dart';
|
||||
import 'package:video_player/video_player.dart';
|
||||
|
||||
class VideoCallRecordingPlayerScreen extends StatefulWidget {
|
||||
const VideoCallRecordingPlayerScreen({super.key, required this.recording});
|
||||
|
||||
static const name = 'videoCallRecordingPlayerScreen';
|
||||
static const path = '/video-call-recording-player-screen';
|
||||
|
||||
final VideoCallRecordingModel recording;
|
||||
|
||||
@override
|
||||
State<VideoCallRecordingPlayerScreen> createState() => _VideoCallRecordingPlayerScreenState();
|
||||
}
|
||||
|
||||
class _VideoCallRecordingPlayerScreenState extends State<VideoCallRecordingPlayerScreen> {
|
||||
VideoPlayerController? _controller;
|
||||
bool _isInitializing = true;
|
||||
bool _hasError = false;
|
||||
bool _isDownloading = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_initPlayer();
|
||||
}
|
||||
|
||||
Future<void> _initPlayer() async {
|
||||
final fileUrl = widget.recording.fileUrl;
|
||||
if (fileUrl == null || fileUrl.isEmpty) {
|
||||
setState(() {
|
||||
_isInitializing = false;
|
||||
_hasError = true;
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final token = await TokenStorage.getTokenFromStorage();
|
||||
final controller = VideoPlayerController.networkUrl(
|
||||
Uri.parse(fileUrl),
|
||||
httpHeaders: {
|
||||
if (token != null && token.isNotEmpty) 'Authorization': 'Bearer $token',
|
||||
},
|
||||
);
|
||||
await controller.initialize();
|
||||
await controller.play();
|
||||
if (!mounted) {
|
||||
await controller.dispose();
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_controller = controller;
|
||||
_isInitializing = false;
|
||||
});
|
||||
} catch (_) {
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_isInitializing = false;
|
||||
_hasError = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _download() async {
|
||||
final fileUrl = widget.recording.fileUrl;
|
||||
if (fileUrl == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() => _isDownloading = true);
|
||||
try {
|
||||
final file = await sl<VideoCallRecordingsRepository>().downloadRecordingFile(
|
||||
fileUrl: fileUrl,
|
||||
recordingId: widget.recording.id,
|
||||
);
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
await SharePlus.instance.share(
|
||||
ShareParams(
|
||||
files: [XFile(file.path)],
|
||||
text: S.of(context).video_call_recordings_card_title,
|
||||
),
|
||||
);
|
||||
} catch (_) {
|
||||
if (mounted) {
|
||||
await Fluttertoast.showToast(msg: S.of(context).video_call_recordings_download_error);
|
||||
}
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _isDownloading = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = S.of(context);
|
||||
final title = widget.recording.counterpart?.name ?? s.video_call_recordings_title;
|
||||
final controller = _controller;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: appTheme.whiteA700,
|
||||
appBar: AppBar(
|
||||
centerTitle: true,
|
||||
title: Text(
|
||||
title,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black),
|
||||
),
|
||||
),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
|
||||
child: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Center(
|
||||
child: _isInitializing
|
||||
? const Loader()
|
||||
: _hasError || controller == null
|
||||
? Text(
|
||||
s.video_call_recordings_player_error,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyles.textMMedium.copyWith(color: appTheme.blueGray400),
|
||||
)
|
||||
: AspectRatio(
|
||||
aspectRatio: controller.value.aspectRatio == 0
|
||||
? 16 / 9
|
||||
: controller.value.aspectRatio,
|
||||
child: Stack(
|
||||
alignment: Alignment.bottomCenter,
|
||||
children: [
|
||||
VideoPlayer(controller),
|
||||
_PlayerControls(controller: controller),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
height: 44,
|
||||
child: ElevatedButton(
|
||||
onPressed: _isDownloading || widget.recording.fileUrl == null ? null : _download,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: appTheme.blueA400,
|
||||
foregroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
child: _isDownloading
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
|
||||
)
|
||||
: Text(
|
||||
s.video_call_recordings_download,
|
||||
style: TextStyles.textSMedium.copyWith(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PlayerControls extends StatelessWidget {
|
||||
const _PlayerControls({required this.controller});
|
||||
|
||||
final VideoPlayerController controller;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AnimatedBuilder(
|
||||
animation: controller,
|
||||
builder: (context, _) {
|
||||
return ColoredBox(
|
||||
color: Colors.black.withValues(alpha: 0.35),
|
||||
child: Row(
|
||||
children: [
|
||||
IconButton(
|
||||
onPressed: () {
|
||||
if (controller.value.isPlaying) {
|
||||
controller.pause();
|
||||
} else {
|
||||
controller.play();
|
||||
}
|
||||
},
|
||||
icon: Icon(
|
||||
controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: VideoProgressIndicator(
|
||||
controller,
|
||||
allowScrubbing: true,
|
||||
colors: VideoProgressColors(
|
||||
playedColor: appTheme.blueA400,
|
||||
bufferedColor: Colors.white38,
|
||||
backgroundColor: Colors.white24,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/widgets/data_error_widget.dart';
|
||||
import 'package:eatvio_app/core/widgets/loader.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_cubit.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/presentation/cubit/video_call_recordings_state.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/presentation/pages/video_call_recording_player_screen.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/presentation/widgets/recording_card.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/presentation/widgets/recording_period_dropdown.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:fluttertoast/fluttertoast.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:share_plus/share_plus.dart';
|
||||
|
||||
class VideoCallRecordingsScreen extends StatelessWidget {
|
||||
const VideoCallRecordingsScreen({super.key});
|
||||
|
||||
static const name = 'videoCallRecordingsScreen';
|
||||
static const path = '/video-call-recordings-screen';
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocProvider(
|
||||
create: (_) => sl<VideoCallRecordingsCubit>()..load(),
|
||||
child: const _VideoCallRecordingsView(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _VideoCallRecordingsView extends StatefulWidget {
|
||||
const _VideoCallRecordingsView();
|
||||
|
||||
@override
|
||||
State<_VideoCallRecordingsView> createState() => _VideoCallRecordingsViewState();
|
||||
}
|
||||
|
||||
class _VideoCallRecordingsViewState extends State<_VideoCallRecordingsView> {
|
||||
final _scrollController = ScrollController();
|
||||
int? _downloadingId;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_scrollController.addListener(_onScroll);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_scrollController
|
||||
..removeListener(_onScroll)
|
||||
..dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onScroll() {
|
||||
if (!_scrollController.hasClients) {
|
||||
return;
|
||||
}
|
||||
final position = _scrollController.position;
|
||||
if (position.pixels >= position.maxScrollExtent - 200) {
|
||||
context.read<VideoCallRecordingsCubit>().loadNextPage();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _download(VideoCallRecordingModel recording) async {
|
||||
final fileUrl = recording.fileUrl;
|
||||
if (fileUrl == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() => _downloadingId = recording.id);
|
||||
final file = await context.read<VideoCallRecordingsCubit>().downloadRecording(
|
||||
recordingId: recording.id,
|
||||
fileUrl: fileUrl,
|
||||
);
|
||||
if (!mounted) {
|
||||
return;
|
||||
}
|
||||
setState(() => _downloadingId = null);
|
||||
|
||||
if (file == null) {
|
||||
final error = context.read<VideoCallRecordingsCubit>().state.downloadError;
|
||||
await Fluttertoast.showToast(
|
||||
msg: error ?? S.of(context).video_call_recordings_download_error,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await SharePlus.instance.share(
|
||||
ShareParams(files: [XFile(file.path)], text: S.of(context).video_call_recordings_card_title),
|
||||
);
|
||||
}
|
||||
|
||||
void _openPlayer(VideoCallRecordingModel recording) {
|
||||
final fileUrl = recording.fileUrl;
|
||||
if (fileUrl == null) {
|
||||
return;
|
||||
}
|
||||
GoRouter.of(context).push(
|
||||
VideoCallRecordingPlayerScreen.path,
|
||||
extra: recording,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = S.of(context);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: appTheme.whiteA700,
|
||||
appBar: AppBar(
|
||||
centerTitle: true,
|
||||
title: Text(
|
||||
s.video_call_recordings_title,
|
||||
style: TextStyles.headingXLSemibold.copyWith(color: appTheme.black),
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
tooltip: s.video_call_recordings_retention_tooltip,
|
||||
onPressed: () {
|
||||
showDialog<void>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
content: Text(s.video_call_recordings_retention_tooltip),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('OK'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
icon: Icon(Icons.help_outline, color: appTheme.blueA400),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: BlocBuilder<VideoCallRecordingsCubit, VideoCallRecordingsState>(
|
||||
builder: (context, state) {
|
||||
return Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),
|
||||
child: RecordingPeriodDropdown(
|
||||
value: state.period,
|
||||
onChanged: (period) => context.read<VideoCallRecordingsCubit>().setPeriod(period),
|
||||
),
|
||||
),
|
||||
Expanded(child: _buildBody(context, state, s)),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBody(BuildContext context, VideoCallRecordingsState state, S s) {
|
||||
if (state.isLoading && state.recordings.isEmpty) {
|
||||
return const Loader();
|
||||
}
|
||||
|
||||
if (state.error != null && state.recordings.isEmpty) {
|
||||
return DataErrorWidget(
|
||||
onReload: () => context.read<VideoCallRecordingsCubit>().load(refresh: true),
|
||||
);
|
||||
}
|
||||
|
||||
if (state.recordings.isEmpty) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text(
|
||||
s.video_call_recordings_empty,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyles.textMMedium.copyWith(color: appTheme.blueGray400),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return RefreshIndicator(
|
||||
onRefresh: () => context.read<VideoCallRecordingsCubit>().load(refresh: true),
|
||||
child: ListView.separated(
|
||||
controller: _scrollController,
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 24),
|
||||
itemCount: state.recordings.length + (state.isLoadingMore ? 1 : 0),
|
||||
separatorBuilder: (_, _) => const SizedBox(height: 16),
|
||||
itemBuilder: (context, index) {
|
||||
if (index >= state.recordings.length) {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 16),
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
}
|
||||
|
||||
final recording = state.recordings[index];
|
||||
return RecordingCard(
|
||||
recording: recording,
|
||||
isDownloading: _downloadingId == recording.id,
|
||||
onPlay: () => _openPlayer(recording),
|
||||
onDownload: () => _download(recording),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
import 'package:cached_network_image/cached_network_image.dart';
|
||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/utils/date_time_utils.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/recording_duration_formatter.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class RecordingCard extends StatelessWidget {
|
||||
const RecordingCard({
|
||||
super.key,
|
||||
required this.recording,
|
||||
required this.onPlay,
|
||||
required this.onDownload,
|
||||
this.isDownloading = false,
|
||||
});
|
||||
|
||||
final VideoCallRecordingModel recording;
|
||||
final VoidCallback onPlay;
|
||||
final VoidCallback onDownload;
|
||||
final bool isDownloading;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = S.of(context);
|
||||
final isReady = recording.isReady;
|
||||
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
color: appTheme.whiteA700,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.15),
|
||||
blurRadius: 10,
|
||||
offset: const Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
AspectRatio(
|
||||
aspectRatio: 1.775,
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
ColoredBox(
|
||||
color: appTheme.dividerColor,
|
||||
child: CachedNetworkImage(
|
||||
imageUrl: recording.previewUrl,
|
||||
fit: BoxFit.cover,
|
||||
errorWidget: (_, _, _) => ColoredBox(color: appTheme.dividerColor),
|
||||
),
|
||||
),
|
||||
if (isReady) ...[
|
||||
Center(
|
||||
child: Material(
|
||||
color: Colors.transparent,
|
||||
child: InkWell(
|
||||
onTap: onPlay,
|
||||
customBorder: const CircleBorder(),
|
||||
child: Container(
|
||||
width: 40,
|
||||
height: 40,
|
||||
decoration: BoxDecoration(
|
||||
color: appTheme.blueA400,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: const Icon(Icons.play_arrow, color: Colors.white, size: 28),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (recording.durationSeconds != null)
|
||||
Positioned(
|
||||
right: 8,
|
||||
bottom: 8,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.7),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Text(
|
||||
formatRecordingDuration(recording.durationSeconds),
|
||||
style: TextStyles.textSMedium.copyWith(
|
||||
color: Colors.white,
|
||||
fontSize: 10,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
] else
|
||||
ColoredBox(
|
||||
color: Colors.white.withValues(alpha: 0.72),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 28,
|
||||
height: 28,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2.5,
|
||||
color: appTheme.blueA400,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Text(
|
||||
s.video_call_recordings_processing,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyles.textSMedium.copyWith(color: appTheme.black),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 12, 12, 12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
s.video_call_recordings_card_title,
|
||||
style: TextStyles.textMMedium.copyWith(
|
||||
color: appTheme.black900,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
_CounterpartAvatar(counterpart: recording.counterpart),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
recording.counterpart?.name ?? s.video_call_counterpart_default,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyles.textSMedium.copyWith(
|
||||
color: const Color(0xFF666666),
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
),
|
||||
Container(
|
||||
width: 3,
|
||||
height: 3,
|
||||
margin: const EdgeInsets.symmetric(horizontal: 6),
|
||||
decoration: const BoxDecoration(
|
||||
color: Color(0xFF666666),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
recording.createdAt.format('d MMMM yyyy, HH:mm', 'ru'),
|
||||
style: TextStyles.textSMedium.copyWith(
|
||||
color: const Color(0xFF666666),
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (isReady) ...[
|
||||
const SizedBox(height: 12),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
height: 40,
|
||||
child: ElevatedButton(
|
||||
onPressed: isDownloading ? null : onDownload,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: appTheme.blueA400,
|
||||
foregroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
child: isDownloading
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
)
|
||||
: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
s.video_call_recordings_download,
|
||||
style: TextStyles.textSMedium.copyWith(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
const Icon(Icons.download, size: 20),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CounterpartAvatar extends StatelessWidget {
|
||||
const _CounterpartAvatar({required this.counterpart});
|
||||
|
||||
final VideoCallRecordingCounterpartModel? counterpart;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final url = counterpart?.profilePhotoUrl;
|
||||
return ClipOval(
|
||||
child: SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: url != null && url.isNotEmpty
|
||||
? CachedNetworkImage(
|
||||
imageUrl: url,
|
||||
fit: BoxFit.cover,
|
||||
errorWidget: (_, _, _) => _placeholder(),
|
||||
)
|
||||
: _placeholder(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _placeholder() {
|
||||
return ColoredBox(
|
||||
color: appTheme.backgroundAvatar,
|
||||
child: Icon(Icons.person, size: 16, color: appTheme.blueGray400),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import 'package:eatvio_app/core/theme/custom_text_style.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/widgets/custom_drop_down_button.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/recording_period.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class RecordingPeriodDropdown extends StatelessWidget {
|
||||
const RecordingPeriodDropdown({
|
||||
super.key,
|
||||
required this.value,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final RecordingPeriod value;
|
||||
final ValueChanged<RecordingPeriod> onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = S.of(context);
|
||||
|
||||
String label(RecordingPeriod period) => switch (period) {
|
||||
RecordingPeriod.today => s.video_call_recordings_period_today,
|
||||
RecordingPeriod.week => s.video_call_recordings_period_week,
|
||||
RecordingPeriod.currentMonth => s.video_call_recordings_period_current_month,
|
||||
RecordingPeriod.prevMonth => s.video_call_recordings_period_prev_month,
|
||||
RecordingPeriod.all => s.video_call_recordings_period_all,
|
||||
};
|
||||
|
||||
return CustomDropDownButton<RecordingPeriod>(
|
||||
key: ValueKey(value),
|
||||
isExpanded: true,
|
||||
value: value,
|
||||
onChanged: (period) {
|
||||
if (period != null) {
|
||||
onChanged(period);
|
||||
}
|
||||
},
|
||||
items: RecordingPeriod.values
|
||||
.map(
|
||||
(period) => DropdownMenuItem(
|
||||
value: period,
|
||||
child: Text(
|
||||
label(period),
|
||||
style: TextStyles.textMMedium.copyWith(color: appTheme.black),
|
||||
),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/recording_not_ready_exception.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/recording_period.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart';
|
||||
import 'package:eatvio_app/features/video_calls/services/video_call_service.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
class VideoCallRecordingsRepository {
|
||||
VideoCallRecordingsRepository({
|
||||
required this.videoCallService,
|
||||
required this.dio,
|
||||
});
|
||||
|
||||
final VideoCallService videoCallService;
|
||||
final Dio dio;
|
||||
|
||||
Future<VideoCallRecordingsPagination> getRecordings({
|
||||
required int page,
|
||||
RecordingPeriod? period,
|
||||
}) {
|
||||
return videoCallService.getRecordings(
|
||||
page: page,
|
||||
dateRange: period?.apiValue,
|
||||
);
|
||||
}
|
||||
|
||||
/// Скачивает файл записи во временную директорию.
|
||||
///
|
||||
/// [fileUrl] — абсолютный URL из `file_url` ответа списка.
|
||||
Future<File> downloadRecordingFile({
|
||||
required String fileUrl,
|
||||
required int recordingId,
|
||||
}) async {
|
||||
try {
|
||||
final uri = Uri.parse(fileUrl).replace(
|
||||
queryParameters: <String, String>{
|
||||
...Uri.parse(fileUrl).queryParameters,
|
||||
'download': '1',
|
||||
},
|
||||
);
|
||||
|
||||
final directory = await getTemporaryDirectory();
|
||||
final targetPath = '${directory.path}/recording_$recordingId.mp4';
|
||||
|
||||
await dio.download(
|
||||
uri.toString(),
|
||||
targetPath,
|
||||
options: Options(
|
||||
responseType: ResponseType.bytes,
|
||||
validateStatus: (status) => status != null && status < 400,
|
||||
),
|
||||
);
|
||||
|
||||
return File(targetPath);
|
||||
} on DioException catch (error) {
|
||||
_throwIfNotReady(error);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
void _throwIfNotReady(DioException error) {
|
||||
if (error.response?.statusCode != 409) {
|
||||
return;
|
||||
}
|
||||
|
||||
final data = error.response?.data;
|
||||
String? message;
|
||||
String? code;
|
||||
|
||||
if (data is Map) {
|
||||
message = data['message']?.toString();
|
||||
code = data['code']?.toString();
|
||||
}
|
||||
|
||||
if (code == RecordingNotReadyException.code || code == null) {
|
||||
throw RecordingNotReadyException(message: message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/features/video_calls/models/video_call_models.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart';
|
||||
import 'package:retrofit/retrofit.dart';
|
||||
|
||||
part 'video_call_service.g.dart';
|
||||
@@ -36,4 +37,10 @@ abstract class VideoCallService {
|
||||
@Path('conversation') required String conversationUuid,
|
||||
@Body() required Map<String, dynamic> body,
|
||||
});
|
||||
|
||||
@GET('/api/video-call/recordings')
|
||||
Future<VideoCallRecordingsPagination> getRecordings({
|
||||
@Query('page') required int page,
|
||||
@Query(r'filters[created_at][$date_range]') String? dateRange,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -22,32 +22,50 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
|
||||
static String m0(date) => "Консультант прокомментировал день ${date}";
|
||||
|
||||
static String m1(planName) => "План «${planName}» начался";
|
||||
static String m1(userName) =>
|
||||
"You have proposed a personal diet to ${userName}";
|
||||
|
||||
static String m2(planName, name) =>
|
||||
static String m2(userName, dietName) =>
|
||||
"You have proposed a personal diet to ${userName}, selected diet: «${dietName}»";
|
||||
|
||||
static String m3(duration, dayWord) =>
|
||||
"The diet lasts ${duration} ${dayWord}. It can only be offered for a plan with the same duration.";
|
||||
|
||||
static String m4(dietDuration, dietDayWord, planDuration, planDayWord) =>
|
||||
"Not suitable: diet lasts ${dietDuration} ${dietDayWord}, plan lasts ${planDuration} ${planDayWord}.";
|
||||
|
||||
static String m5(name) => "Diet «${name}» proposed";
|
||||
|
||||
static String m6(planName) => "План «${planName}» начался";
|
||||
|
||||
static String m7(planName, name) =>
|
||||
"План «${planName}» с пользователем ${name} начался";
|
||||
|
||||
static String m3(percent, amount) =>
|
||||
static String m8(duration, dayWord) => "Plan for ${duration} ${dayWord}";
|
||||
|
||||
static String m9(percent, amount) =>
|
||||
"Discount ${percent}% — you save ${amount} ₽";
|
||||
|
||||
static String m4(step) => "шаг ${step} из 2";
|
||||
static String m10(date) => "Start: ${date}";
|
||||
|
||||
static String m5(planName, name) =>
|
||||
static String m11(step) => "шаг ${step} из 2";
|
||||
|
||||
static String m12(planName, name) =>
|
||||
"Завтра начинается план «${planName}» с пользователем ${name}";
|
||||
|
||||
static String m6(planName) =>
|
||||
static String m13(planName) =>
|
||||
"Завтра начнется прохождение плана «${planName}»";
|
||||
|
||||
static String m7(name, planName) =>
|
||||
static String m14(name, planName) =>
|
||||
"Пользователь ${name} отменил подписку на план «${planName}»";
|
||||
|
||||
static String m8(name, planName) =>
|
||||
static String m15(name, planName) =>
|
||||
"Пользователь ${name} оплатил план «${planName}»";
|
||||
|
||||
static String m9(name, planName) =>
|
||||
static String m16(name, planName) =>
|
||||
"Пользователь ${name} подписался на план «${planName}»";
|
||||
|
||||
static String m10(planName) => "Вы отменили подписку на план «${planName}»";
|
||||
static String m17(planName) => "Вы отменили подписку на план «${planName}»";
|
||||
|
||||
final messages = _notInlinedMessages(_notInlinedMessages);
|
||||
static Map<String, Function> _notInlinedMessages(_) => <String, Function>{
|
||||
@@ -170,6 +188,9 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
),
|
||||
"carbohydrates": MessageLookupByLibrary.simpleMessage("Углеводы"),
|
||||
"changeDiet": MessageLookupByLibrary.simpleMessage("Заменить диету"),
|
||||
"change_personal_diet": MessageLookupByLibrary.simpleMessage(
|
||||
"Change personal diet",
|
||||
),
|
||||
"chargeApproved": MessageLookupByLibrary.simpleMessage("Выплата одобрена"),
|
||||
"chargeCollectionFailed": MessageLookupByLibrary.simpleMessage(
|
||||
"Не удалось оформить выплату",
|
||||
@@ -317,6 +338,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
),
|
||||
"days": MessageLookupByLibrary.simpleMessage("дней"),
|
||||
"deception": MessageLookupByLibrary.simpleMessage("Обман"),
|
||||
"default_user_name": MessageLookupByLibrary.simpleMessage("User"),
|
||||
"delete": MessageLookupByLibrary.simpleMessage("Удалить"),
|
||||
"deleteComment": MessageLookupByLibrary.simpleMessage(
|
||||
"Удалить комментарий",
|
||||
@@ -604,6 +626,10 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"nicotine": MessageLookupByLibrary.simpleMessage("Никотин"),
|
||||
"no": MessageLookupByLibrary.simpleMessage("Нет"),
|
||||
"no_account": MessageLookupByLibrary.simpleMessage("У меня нет аккаунта"),
|
||||
"no_active_personal_diet_consultations":
|
||||
MessageLookupByLibrary.simpleMessage(
|
||||
"No active consultations with a personal diet",
|
||||
),
|
||||
"no_default_cards": MessageLookupByLibrary.simpleMessage(
|
||||
"У вас нет привязанных карт. Что бы начать работу, привяжите карту",
|
||||
),
|
||||
@@ -635,6 +661,9 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"order": MessageLookupByLibrary.simpleMessage("Порядок"),
|
||||
"orderCanceled": MessageLookupByLibrary.simpleMessage("Заказ отменен"),
|
||||
"order_created": MessageLookupByLibrary.simpleMessage("Заказ создан"),
|
||||
"order_in_progress": MessageLookupByLibrary.simpleMessage(
|
||||
"Order in progress",
|
||||
),
|
||||
"order_paid": MessageLookupByLibrary.simpleMessage("Заказ оплачен"),
|
||||
"order_price": MessageLookupByLibrary.simpleMessage("Сумма заказа"),
|
||||
"order_status": MessageLookupByLibrary.simpleMessage("Статус заказа"),
|
||||
@@ -658,6 +687,9 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"В пароле должно быть минимум 6 символов",
|
||||
),
|
||||
"pay": MessageLookupByLibrary.simpleMessage("Оплатить"),
|
||||
"pay_by_qr_code": MessageLookupByLibrary.simpleMessage(
|
||||
"Оплатить по QR-коду",
|
||||
),
|
||||
"payment_failed": MessageLookupByLibrary.simpleMessage("Оплата не прошла"),
|
||||
"pcs": MessageLookupByLibrary.simpleMessage("шт"),
|
||||
"pending_payment": MessageLookupByLibrary.simpleMessage("Ожидается оплата"),
|
||||
@@ -665,6 +697,20 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"personalDietCreating": MessageLookupByLibrary.simpleMessage(
|
||||
"Составление индивидуальной диеты",
|
||||
),
|
||||
"personal_diet_defined_to_author": m1,
|
||||
"personal_diet_defined_to_author_named": m2,
|
||||
"personal_diet_duration_hint": m3,
|
||||
"personal_diet_duration_mismatch": m4,
|
||||
"personal_diet_not_proposed": MessageLookupByLibrary.simpleMessage(
|
||||
"Personal diet not proposed",
|
||||
),
|
||||
"personal_diet_proposed": MessageLookupByLibrary.simpleMessage(
|
||||
"Personal diet proposed",
|
||||
),
|
||||
"personal_diet_proposed_named": m5,
|
||||
"personal_diet_replaces_tomorrow": MessageLookupByLibrary.simpleMessage(
|
||||
"The change takes effect tomorrow",
|
||||
),
|
||||
"personal_diet_set": MessageLookupByLibrary.simpleMessage(
|
||||
"Персональная диета установлена",
|
||||
),
|
||||
@@ -681,17 +727,18 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"Физическая форма",
|
||||
),
|
||||
"place_of_living": MessageLookupByLibrary.simpleMessage("Место проживания"),
|
||||
"planStarted": m1,
|
||||
"planStarted": m6,
|
||||
"planWillBeConfirmedAfterThreeDays": MessageLookupByLibrary.simpleMessage(
|
||||
"Если вы не подтвердите, то план через три дня подтвердится автоматически",
|
||||
),
|
||||
"planWithUserStarted": m2,
|
||||
"planWithUserStarted": m7,
|
||||
"plan_author": MessageLookupByLibrary.simpleMessage("Автор плана"),
|
||||
"plan_desc": MessageLookupByLibrary.simpleMessage("Описание плана"),
|
||||
"plan_desc_example": MessageLookupByLibrary.simpleMessage(
|
||||
"Большое подробное, привлекательное описание плана",
|
||||
),
|
||||
"plan_duration": MessageLookupByLibrary.simpleMessage("Срок плана"),
|
||||
"plan_duration_label": m8,
|
||||
"plan_label_desc": MessageLookupByLibrary.simpleMessage(
|
||||
"План для поддержания формы",
|
||||
),
|
||||
@@ -728,7 +775,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"Promo code applied!",
|
||||
),
|
||||
"promo_code": MessageLookupByLibrary.simpleMessage("Promo code"),
|
||||
"promo_discount_hint": m3,
|
||||
"promo_discount_hint": m9,
|
||||
"promo_invalid": MessageLookupByLibrary.simpleMessage(
|
||||
"Promo code not found or expired",
|
||||
),
|
||||
@@ -777,6 +824,34 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"sbp_payment_error": MessageLookupByLibrary.simpleMessage(
|
||||
"Не удалось начать оплату. Попробуйте позже",
|
||||
),
|
||||
"sbp_qr_amount_label": MessageLookupByLibrary.simpleMessage(
|
||||
"Сумма к оплате",
|
||||
),
|
||||
"sbp_qr_open_test_payment": MessageLookupByLibrary.simpleMessage(
|
||||
"Открыть тестовую оплату",
|
||||
),
|
||||
"sbp_qr_paid_description": MessageLookupByLibrary.simpleMessage(
|
||||
"Консультация оплачена. Можно вернуться в чат.",
|
||||
),
|
||||
"sbp_qr_paid_title": MessageLookupByLibrary.simpleMessage(
|
||||
"Оплата прошла успешно!",
|
||||
),
|
||||
"sbp_qr_step1": MessageLookupByLibrary.simpleMessage(
|
||||
"Откройте приложение банка на телефоне",
|
||||
),
|
||||
"sbp_qr_step2": MessageLookupByLibrary.simpleMessage(
|
||||
"Выберите «Оплата по QR-коду»",
|
||||
),
|
||||
"sbp_qr_step3": MessageLookupByLibrary.simpleMessage(
|
||||
"Наведите камеру на код",
|
||||
),
|
||||
"sbp_qr_test_hint": MessageLookupByLibrary.simpleMessage(
|
||||
"Симуляция оплаты на тестовом стенде Альфа-Банка",
|
||||
),
|
||||
"sbp_qr_title": MessageLookupByLibrary.simpleMessage("Оплата по QR-коду"),
|
||||
"sbp_qr_waiting_payment": MessageLookupByLibrary.simpleMessage(
|
||||
"Ожидание оплаты…",
|
||||
),
|
||||
"send": MessageLookupByLibrary.simpleMessage("Отправить"),
|
||||
"send_complain": MessageLookupByLibrary.simpleMessage("Отправить жалобу"),
|
||||
"services": MessageLookupByLibrary.simpleMessage("Оказание услуг"),
|
||||
@@ -821,12 +896,13 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"Выбрана дата старта",
|
||||
),
|
||||
"startDiet": MessageLookupByLibrary.simpleMessage("Начать диету"),
|
||||
"start_date_label": m10,
|
||||
"statistic": MessageLookupByLibrary.simpleMessage("Статистика"),
|
||||
"step": MessageLookupByLibrary.simpleMessage("Шаг"),
|
||||
"step_by_step_photo_recipe": MessageLookupByLibrary.simpleMessage(
|
||||
"Пошаговый фоторецепт",
|
||||
),
|
||||
"step_widget": m4,
|
||||
"step_widget": m11,
|
||||
"successfully_published": MessageLookupByLibrary.simpleMessage(
|
||||
"успешно опубликован",
|
||||
),
|
||||
@@ -851,8 +927,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"toOffer": MessageLookupByLibrary.simpleMessage("Предложить"),
|
||||
"to_draft": MessageLookupByLibrary.simpleMessage("В черновик"),
|
||||
"to_order": MessageLookupByLibrary.simpleMessage("Заказать"),
|
||||
"tommorowPlanWithUserWillStart": m5,
|
||||
"tomorrowYourPlanWillStart": m6,
|
||||
"tommorowPlanWithUserWillStart": m12,
|
||||
"tomorrowYourPlanWillStart": m13,
|
||||
"try_again": MessageLookupByLibrary.simpleMessage("Попробовать снова"),
|
||||
"try_again_2": MessageLookupByLibrary.simpleMessage("Попробуйте ещё раз"),
|
||||
"typeAmoutOfReturn": MessageLookupByLibrary.simpleMessage(
|
||||
@@ -886,7 +962,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"Верхние показатели давления:",
|
||||
),
|
||||
"upper": MessageLookupByLibrary.simpleMessage("Верхнее"),
|
||||
"userCanceldThePlanSubscription": m7,
|
||||
"userCanceldThePlanSubscription": m14,
|
||||
"userConfirmedPlanCompletion": MessageLookupByLibrary.simpleMessage(
|
||||
"Пользователь подтвердил прохождения плана. В ближайшее время Вы получите",
|
||||
),
|
||||
@@ -894,8 +970,8 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
MessageLookupByLibrary.simpleMessage(
|
||||
"Пользователь подтвердил прохождения плана.",
|
||||
),
|
||||
"userPaidThePlan": m8,
|
||||
"userSubscribedToPlan": m9,
|
||||
"userPaidThePlan": m15,
|
||||
"userSubscribedToPlan": m16,
|
||||
"user_authorization": MessageLookupByLibrary.simpleMessage(
|
||||
"Аутентификация",
|
||||
),
|
||||
@@ -961,6 +1037,45 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"video_call_recording_notice": MessageLookupByLibrary.simpleMessage(
|
||||
"The video call will be recorded.\nThe consultation may be reviewed by Eatvio staff for quality assurance.",
|
||||
),
|
||||
"video_call_recordings_card_title": MessageLookupByLibrary.simpleMessage(
|
||||
"Video consultation with a nutrition specialist",
|
||||
),
|
||||
"video_call_recordings_download": MessageLookupByLibrary.simpleMessage(
|
||||
"Download",
|
||||
),
|
||||
"video_call_recordings_download_error":
|
||||
MessageLookupByLibrary.simpleMessage(
|
||||
"Could not download the recording. Please try again later.",
|
||||
),
|
||||
"video_call_recordings_empty": MessageLookupByLibrary.simpleMessage(
|
||||
"No video consultations yet",
|
||||
),
|
||||
"video_call_recordings_period_all": MessageLookupByLibrary.simpleMessage(
|
||||
"All time",
|
||||
),
|
||||
"video_call_recordings_period_current_month":
|
||||
MessageLookupByLibrary.simpleMessage("Current month"),
|
||||
"video_call_recordings_period_prev_month":
|
||||
MessageLookupByLibrary.simpleMessage("Previous month"),
|
||||
"video_call_recordings_period_today": MessageLookupByLibrary.simpleMessage(
|
||||
"Today",
|
||||
),
|
||||
"video_call_recordings_period_week": MessageLookupByLibrary.simpleMessage(
|
||||
"7 days",
|
||||
),
|
||||
"video_call_recordings_player_error": MessageLookupByLibrary.simpleMessage(
|
||||
"Could not play the recording",
|
||||
),
|
||||
"video_call_recordings_processing": MessageLookupByLibrary.simpleMessage(
|
||||
"Recording is being processed…",
|
||||
),
|
||||
"video_call_recordings_retention_tooltip":
|
||||
MessageLookupByLibrary.simpleMessage(
|
||||
"Video consultation recordings are stored on Eatvio servers for 1 year.",
|
||||
),
|
||||
"video_call_recordings_title": MessageLookupByLibrary.simpleMessage(
|
||||
"My consultations",
|
||||
),
|
||||
"video_call_role_consultant": MessageLookupByLibrary.simpleMessage(
|
||||
"Eatvio consultant",
|
||||
),
|
||||
@@ -1025,7 +1140,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"youCanComplain": MessageLookupByLibrary.simpleMessage(
|
||||
"Если вас что-то не устроило, вы можете подать жалобу",
|
||||
),
|
||||
"youCanceledSubscriptionToPlan": m10,
|
||||
"youCanceledSubscriptionToPlan": m17,
|
||||
"youShureYouWantToCancelOrder": MessageLookupByLibrary.simpleMessage(
|
||||
"Вы уверены, что хотите отменить заказ?",
|
||||
),
|
||||
|
||||
@@ -20,9 +20,27 @@ typedef String MessageIfAbsent(String messageStr, List<dynamic> args);
|
||||
class MessageLookup extends MessageLookupByLibrary {
|
||||
String get localeName => 'ru';
|
||||
|
||||
static String m3(percent, amount) =>
|
||||
static String m1(userName) =>
|
||||
"Вы предложили персональную диету пользователю ${userName}";
|
||||
|
||||
static String m2(userName, dietName) =>
|
||||
"Вы предложили персональную диету пользователю ${userName}, выбранная диета: «${dietName}»";
|
||||
|
||||
static String m3(duration, dayWord) =>
|
||||
"Диета рассчитана на ${duration} ${dayWord}. Предложить её можно только для плана с такой же длительностью.";
|
||||
|
||||
static String m4(dietDuration, dietDayWord, planDuration, planDayWord) =>
|
||||
"Не подходит: диета на ${dietDuration} ${dietDayWord}, план на ${planDuration} ${planDayWord}.";
|
||||
|
||||
static String m5(name) => "Диета «${name}» предложена";
|
||||
|
||||
static String m8(duration, dayWord) => "План на ${duration} ${dayWord}";
|
||||
|
||||
static String m9(percent, amount) =>
|
||||
"Скидка ${percent}% — вы экономите ${amount} ₽";
|
||||
|
||||
static String m10(date) => "Старт: ${date}";
|
||||
|
||||
final messages = _notInlinedMessages(_notInlinedMessages);
|
||||
static Map<String, Function> _notInlinedMessages(_) => <String, Function>{
|
||||
"Moscow": MessageLookupByLibrary.simpleMessage("Москва"),
|
||||
@@ -66,6 +84,10 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"Если вы любите мучные продукты, но хотите придерживаться диеты, вам подходит диета с добавленим мучных блюд на основе цельнозерновых вариантов. В них больше сложных углеводов и клетчатки, что способствует длительному чувству сытости и поддерживает здоровье пищеварительной системы.",
|
||||
),
|
||||
"carbohydrates": MessageLookupByLibrary.simpleMessage("Углеводы"),
|
||||
"changeDiet": MessageLookupByLibrary.simpleMessage("Заменить диету"),
|
||||
"change_personal_diet": MessageLookupByLibrary.simpleMessage(
|
||||
"Заменить диету",
|
||||
),
|
||||
"chat": MessageLookupByLibrary.simpleMessage("Чат"),
|
||||
"chest": MessageLookupByLibrary.simpleMessage("Грудь"),
|
||||
"chest_circumference": MessageLookupByLibrary.simpleMessage("Обхват груди"),
|
||||
@@ -78,6 +100,10 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"choose_plan_duration": MessageLookupByLibrary.simpleMessage(
|
||||
"Выберите срок плана",
|
||||
),
|
||||
"choose_plan_start_date_with_personal_diet":
|
||||
MessageLookupByLibrary.simpleMessage(
|
||||
"Выберите дату старта плана питания с учетом составления персональной диеты",
|
||||
),
|
||||
"choose_start_diet_date": MessageLookupByLibrary.simpleMessage(
|
||||
"Выберите дату старты диеты. Она отобразиться у Вас в дневнике",
|
||||
),
|
||||
@@ -110,6 +136,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"date_of_birth": MessageLookupByLibrary.simpleMessage("Дата рождения"),
|
||||
"day": MessageLookupByLibrary.simpleMessage("День"),
|
||||
"days": MessageLookupByLibrary.simpleMessage("дней"),
|
||||
"default_user_name": MessageLookupByLibrary.simpleMessage("Пользователь"),
|
||||
"deleted": MessageLookupByLibrary.simpleMessage("Удалена"),
|
||||
"diary": MessageLookupByLibrary.simpleMessage("Дневник"),
|
||||
"diet": MessageLookupByLibrary.simpleMessage("Диета"),
|
||||
@@ -126,6 +153,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"do_you_take_pills": MessageLookupByLibrary.simpleMessage(
|
||||
"Принимаете ли вы лекарства или бады?",
|
||||
),
|
||||
"done": MessageLookupByLibrary.simpleMessage("Завершен"),
|
||||
"down_pressure": MessageLookupByLibrary.simpleMessage(
|
||||
"Нижние показатели давления:",
|
||||
),
|
||||
@@ -192,6 +220,9 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"from_a_to_z": MessageLookupByLibrary.simpleMessage("Название: А-Я"),
|
||||
"from_z_to_a": MessageLookupByLibrary.simpleMessage("Название: Я-А"),
|
||||
"gallery": MessageLookupByLibrary.simpleMessage("Галерея"),
|
||||
"goToMyDiets": MessageLookupByLibrary.simpleMessage(
|
||||
"Перейти к моим диетам",
|
||||
),
|
||||
"gr": MessageLookupByLibrary.simpleMessage("гр"),
|
||||
"grams": MessageLookupByLibrary.simpleMessage("гр"),
|
||||
"have_promo_code": MessageLookupByLibrary.simpleMessage(
|
||||
@@ -262,6 +293,10 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
),
|
||||
"no": MessageLookupByLibrary.simpleMessage("Нет"),
|
||||
"no_account": MessageLookupByLibrary.simpleMessage("У меня нет аккаунта"),
|
||||
"no_active_personal_diet_consultations":
|
||||
MessageLookupByLibrary.simpleMessage(
|
||||
"Нет активных консультаций с персональной диетой",
|
||||
),
|
||||
"no_installed_banks": MessageLookupByLibrary.simpleMessage(
|
||||
"Нет установленных банков",
|
||||
),
|
||||
@@ -284,6 +319,9 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
),
|
||||
"option_title": MessageLookupByLibrary.simpleMessage("Заголовок опции"),
|
||||
"order": MessageLookupByLibrary.simpleMessage("Порядок"),
|
||||
"orderCanceled": MessageLookupByLibrary.simpleMessage("Заказ отменен"),
|
||||
"order_in_progress": MessageLookupByLibrary.simpleMessage("Заказ в работе"),
|
||||
"order_paid": MessageLookupByLibrary.simpleMessage("Заказ оплачен"),
|
||||
"password": MessageLookupByLibrary.simpleMessage("Пароль"),
|
||||
"password_confirmation": MessageLookupByLibrary.simpleMessage(
|
||||
"Подтвердите пароль",
|
||||
@@ -297,8 +335,29 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"password_short": MessageLookupByLibrary.simpleMessage(
|
||||
"В пароле должно быть минимум 6 символов",
|
||||
),
|
||||
"pay_by_qr_code": MessageLookupByLibrary.simpleMessage(
|
||||
"Оплатить по QR-коду",
|
||||
),
|
||||
"payment_failed": MessageLookupByLibrary.simpleMessage("Оплата не прошла"),
|
||||
"pcs": MessageLookupByLibrary.simpleMessage("шт"),
|
||||
"personal": MessageLookupByLibrary.simpleMessage("Персональные"),
|
||||
"personal_diet_defined_to_author": m1,
|
||||
"personal_diet_defined_to_author_named": m2,
|
||||
"personal_diet_duration_hint": m3,
|
||||
"personal_diet_duration_mismatch": m4,
|
||||
"personal_diet_not_proposed": MessageLookupByLibrary.simpleMessage(
|
||||
"Диета не предложена",
|
||||
),
|
||||
"personal_diet_proposed": MessageLookupByLibrary.simpleMessage(
|
||||
"Диета предложена",
|
||||
),
|
||||
"personal_diet_proposed_named": m5,
|
||||
"personal_diet_replaces_tomorrow": MessageLookupByLibrary.simpleMessage(
|
||||
"Замена действует со следующего дня",
|
||||
),
|
||||
"personal_diet_set": MessageLookupByLibrary.simpleMessage(
|
||||
"Персональная диета установлена",
|
||||
),
|
||||
"personal_diet_state": MessageLookupByLibrary.simpleMessage("Персональная"),
|
||||
"photo": MessageLookupByLibrary.simpleMessage("Фото"),
|
||||
"place_of_living": MessageLookupByLibrary.simpleMessage("Место проживания"),
|
||||
@@ -308,6 +367,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"Большое подробное, привлекательное описание плана",
|
||||
),
|
||||
"plan_duration": MessageLookupByLibrary.simpleMessage("Срок плана"),
|
||||
"plan_duration_label": m8,
|
||||
"plan_label_desc": MessageLookupByLibrary.simpleMessage(
|
||||
"План для поддержания формы",
|
||||
),
|
||||
@@ -335,7 +395,7 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"Промокод применён!",
|
||||
),
|
||||
"promo_code": MessageLookupByLibrary.simpleMessage("Промокод"),
|
||||
"promo_discount_hint": m3,
|
||||
"promo_discount_hint": m9,
|
||||
"promo_invalid": MessageLookupByLibrary.simpleMessage(
|
||||
"Промокод не найден или истёк",
|
||||
),
|
||||
@@ -354,6 +414,34 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"sbp_payment_error": MessageLookupByLibrary.simpleMessage(
|
||||
"Не удалось начать оплату. Попробуйте позже",
|
||||
),
|
||||
"sbp_qr_amount_label": MessageLookupByLibrary.simpleMessage(
|
||||
"Сумма к оплате",
|
||||
),
|
||||
"sbp_qr_open_test_payment": MessageLookupByLibrary.simpleMessage(
|
||||
"Открыть тестовую оплату",
|
||||
),
|
||||
"sbp_qr_paid_description": MessageLookupByLibrary.simpleMessage(
|
||||
"Консультация оплачена. Можно вернуться в чат.",
|
||||
),
|
||||
"sbp_qr_paid_title": MessageLookupByLibrary.simpleMessage(
|
||||
"Оплата прошла успешно!",
|
||||
),
|
||||
"sbp_qr_step1": MessageLookupByLibrary.simpleMessage(
|
||||
"Откройте приложение банка на телефоне",
|
||||
),
|
||||
"sbp_qr_step2": MessageLookupByLibrary.simpleMessage(
|
||||
"Выберите «Оплата по QR-коду»",
|
||||
),
|
||||
"sbp_qr_step3": MessageLookupByLibrary.simpleMessage(
|
||||
"Наведите камеру на код",
|
||||
),
|
||||
"sbp_qr_test_hint": MessageLookupByLibrary.simpleMessage(
|
||||
"Симуляция оплаты на тестовом стенде Альфа-Банка",
|
||||
),
|
||||
"sbp_qr_title": MessageLookupByLibrary.simpleMessage("Оплата по QR-коду"),
|
||||
"sbp_qr_waiting_payment": MessageLookupByLibrary.simpleMessage(
|
||||
"Ожидание оплаты…",
|
||||
),
|
||||
"services": MessageLookupByLibrary.simpleMessage("Оказание услуг"),
|
||||
"settings": MessageLookupByLibrary.simpleMessage("Настройки"),
|
||||
"share": MessageLookupByLibrary.simpleMessage("Поделиться"),
|
||||
@@ -364,7 +452,12 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"План питания для похудения должен быть разработан с учётом индивидуальных особенностей организма, возраста, пола, уровня физической активности и состояния здоровья. Общие принципы: \n● Снижение калорийности; \n● Сбалансированный рацион; \n● Разнообразие продуктов; \n● Питьевой режим; \n● Ограничение вредных продуктов;",
|
||||
),
|
||||
"standard": MessageLookupByLibrary.simpleMessage("Стандарт"),
|
||||
"startDateHasBeenSet": MessageLookupByLibrary.simpleMessage(
|
||||
"Выбрана дата старта",
|
||||
),
|
||||
"startDiet": MessageLookupByLibrary.simpleMessage("Начать диету"),
|
||||
"start_date_label": m10,
|
||||
"suggestDiet": MessageLookupByLibrary.simpleMessage("Предложить диету"),
|
||||
"tell_your_schedule": MessageLookupByLibrary.simpleMessage(
|
||||
"Расскажите в свободной форме о том как просыпаетесь, когда едите, когда ложитесь спать:",
|
||||
),
|
||||
@@ -441,6 +534,45 @@ class MessageLookup extends MessageLookupByLibrary {
|
||||
"video_call_recording_notice": MessageLookupByLibrary.simpleMessage(
|
||||
"Видеозвонок будет записан.\nКонсультация может быть проверена сотрудниками Итвио, на предмет качества оказания услуг.",
|
||||
),
|
||||
"video_call_recordings_card_title": MessageLookupByLibrary.simpleMessage(
|
||||
"Видеоконсультация со специалистом по питанию",
|
||||
),
|
||||
"video_call_recordings_download": MessageLookupByLibrary.simpleMessage(
|
||||
"Скачать",
|
||||
),
|
||||
"video_call_recordings_download_error":
|
||||
MessageLookupByLibrary.simpleMessage(
|
||||
"Не удалось скачать запись. Попробуйте позже.",
|
||||
),
|
||||
"video_call_recordings_empty": MessageLookupByLibrary.simpleMessage(
|
||||
"Пока нет видеоконсультаций",
|
||||
),
|
||||
"video_call_recordings_period_all": MessageLookupByLibrary.simpleMessage(
|
||||
"Всё время",
|
||||
),
|
||||
"video_call_recordings_period_current_month":
|
||||
MessageLookupByLibrary.simpleMessage("Текущий месяц"),
|
||||
"video_call_recordings_period_prev_month":
|
||||
MessageLookupByLibrary.simpleMessage("Прошлый месяц"),
|
||||
"video_call_recordings_period_today": MessageLookupByLibrary.simpleMessage(
|
||||
"Сегодня",
|
||||
),
|
||||
"video_call_recordings_period_week": MessageLookupByLibrary.simpleMessage(
|
||||
"7 дней",
|
||||
),
|
||||
"video_call_recordings_player_error": MessageLookupByLibrary.simpleMessage(
|
||||
"Не удалось воспроизвести запись",
|
||||
),
|
||||
"video_call_recordings_processing": MessageLookupByLibrary.simpleMessage(
|
||||
"Запись обрабатывается…",
|
||||
),
|
||||
"video_call_recordings_retention_tooltip":
|
||||
MessageLookupByLibrary.simpleMessage(
|
||||
"Записи видеоконсультаций хранятся на серверах Итвио в течение 1 года.",
|
||||
),
|
||||
"video_call_recordings_title": MessageLookupByLibrary.simpleMessage(
|
||||
"Мои консультации",
|
||||
),
|
||||
"video_call_role_consultant": MessageLookupByLibrary.simpleMessage(
|
||||
"Консультант Итвио",
|
||||
),
|
||||
|
||||
@@ -2689,6 +2689,116 @@ class S {
|
||||
);
|
||||
}
|
||||
|
||||
/// `Оплатить по QR-коду`
|
||||
String get pay_by_qr_code {
|
||||
return Intl.message(
|
||||
'Оплатить по QR-коду',
|
||||
name: 'pay_by_qr_code',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Оплата по QR-коду`
|
||||
String get sbp_qr_title {
|
||||
return Intl.message(
|
||||
'Оплата по QR-коду',
|
||||
name: 'sbp_qr_title',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Сумма к оплате`
|
||||
String get sbp_qr_amount_label {
|
||||
return Intl.message(
|
||||
'Сумма к оплате',
|
||||
name: 'sbp_qr_amount_label',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Откройте приложение банка на телефоне`
|
||||
String get sbp_qr_step1 {
|
||||
return Intl.message(
|
||||
'Откройте приложение банка на телефоне',
|
||||
name: 'sbp_qr_step1',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Выберите «Оплата по QR-коду»`
|
||||
String get sbp_qr_step2 {
|
||||
return Intl.message(
|
||||
'Выберите «Оплата по QR-коду»',
|
||||
name: 'sbp_qr_step2',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Наведите камеру на код`
|
||||
String get sbp_qr_step3 {
|
||||
return Intl.message(
|
||||
'Наведите камеру на код',
|
||||
name: 'sbp_qr_step3',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Ожидание оплаты…`
|
||||
String get sbp_qr_waiting_payment {
|
||||
return Intl.message(
|
||||
'Ожидание оплаты…',
|
||||
name: 'sbp_qr_waiting_payment',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Оплата прошла успешно!`
|
||||
String get sbp_qr_paid_title {
|
||||
return Intl.message(
|
||||
'Оплата прошла успешно!',
|
||||
name: 'sbp_qr_paid_title',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Консультация оплачена. Можно вернуться в чат.`
|
||||
String get sbp_qr_paid_description {
|
||||
return Intl.message(
|
||||
'Консультация оплачена. Можно вернуться в чат.',
|
||||
name: 'sbp_qr_paid_description',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Открыть тестовую оплату`
|
||||
String get sbp_qr_open_test_payment {
|
||||
return Intl.message(
|
||||
'Открыть тестовую оплату',
|
||||
name: 'sbp_qr_open_test_payment',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Симуляция оплаты на тестовом стенде Альфа-Банка`
|
||||
String get sbp_qr_test_hint {
|
||||
return Intl.message(
|
||||
'Симуляция оплаты на тестовом стенде Альфа-Банка',
|
||||
name: 'sbp_qr_test_hint',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Подробнее о заказе`
|
||||
String get more_about_order {
|
||||
return Intl.message(
|
||||
@@ -4443,6 +4553,279 @@ class S {
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Order in progress`
|
||||
String get order_in_progress {
|
||||
return Intl.message(
|
||||
'Order in progress',
|
||||
name: 'order_in_progress',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Personal diet proposed`
|
||||
String get personal_diet_proposed {
|
||||
return Intl.message(
|
||||
'Personal diet proposed',
|
||||
name: 'personal_diet_proposed',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Diet «{name}» proposed`
|
||||
String personal_diet_proposed_named(String name) {
|
||||
return Intl.message(
|
||||
'Diet «$name» proposed',
|
||||
name: 'personal_diet_proposed_named',
|
||||
desc: '',
|
||||
args: [name],
|
||||
);
|
||||
}
|
||||
|
||||
/// `User`
|
||||
String get default_user_name {
|
||||
return Intl.message('User', name: 'default_user_name', desc: '', args: []);
|
||||
}
|
||||
|
||||
/// `You have proposed a personal diet to {userName}`
|
||||
String personal_diet_defined_to_author(String userName) {
|
||||
return Intl.message(
|
||||
'You have proposed a personal diet to $userName',
|
||||
name: 'personal_diet_defined_to_author',
|
||||
desc: '',
|
||||
args: [userName],
|
||||
);
|
||||
}
|
||||
|
||||
/// `You have proposed a personal diet to {userName}, selected diet: «{dietName}»`
|
||||
String personal_diet_defined_to_author_named(
|
||||
String userName,
|
||||
String dietName,
|
||||
) {
|
||||
return Intl.message(
|
||||
'You have proposed a personal diet to $userName, selected diet: «$dietName»',
|
||||
name: 'personal_diet_defined_to_author_named',
|
||||
desc: '',
|
||||
args: [userName, dietName],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Personal diet not proposed`
|
||||
String get personal_diet_not_proposed {
|
||||
return Intl.message(
|
||||
'Personal diet not proposed',
|
||||
name: 'personal_diet_not_proposed',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Change personal diet`
|
||||
String get change_personal_diet {
|
||||
return Intl.message(
|
||||
'Change personal diet',
|
||||
name: 'change_personal_diet',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `The change takes effect tomorrow`
|
||||
String get personal_diet_replaces_tomorrow {
|
||||
return Intl.message(
|
||||
'The change takes effect tomorrow',
|
||||
name: 'personal_diet_replaces_tomorrow',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Start: {date}`
|
||||
String start_date_label(String date) {
|
||||
return Intl.message(
|
||||
'Start: $date',
|
||||
name: 'start_date_label',
|
||||
desc: '',
|
||||
args: [date],
|
||||
);
|
||||
}
|
||||
|
||||
/// `The diet lasts {duration} {dayWord}. It can only be offered for a plan with the same duration.`
|
||||
String personal_diet_duration_hint(int duration, String dayWord) {
|
||||
return Intl.message(
|
||||
'The diet lasts $duration $dayWord. It can only be offered for a plan with the same duration.',
|
||||
name: 'personal_diet_duration_hint',
|
||||
desc: '',
|
||||
args: [duration, dayWord],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Not suitable: diet lasts {dietDuration} {dietDayWord}, plan lasts {planDuration} {planDayWord}.`
|
||||
String personal_diet_duration_mismatch(
|
||||
int dietDuration,
|
||||
String dietDayWord,
|
||||
int planDuration,
|
||||
String planDayWord,
|
||||
) {
|
||||
return Intl.message(
|
||||
'Not suitable: diet lasts $dietDuration $dietDayWord, plan lasts $planDuration $planDayWord.',
|
||||
name: 'personal_diet_duration_mismatch',
|
||||
desc: '',
|
||||
args: [dietDuration, dietDayWord, planDuration, planDayWord],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Plan for {duration} {dayWord}`
|
||||
String plan_duration_label(int duration, String dayWord) {
|
||||
return Intl.message(
|
||||
'Plan for $duration $dayWord',
|
||||
name: 'plan_duration_label',
|
||||
desc: '',
|
||||
args: [duration, dayWord],
|
||||
);
|
||||
}
|
||||
|
||||
/// `No active consultations with a personal diet`
|
||||
String get no_active_personal_diet_consultations {
|
||||
return Intl.message(
|
||||
'No active consultations with a personal diet',
|
||||
name: 'no_active_personal_diet_consultations',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `My consultations`
|
||||
String get video_call_recordings_title {
|
||||
return Intl.message(
|
||||
'My consultations',
|
||||
name: 'video_call_recordings_title',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Video consultation recordings are stored on Eatvio servers for 1 year.`
|
||||
String get video_call_recordings_retention_tooltip {
|
||||
return Intl.message(
|
||||
'Video consultation recordings are stored on Eatvio servers for 1 year.',
|
||||
name: 'video_call_recordings_retention_tooltip',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `No video consultations yet`
|
||||
String get video_call_recordings_empty {
|
||||
return Intl.message(
|
||||
'No video consultations yet',
|
||||
name: 'video_call_recordings_empty',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Recording is being processed…`
|
||||
String get video_call_recordings_processing {
|
||||
return Intl.message(
|
||||
'Recording is being processed…',
|
||||
name: 'video_call_recordings_processing',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Download`
|
||||
String get video_call_recordings_download {
|
||||
return Intl.message(
|
||||
'Download',
|
||||
name: 'video_call_recordings_download',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Could not download the recording. Please try again later.`
|
||||
String get video_call_recordings_download_error {
|
||||
return Intl.message(
|
||||
'Could not download the recording. Please try again later.',
|
||||
name: 'video_call_recordings_download_error',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Could not play the recording`
|
||||
String get video_call_recordings_player_error {
|
||||
return Intl.message(
|
||||
'Could not play the recording',
|
||||
name: 'video_call_recordings_player_error',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Video consultation with a nutrition specialist`
|
||||
String get video_call_recordings_card_title {
|
||||
return Intl.message(
|
||||
'Video consultation with a nutrition specialist',
|
||||
name: 'video_call_recordings_card_title',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Today`
|
||||
String get video_call_recordings_period_today {
|
||||
return Intl.message(
|
||||
'Today',
|
||||
name: 'video_call_recordings_period_today',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `7 days`
|
||||
String get video_call_recordings_period_week {
|
||||
return Intl.message(
|
||||
'7 days',
|
||||
name: 'video_call_recordings_period_week',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Current month`
|
||||
String get video_call_recordings_period_current_month {
|
||||
return Intl.message(
|
||||
'Current month',
|
||||
name: 'video_call_recordings_period_current_month',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `Previous month`
|
||||
String get video_call_recordings_period_prev_month {
|
||||
return Intl.message(
|
||||
'Previous month',
|
||||
name: 'video_call_recordings_period_prev_month',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
|
||||
/// `All time`
|
||||
String get video_call_recordings_period_all {
|
||||
return Intl.message(
|
||||
'All time',
|
||||
name: 'video_call_recordings_period_all',
|
||||
desc: '',
|
||||
args: [],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AppLocalizationDelegate extends LocalizationsDelegate<S> {
|
||||
|
||||
@@ -330,6 +330,17 @@
|
||||
"choose_bank_for_payment": "Выберите банк",
|
||||
"no_installed_banks": "Нет установленных банков",
|
||||
"sbp_payment_error": "Не удалось начать оплату. Попробуйте позже",
|
||||
"pay_by_qr_code": "Оплатить по QR-коду",
|
||||
"sbp_qr_title": "Оплата по QR-коду",
|
||||
"sbp_qr_amount_label": "Сумма к оплате",
|
||||
"sbp_qr_step1": "Откройте приложение банка на телефоне",
|
||||
"sbp_qr_step2": "Выберите «Оплата по QR-коду»",
|
||||
"sbp_qr_step3": "Наведите камеру на код",
|
||||
"sbp_qr_waiting_payment": "Ожидание оплаты…",
|
||||
"sbp_qr_paid_title": "Оплата прошла успешно!",
|
||||
"sbp_qr_paid_description": "Консультация оплачена. Можно вернуться в чат.",
|
||||
"sbp_qr_open_test_payment": "Открыть тестовую оплату",
|
||||
"sbp_qr_test_hint": "Симуляция оплаты на тестовом стенде Альфа-Банка",
|
||||
"more_about_order": "Подробнее о заказе",
|
||||
"cancel_order": "Отменить заказ",
|
||||
"refuse_order":"Отказаться от заказа",
|
||||
@@ -526,6 +537,74 @@
|
||||
"video_call_close": "Close",
|
||||
"video_call_notification_in_progress": "Call in progress",
|
||||
"video_call_notification_return": "Return to call",
|
||||
"video_call_notification_end": "End call"
|
||||
"video_call_notification_end": "End call",
|
||||
"order_in_progress": "Order in progress",
|
||||
"personal_diet_proposed": "Personal diet proposed",
|
||||
"personal_diet_proposed_named": "Diet «{name}» proposed",
|
||||
"@personal_diet_proposed_named": {
|
||||
"placeholders": {
|
||||
"name": {"type": "String"}
|
||||
}
|
||||
},
|
||||
"default_user_name": "User",
|
||||
"personal_diet_defined_to_author": "You have proposed a personal diet to {userName}",
|
||||
"@personal_diet_defined_to_author": {
|
||||
"placeholders": {
|
||||
"userName": {"type": "String"}
|
||||
}
|
||||
},
|
||||
"personal_diet_defined_to_author_named": "You have proposed a personal diet to {userName}, selected diet: «{dietName}»",
|
||||
"@personal_diet_defined_to_author_named": {
|
||||
"placeholders": {
|
||||
"userName": {"type": "String"},
|
||||
"dietName": {"type": "String"}
|
||||
}
|
||||
},
|
||||
"personal_diet_not_proposed": "Personal diet not proposed",
|
||||
"change_personal_diet": "Change personal diet",
|
||||
"personal_diet_replaces_tomorrow": "The change takes effect tomorrow",
|
||||
"start_date_label": "Start: {date}",
|
||||
"@start_date_label": {
|
||||
"placeholders": {
|
||||
"date": {"type": "String"}
|
||||
}
|
||||
},
|
||||
"personal_diet_duration_hint": "The diet lasts {duration} {dayWord}. It can only be offered for a plan with the same duration.",
|
||||
"@personal_diet_duration_hint": {
|
||||
"placeholders": {
|
||||
"duration": {"type": "int"},
|
||||
"dayWord": {"type": "String"}
|
||||
}
|
||||
},
|
||||
"personal_diet_duration_mismatch": "Not suitable: diet lasts {dietDuration} {dietDayWord}, plan lasts {planDuration} {planDayWord}.",
|
||||
"@personal_diet_duration_mismatch": {
|
||||
"placeholders": {
|
||||
"dietDuration": {"type": "int"},
|
||||
"dietDayWord": {"type": "String"},
|
||||
"planDuration": {"type": "int"},
|
||||
"planDayWord": {"type": "String"}
|
||||
}
|
||||
},
|
||||
"plan_duration_label": "Plan for {duration} {dayWord}",
|
||||
"@plan_duration_label": {
|
||||
"placeholders": {
|
||||
"duration": {"type": "int"},
|
||||
"dayWord": {"type": "String"}
|
||||
}
|
||||
},
|
||||
"no_active_personal_diet_consultations": "No active consultations with a personal diet",
|
||||
"video_call_recordings_title": "My consultations",
|
||||
"video_call_recordings_retention_tooltip": "Video consultation recordings are stored on Eatvio servers for 1 year.",
|
||||
"video_call_recordings_empty": "No video consultations yet",
|
||||
"video_call_recordings_processing": "Recording is being processed…",
|
||||
"video_call_recordings_download": "Download",
|
||||
"video_call_recordings_download_error": "Could not download the recording. Please try again later.",
|
||||
"video_call_recordings_player_error": "Could not play the recording",
|
||||
"video_call_recordings_card_title": "Video consultation with a nutrition specialist",
|
||||
"video_call_recordings_period_today": "Today",
|
||||
"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"
|
||||
}
|
||||
|
||||
|
||||
@@ -239,6 +239,17 @@
|
||||
"choose_bank_for_payment": "Выберите банк",
|
||||
"no_installed_banks": "Нет установленных банков",
|
||||
"sbp_payment_error": "Не удалось начать оплату. Попробуйте позже",
|
||||
"pay_by_qr_code": "Оплатить по QR-коду",
|
||||
"sbp_qr_title": "Оплата по QR-коду",
|
||||
"sbp_qr_amount_label": "Сумма к оплате",
|
||||
"sbp_qr_step1": "Откройте приложение банка на телефоне",
|
||||
"sbp_qr_step2": "Выберите «Оплата по QR-коду»",
|
||||
"sbp_qr_step3": "Наведите камеру на код",
|
||||
"sbp_qr_waiting_payment": "Ожидание оплаты…",
|
||||
"sbp_qr_paid_title": "Оплата прошла успешно!",
|
||||
"sbp_qr_paid_description": "Консультация оплачена. Можно вернуться в чат.",
|
||||
"sbp_qr_open_test_payment": "Открыть тестовую оплату",
|
||||
"sbp_qr_test_hint": "Симуляция оплаты на тестовом стенде Альфа-Банка",
|
||||
"yes": "Да",
|
||||
"apply": "Применить",
|
||||
"have_promo_code": "У вас есть промокод?",
|
||||
@@ -271,5 +282,83 @@
|
||||
"video_call_notification_in_progress": "Звонок идёт",
|
||||
"video_call_notification_return": "Вернуться к звонку",
|
||||
"video_call_notification_end": "Завершить звонок",
|
||||
"blog_post_image_min_size_error": "Минимальный размер изображения — 500×500 px"
|
||||
"blog_post_image_min_size_error": "Минимальный размер изображения — 500×500 px",
|
||||
"startDateHasBeenSet": "Выбрана дата старта",
|
||||
"order_paid": "Заказ оплачен",
|
||||
"done": "Завершен",
|
||||
"orderCanceled": "Заказ отменен",
|
||||
"payment_failed": "Оплата не прошла",
|
||||
"personal_diet_set": "Персональная диета установлена",
|
||||
"suggestDiet": "Предложить диету",
|
||||
"changeDiet": "Заменить диету",
|
||||
"goToMyDiets": "Перейти к моим диетам",
|
||||
"choose_plan_start_date_with_personal_diet": "Выберите дату старта плана питания с учетом составления персональной диеты",
|
||||
"order_in_progress": "Заказ в работе",
|
||||
"personal_diet_proposed": "Диета предложена",
|
||||
"personal_diet_proposed_named": "Диета «{name}» предложена",
|
||||
"@personal_diet_proposed_named": {
|
||||
"placeholders": {
|
||||
"name": {"type": "String"}
|
||||
}
|
||||
},
|
||||
"default_user_name": "Пользователь",
|
||||
"personal_diet_defined_to_author": "Вы предложили персональную диету пользователю {userName}",
|
||||
"@personal_diet_defined_to_author": {
|
||||
"placeholders": {
|
||||
"userName": {"type": "String"}
|
||||
}
|
||||
},
|
||||
"personal_diet_defined_to_author_named": "Вы предложили персональную диету пользователю {userName}, выбранная диета: «{dietName}»",
|
||||
"@personal_diet_defined_to_author_named": {
|
||||
"placeholders": {
|
||||
"userName": {"type": "String"},
|
||||
"dietName": {"type": "String"}
|
||||
}
|
||||
},
|
||||
"personal_diet_not_proposed": "Диета не предложена",
|
||||
"change_personal_diet": "Заменить диету",
|
||||
"personal_diet_replaces_tomorrow": "Замена действует со следующего дня",
|
||||
"start_date_label": "Старт: {date}",
|
||||
"@start_date_label": {
|
||||
"placeholders": {
|
||||
"date": {"type": "String"}
|
||||
}
|
||||
},
|
||||
"personal_diet_duration_hint": "Диета рассчитана на {duration} {dayWord}. Предложить её можно только для плана с такой же длительностью.",
|
||||
"@personal_diet_duration_hint": {
|
||||
"placeholders": {
|
||||
"duration": {"type": "int"},
|
||||
"dayWord": {"type": "String"}
|
||||
}
|
||||
},
|
||||
"personal_diet_duration_mismatch": "Не подходит: диета на {dietDuration} {dietDayWord}, план на {planDuration} {planDayWord}.",
|
||||
"@personal_diet_duration_mismatch": {
|
||||
"placeholders": {
|
||||
"dietDuration": {"type": "int"},
|
||||
"dietDayWord": {"type": "String"},
|
||||
"planDuration": {"type": "int"},
|
||||
"planDayWord": {"type": "String"}
|
||||
}
|
||||
},
|
||||
"plan_duration_label": "План на {duration} {dayWord}",
|
||||
"@plan_duration_label": {
|
||||
"placeholders": {
|
||||
"duration": {"type": "int"},
|
||||
"dayWord": {"type": "String"}
|
||||
}
|
||||
},
|
||||
"no_active_personal_diet_consultations": "Нет активных консультаций с персональной диетой",
|
||||
"video_call_recordings_title": "Мои консультации",
|
||||
"video_call_recordings_retention_tooltip": "Записи видеоконсультаций хранятся на серверах Итвио в течение 1 года.",
|
||||
"video_call_recordings_empty": "Пока нет видеоконсультаций",
|
||||
"video_call_recordings_processing": "Запись обрабатывается…",
|
||||
"video_call_recordings_download": "Скачать",
|
||||
"video_call_recordings_download_error": "Не удалось скачать запись. Попробуйте позже.",
|
||||
"video_call_recordings_player_error": "Не удалось воспроизвести запись",
|
||||
"video_call_recordings_card_title": "Видеоконсультация со специалистом по питанию",
|
||||
"video_call_recordings_period_today": "Сегодня",
|
||||
"video_call_recordings_period_week": "7 дней",
|
||||
"video_call_recordings_period_current_month": "Текущий месяц",
|
||||
"video_call_recordings_period_prev_month": "Прошлый месяц",
|
||||
"video_call_recordings_period_all": "Всё время"
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
name: eatvio_app
|
||||
description: A new Flutter project.
|
||||
version: 1.3.69+158
|
||||
publish_to: 'none'
|
||||
version: 1.3.71+160
|
||||
publish_to: "none"
|
||||
|
||||
environment:
|
||||
sdk: ^3.10.4
|
||||
@@ -86,12 +86,14 @@ dependencies:
|
||||
intl_utils: ^2.8.13
|
||||
sentry_dio: ^9.10.0
|
||||
livekit_client: ^2.6.1
|
||||
video_player: ^2.10.0
|
||||
audio_session: ^0.1.25
|
||||
flutter_foreground_task: ^9.2.1
|
||||
flutter_callkit_incoming: ^3.1.1
|
||||
floating: ^6.0.0
|
||||
wakelock_plus: ^1.5.2
|
||||
sbp: 0.1.0
|
||||
qr_flutter: ^4.1.0
|
||||
|
||||
# html 0.15.7 removed top-level query_selector.matches used by flutter_html 3.0.0.
|
||||
dependency_overrides:
|
||||
|
||||
118
test/core/interceptors/token_interceptor_session_test.dart
Normal file
118
test/core/interceptors/token_interceptor_session_test.dart
Normal file
@@ -0,0 +1,118 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/interceptors/token_interceptor.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../fixtures/doubles/session_doubles.dart';
|
||||
|
||||
class _RecordingErrorInterceptorHandler extends ErrorInterceptorHandler {
|
||||
int nextCalls = 0;
|
||||
DioException? nextError;
|
||||
|
||||
@override
|
||||
void next(DioException error) {
|
||||
nextCalls++;
|
||||
nextError = error;
|
||||
}
|
||||
|
||||
@override
|
||||
void resolve(Response<dynamic> response) {
|
||||
throw UnimplementedError('resolve should not be called');
|
||||
}
|
||||
|
||||
@override
|
||||
void reject(
|
||||
DioException error, [
|
||||
bool callFollowingErrorInterceptor = false,
|
||||
]) {
|
||||
throw UnimplementedError('reject should not be called');
|
||||
}
|
||||
}
|
||||
|
||||
DioException _unauthorized(RequestOptions options) {
|
||||
return DioException(
|
||||
requestOptions: options,
|
||||
response: Response<dynamic>(requestOptions: options, statusCode: 401),
|
||||
type: DioExceptionType.badResponse,
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late FakeSessionLifecycleService sessionLifecycleService;
|
||||
late TokenInterceptor interceptor;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
TokenStorage.clearCache();
|
||||
await sl.reset();
|
||||
|
||||
sessionLifecycleService = FakeSessionLifecycleService();
|
||||
sl.registerSingleton<SessionLifecycleService>(sessionLifecycleService);
|
||||
interceptor = TokenInterceptor();
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await sl.reset();
|
||||
TokenStorage.clearCache();
|
||||
});
|
||||
|
||||
group('TokenInterceptor.onError 401', () {
|
||||
test('request without Authorization does not end the session', () async {
|
||||
await TokenStorage.saveTokenInStorage('current-token');
|
||||
|
||||
final options = RequestOptions(path: '/api/profile/index');
|
||||
final error = _unauthorized(options);
|
||||
final handler = _RecordingErrorInterceptorHandler();
|
||||
|
||||
await interceptor.onError(error, handler);
|
||||
|
||||
expect(handler.nextCalls, 1);
|
||||
expect(handler.nextError, same(error));
|
||||
expect(sessionLifecycleService.endSessionCalls, 0);
|
||||
});
|
||||
|
||||
test('stale request token does not end the new session', () async {
|
||||
await TokenStorage.saveTokenInStorage('new-token');
|
||||
|
||||
final options = RequestOptions(path: '/api/profile/index');
|
||||
options.headers['Authorization'] = 'Bearer old-token';
|
||||
options.extra['authToken'] = 'old-token';
|
||||
|
||||
final error = _unauthorized(options);
|
||||
final handler = _RecordingErrorInterceptorHandler();
|
||||
|
||||
await interceptor.onError(error, handler);
|
||||
|
||||
expect(handler.nextCalls, 1);
|
||||
expect(sessionLifecycleService.endSessionCalls, 0);
|
||||
});
|
||||
|
||||
test(
|
||||
'current request token ends the session once as unauthorized',
|
||||
() async {
|
||||
await TokenStorage.saveTokenInStorage('current-token');
|
||||
|
||||
final options = RequestOptions(path: '/api/profile/index');
|
||||
options.headers['Authorization'] = 'Bearer current-token';
|
||||
options.extra['authToken'] = 'current-token';
|
||||
|
||||
final error = _unauthorized(options);
|
||||
final handler = _RecordingErrorInterceptorHandler();
|
||||
|
||||
await interceptor.onError(error, handler);
|
||||
|
||||
expect(handler.nextCalls, 1);
|
||||
expect(sessionLifecycleService.endSessionCalls, 1);
|
||||
expect(
|
||||
sessionLifecycleService.lastEndReason,
|
||||
SessionEndReason.unauthorized,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,22 +1,24 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/core/interceptors/token_interceptor.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mocktail/mocktail.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../fixtures/doubles/session_doubles.dart';
|
||||
|
||||
class MockRequestOptions extends Mock implements RequestOptions {}
|
||||
|
||||
class MockRequestInterceptorHandler extends Mock implements RequestInterceptorHandler {}
|
||||
class MockRequestInterceptorHandler extends Mock
|
||||
implements RequestInterceptorHandler {}
|
||||
|
||||
class MockErrorInterceptorHandler extends Mock implements ErrorInterceptorHandler {}
|
||||
class MockErrorInterceptorHandler extends Mock
|
||||
implements ErrorInterceptorHandler {}
|
||||
|
||||
class MockResponse extends Mock implements Response {}
|
||||
|
||||
class MockWsManager extends Mock implements WsManager {}
|
||||
|
||||
class MockDioException extends Mock implements DioException {}
|
||||
|
||||
class FakeRequestOptions extends Fake implements RequestOptions {}
|
||||
@@ -32,23 +34,18 @@ void main() {
|
||||
});
|
||||
group('TokenInterceptor', () {
|
||||
late TokenInterceptor interceptor;
|
||||
late FakeSessionLifecycleService fakeSession;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
|
||||
final mockWsManager = MockWsManager();
|
||||
when(() => mockWsManager.clear()).thenAnswer((_) async {});
|
||||
|
||||
await sl.reset(); // Сбрасываем sl перед каждым тестом
|
||||
sl.registerSingleton<WsManager>(mockWsManager);
|
||||
|
||||
TokenStorage.clearCache();
|
||||
|
||||
await sl.reset();
|
||||
fakeSession = FakeSessionLifecycleService();
|
||||
sl.registerSingleton<SessionLifecycleService>(fakeSession);
|
||||
|
||||
interceptor = TokenInterceptor();
|
||||
// Сбрасываем токен перед каждым тестом
|
||||
try {
|
||||
await TokenStorage.removeTokenInStorage();
|
||||
} catch (e) {
|
||||
// Игнорируем ошибки при очистке
|
||||
}
|
||||
await TokenStorage.removeTokenInStorage();
|
||||
});
|
||||
|
||||
group('onRequest', () {
|
||||
@@ -59,6 +56,7 @@ void main() {
|
||||
final headers = <String, dynamic>{};
|
||||
final options = MockRequestOptions();
|
||||
when(() => options.headers).thenReturn(headers);
|
||||
when(() => options.extra).thenReturn(<String, dynamic>{});
|
||||
final handler = MockRequestInterceptorHandler();
|
||||
|
||||
when(() => handler.next(any())).thenReturn(null);
|
||||
@@ -73,6 +71,7 @@ void main() {
|
||||
final headers = <String, dynamic>{};
|
||||
final options = MockRequestOptions();
|
||||
when(() => options.headers).thenReturn(headers);
|
||||
when(() => options.extra).thenReturn(<String, dynamic>{});
|
||||
final handler = MockRequestInterceptorHandler();
|
||||
|
||||
when(() => handler.next(any())).thenReturn(null);
|
||||
@@ -89,6 +88,7 @@ void main() {
|
||||
final headers = <String, dynamic>{};
|
||||
final options = MockRequestOptions();
|
||||
when(() => options.headers).thenReturn(headers);
|
||||
when(() => options.extra).thenReturn(<String, dynamic>{});
|
||||
final handler = MockRequestInterceptorHandler();
|
||||
|
||||
when(() => handler.next(any())).thenReturn(null);
|
||||
@@ -101,11 +101,16 @@ void main() {
|
||||
});
|
||||
|
||||
group('onError', () {
|
||||
test('удаляет токен и перенаправляет на auth при 401', () async {
|
||||
test('завершает сессию при 401 для текущего токена', () async {
|
||||
const token = 'test-token';
|
||||
await TokenStorage.saveTokenInStorage(token);
|
||||
|
||||
final options = MockRequestOptions();
|
||||
when(
|
||||
() => options.headers,
|
||||
).thenReturn({'Authorization': 'Bearer $token'});
|
||||
when(() => options.extra).thenReturn({'authToken': token});
|
||||
|
||||
final response = MockResponse();
|
||||
when(() => response.statusCode).thenReturn(401);
|
||||
|
||||
@@ -116,14 +121,10 @@ void main() {
|
||||
final handler = MockErrorInterceptorHandler();
|
||||
when(() => handler.next(any())).thenReturn(null);
|
||||
|
||||
// Проверяем, что токен был удален
|
||||
final tokenBefore = await TokenStorage.getTokenFromStorage();
|
||||
expect(tokenBefore, token);
|
||||
|
||||
await interceptor.onError(error, handler);
|
||||
|
||||
final tokenAfter = await TokenStorage.getTokenFromStorage();
|
||||
expect(tokenAfter, null);
|
||||
expect(fakeSession.endSessionCalls, 1);
|
||||
expect(fakeSession.lastEndReason, SessionEndReason.unauthorized);
|
||||
verify(() => handler.next(error)).called(1);
|
||||
});
|
||||
|
||||
|
||||
223
test/core/session/session_lifecycle_service_test.dart
Normal file
223
test/core/session/session_lifecycle_service_test.dart
Normal file
@@ -0,0 +1,223 @@
|
||||
import 'package:eatvio_app/core/error_reporting/error_reporter.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/prefs.dart';
|
||||
import 'package:eatvio_app/core/prefs_keys.dart';
|
||||
import 'package:eatvio_app/core/session/session_lifecycle_service.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/core/websockets/ws_manager.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/new_messages_cubit/new_messages_cubit.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/bloc/chats_cubit/chats_cubit.dart';
|
||||
import 'package:eatvio_app/features/feed/presentation/bloc/feed_cubit/feed_cubit.dart';
|
||||
import 'package:eatvio_app/features/notifications/presentation/notifications_cubit/notifications_cubit.dart';
|
||||
import 'package:eatvio_app/features/video_calls/presentation/bloc/video_call_session/video_call_session_cubit.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class _FakeWsManager implements WsManager {
|
||||
int clearCalls = 0;
|
||||
|
||||
@override
|
||||
Future<void> clear() async {
|
||||
clearCalls++;
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) {
|
||||
throw UnimplementedError('WsManager.${invocation.memberName}');
|
||||
}
|
||||
}
|
||||
|
||||
class _FakeErrorReporter implements ErrorReporter {
|
||||
int reportCalls = 0;
|
||||
|
||||
@override
|
||||
Future<void> report(
|
||||
Object error,
|
||||
StackTrace? stackTrace, {
|
||||
String? origin,
|
||||
Map<String, Object?>? extras,
|
||||
}) async {
|
||||
reportCalls++;
|
||||
}
|
||||
}
|
||||
|
||||
class _FakeProfileAvatarCubit implements ProfileAvatarCubit {
|
||||
int resetCalls = 0;
|
||||
|
||||
@override
|
||||
void reset() {
|
||||
resetCalls++;
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) {
|
||||
throw UnimplementedError('ProfileAvatarCubit.${invocation.memberName}');
|
||||
}
|
||||
}
|
||||
|
||||
class _FakeChatsCubit implements ChatsCubit {
|
||||
int resetCalls = 0;
|
||||
|
||||
@override
|
||||
void reset() {
|
||||
resetCalls++;
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) {
|
||||
throw UnimplementedError('ChatsCubit.${invocation.memberName}');
|
||||
}
|
||||
}
|
||||
|
||||
class _FakeNotificationsCubit implements NotificationsCubit {
|
||||
int resetCalls = 0;
|
||||
|
||||
@override
|
||||
void reset() {
|
||||
resetCalls++;
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) {
|
||||
throw UnimplementedError('NotificationsCubit.${invocation.memberName}');
|
||||
}
|
||||
}
|
||||
|
||||
class _FakeNewMessagesCubit implements NewMessagesCubit {
|
||||
int resetCalls = 0;
|
||||
|
||||
@override
|
||||
void reset() {
|
||||
resetCalls++;
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) {
|
||||
throw UnimplementedError('NewMessagesCubit.${invocation.memberName}');
|
||||
}
|
||||
}
|
||||
|
||||
class _FakeFeedCubit implements FeedCubit {
|
||||
int resetCalls = 0;
|
||||
|
||||
@override
|
||||
void reset() {
|
||||
resetCalls++;
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) {
|
||||
throw UnimplementedError('FeedCubit.${invocation.memberName}');
|
||||
}
|
||||
}
|
||||
|
||||
class _FakeVideoCallSessionCubit implements VideoCallSessionCubit {
|
||||
int endCallCalls = 0;
|
||||
|
||||
@override
|
||||
Future<void> endCall() async {
|
||||
endCallCalls++;
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) {
|
||||
throw UnimplementedError('VideoCallSessionCubit.${invocation.memberName}');
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late _FakeWsManager wsManager;
|
||||
late _FakeProfileAvatarCubit profileAvatarCubit;
|
||||
late _FakeChatsCubit chatsCubit;
|
||||
late _FakeNotificationsCubit notificationsCubit;
|
||||
late _FakeNewMessagesCubit newMessagesCubit;
|
||||
late _FakeFeedCubit feedCubit;
|
||||
late _FakeVideoCallSessionCubit videoCallSessionCubit;
|
||||
late SessionLifecycleService service;
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({
|
||||
'token': 'token-a',
|
||||
'socketId': 'socket-a',
|
||||
PrefsKeys.customBaseUrl.name: 'https://old.example',
|
||||
PrefsKeys.isEmailVerificationSkipped.name: true,
|
||||
PrefsKeys.registrationDate.name: '2024-01-01',
|
||||
PrefsKeys.welcomeScreenWasShowed.name: true,
|
||||
});
|
||||
TokenStorage.clearCache();
|
||||
await sl.reset();
|
||||
|
||||
wsManager = _FakeWsManager();
|
||||
profileAvatarCubit = _FakeProfileAvatarCubit();
|
||||
chatsCubit = _FakeChatsCubit();
|
||||
notificationsCubit = _FakeNotificationsCubit();
|
||||
newMessagesCubit = _FakeNewMessagesCubit();
|
||||
feedCubit = _FakeFeedCubit();
|
||||
videoCallSessionCubit = _FakeVideoCallSessionCubit();
|
||||
|
||||
sl.registerSingleton<ProfileAvatarCubit>(profileAvatarCubit);
|
||||
sl.registerSingleton<ChatsCubit>(chatsCubit);
|
||||
sl.registerSingleton<NotificationsCubit>(notificationsCubit);
|
||||
sl.registerSingleton<NewMessagesCubit>(newMessagesCubit);
|
||||
sl.registerSingleton<FeedCubit>(feedCubit);
|
||||
sl.registerSingleton<VideoCallSessionCubit>(videoCallSessionCubit);
|
||||
sl.registerSingleton<Prefs>(Prefs(await SharedPreferences.getInstance()));
|
||||
|
||||
service = SessionLifecycleService(
|
||||
wsManager: wsManager,
|
||||
errorReporter: _FakeErrorReporter(),
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await sl.reset();
|
||||
TokenStorage.clearCache();
|
||||
});
|
||||
|
||||
group('SessionLifecycleService.endSession', () {
|
||||
test(
|
||||
'resets user-scoped state and clears only session-scoped keys',
|
||||
() async {
|
||||
await service.endSession(reason: SessionEndReason.logout);
|
||||
|
||||
expect(wsManager.clearCalls, 1);
|
||||
expect(profileAvatarCubit.resetCalls, 1);
|
||||
expect(chatsCubit.resetCalls, 1);
|
||||
expect(notificationsCubit.resetCalls, 1);
|
||||
expect(newMessagesCubit.resetCalls, 1);
|
||||
expect(feedCubit.resetCalls, 1);
|
||||
expect(videoCallSessionCubit.endCallCalls, 1);
|
||||
|
||||
expect(await TokenStorage.getTokenFromStorage(), isNull);
|
||||
expect(await SocketIdStorage.getSocketIdFromStorage(), isNull);
|
||||
|
||||
final prefs = sl<Prefs>();
|
||||
expect(prefs.getString(PrefsKeys.customBaseUrl), 'https://old.example');
|
||||
expect(prefs.getBool(PrefsKeys.isEmailVerificationSkipped), isNull);
|
||||
expect(prefs.getString(PrefsKeys.registrationDate), isNull);
|
||||
expect(prefs.getBool(PrefsKeys.welcomeScreenWasShowed), isTrue);
|
||||
},
|
||||
);
|
||||
|
||||
test('is idempotent for concurrent calls', () async {
|
||||
final first = service.endSession(reason: SessionEndReason.logout);
|
||||
final second = service.endSession(reason: SessionEndReason.unauthorized);
|
||||
|
||||
await Future.wait([first, second]);
|
||||
|
||||
expect(wsManager.clearCalls, 1);
|
||||
expect(profileAvatarCubit.resetCalls, 1);
|
||||
expect(chatsCubit.resetCalls, 1);
|
||||
expect(notificationsCubit.resetCalls, 1);
|
||||
expect(newMessagesCubit.resetCalls, 1);
|
||||
expect(feedCubit.resetCalls, 1);
|
||||
expect(videoCallSessionCubit.endCallCalls, 1);
|
||||
|
||||
expect(await TokenStorage.getTokenFromStorage(), isNull);
|
||||
expect(await SocketIdStorage.getSocketIdFromStorage(), isNull);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import 'package:mockito/annotations.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../../../../fixtures/doubles/session_doubles.dart';
|
||||
import 'auth_cubit_test.mocks.dart';
|
||||
|
||||
@GenerateNiceMocks([
|
||||
@@ -75,6 +76,7 @@ void main() {
|
||||
profileRepository: mockProfileRepository,
|
||||
firebaseApi: mockFirebaseApi,
|
||||
prefs: mockPrefs,
|
||||
sessionLifecycleService: FakeSessionLifecycleService(),
|
||||
);
|
||||
|
||||
expect(cubit!.state, isA<AuthState>());
|
||||
@@ -86,6 +88,7 @@ void main() {
|
||||
profileRepository: mockProfileRepository,
|
||||
firebaseApi: mockFirebaseApi,
|
||||
prefs: mockPrefs,
|
||||
sessionLifecycleService: FakeSessionLifecycleService(),
|
||||
);
|
||||
|
||||
const email = 'test@example.com';
|
||||
@@ -116,6 +119,7 @@ void main() {
|
||||
profileRepository: mockProfileRepository,
|
||||
firebaseApi: mockFirebaseApi,
|
||||
prefs: mockPrefs,
|
||||
sessionLifecycleService: FakeSessionLifecycleService(),
|
||||
);
|
||||
|
||||
const email = 'test@example.com';
|
||||
@@ -140,6 +144,7 @@ void main() {
|
||||
profileRepository: mockProfileRepository,
|
||||
firebaseApi: mockFirebaseApi,
|
||||
prefs: mockPrefs,
|
||||
sessionLifecycleService: FakeSessionLifecycleService(),
|
||||
);
|
||||
|
||||
when(mockPrefs.getBool(any)).thenReturn(false);
|
||||
@@ -159,6 +164,7 @@ void main() {
|
||||
profileRepository: mockProfileRepository,
|
||||
firebaseApi: mockFirebaseApi,
|
||||
prefs: mockPrefs,
|
||||
sessionLifecycleService: FakeSessionLifecycleService(),
|
||||
);
|
||||
|
||||
when(mockPrefs.getBool(any)).thenReturn(true);
|
||||
@@ -174,6 +180,7 @@ void main() {
|
||||
profileRepository: mockProfileRepository,
|
||||
firebaseApi: mockFirebaseApi,
|
||||
prefs: mockPrefs,
|
||||
sessionLifecycleService: FakeSessionLifecycleService(),
|
||||
);
|
||||
|
||||
when(mockFirebaseApi.registerPushToken())
|
||||
@@ -190,6 +197,7 @@ void main() {
|
||||
profileRepository: mockProfileRepository,
|
||||
firebaseApi: mockFirebaseApi,
|
||||
prefs: mockPrefs,
|
||||
sessionLifecycleService: FakeSessionLifecycleService(),
|
||||
);
|
||||
|
||||
// TokenStorage.haveTokenInStorage() вернет false
|
||||
|
||||
@@ -13,6 +13,7 @@ import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../../../fixtures/doubles/auth_doubles.dart';
|
||||
import '../../../../fixtures/doubles/profile_doubles.dart';
|
||||
import '../../../../fixtures/doubles/session_doubles.dart';
|
||||
import '../../../../fixtures/fixture_reader.dart';
|
||||
import 'auth_cubit_test.mocks.dart';
|
||||
|
||||
@@ -26,6 +27,7 @@ void main() {
|
||||
late FixtureProfileRepository profileRepository;
|
||||
late MockPrefs mockPrefs;
|
||||
late MockFirebaseApi mockFirebaseApi;
|
||||
late FakeSessionLifecycleService fakeSession;
|
||||
late Map<String, dynamic> credentialsFixture;
|
||||
|
||||
late TokenModel tokenFixture;
|
||||
@@ -37,6 +39,7 @@ void main() {
|
||||
profileRepository = FixtureProfileRepository();
|
||||
mockPrefs = MockPrefs();
|
||||
mockFirebaseApi = MockFirebaseApi();
|
||||
fakeSession = FakeSessionLifecycleService();
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
|
||||
// Mock Fluttertoast plugin
|
||||
@@ -59,12 +62,12 @@ void main() {
|
||||
});
|
||||
|
||||
test('начальное состояние - AuthState', () {
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi);
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession);
|
||||
expect(authCubit!.state, const AuthState());
|
||||
});
|
||||
|
||||
test('getTokenByCredentials - успешная авторизация', () async {
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi);
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession);
|
||||
|
||||
final result = await authCubit!.getTokenByCredentials(credentialsFixture['email'] as String, credentialsFixture['password'] as String);
|
||||
|
||||
@@ -77,7 +80,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('getTokenByCredentials - переход в состояние loading', () async {
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi);
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession);
|
||||
authRepository.responseDelay = const Duration(milliseconds: 50);
|
||||
|
||||
final future = authCubit!.getTokenByCredentials(credentialsFixture['email'] as String, credentialsFixture['password'] as String);
|
||||
@@ -88,7 +91,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('getTokenByCredentials - обработка ошибки авторизации', () async {
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi);
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession);
|
||||
authRepository.error = Exception('Неверный адрес электронной почты или пароль');
|
||||
|
||||
final result = await authCubit!.getTokenByCredentials('wrong@example.com', 'wrongpassword');
|
||||
@@ -102,7 +105,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('getTokenByCredentials - обработка различных типов ошибок', () async {
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi);
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession);
|
||||
authRepository.error = const FormatException('Invalid credentials format');
|
||||
|
||||
final result = await authCubit!.getTokenByCredentials('invalid', 'pass');
|
||||
@@ -115,7 +118,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('getTokenByCredentials - проверка вызова с правильными параметрами', () async {
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi);
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession);
|
||||
|
||||
await authCubit!.getTokenByCredentials('user@test.com', 'securePassword123');
|
||||
|
||||
@@ -124,7 +127,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('getTokenByCredentials - множественные вызовы', () async {
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi);
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession);
|
||||
|
||||
await authCubit!.getTokenByCredentials('first@test.com', 'password1');
|
||||
await Future.delayed(const Duration(milliseconds: 100));
|
||||
@@ -138,7 +141,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('registerAnonymousPushToken - регистрирует токен если не был отправлен', () async {
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi);
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession);
|
||||
when(mockPrefs.getBool(PrefsKeys.hasAnonymousTokenBeenSent)).thenReturn(false);
|
||||
when(mockFirebaseApi.registerAnonymousPushToken()).thenAnswer((_) async => {});
|
||||
when(mockPrefs.setBool(PrefsKeys.hasAnonymousTokenBeenSent, true)).thenAnswer((_) async => {});
|
||||
@@ -150,7 +153,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('registerAnonymousPushToken - не регистрирует токен если уже был отправлен', () async {
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi);
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession);
|
||||
when(mockPrefs.getBool(PrefsKeys.hasAnonymousTokenBeenSent)).thenReturn(true);
|
||||
|
||||
await authCubit!.registerAnonymousPushToken();
|
||||
@@ -159,7 +162,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('registerPushToken - регистрирует push токен', () async {
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi);
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession);
|
||||
when(mockFirebaseApi.registerPushToken()).thenAnswer((_) async => {});
|
||||
|
||||
await authCubit!.registerPushToken();
|
||||
@@ -168,7 +171,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('registerAnonymousPushToken - обрабатывает null значение hasAnonymousTokenBeenSent', () async {
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi);
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: fakeSession);
|
||||
when(mockPrefs.getBool(PrefsKeys.hasAnonymousTokenBeenSent)).thenReturn(null);
|
||||
when(mockFirebaseApi.registerAnonymousPushToken()).thenAnswer((_) async => {});
|
||||
when(mockPrefs.setBool(PrefsKeys.hasAnonymousTokenBeenSent, true)).thenAnswer((_) async => {});
|
||||
|
||||
@@ -14,6 +14,7 @@ import 'package:mockito/annotations.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../../../../fixtures/doubles/session_doubles.dart';
|
||||
import '../../../../../fixtures/fixture_reader.dart';
|
||||
import 'oauth_cubit_test.mocks.dart';
|
||||
|
||||
@@ -37,6 +38,7 @@ void main() {
|
||||
late MockAuthRepository mockAuthRepository;
|
||||
late MockPrefs mockPrefs;
|
||||
late _RecordingFirebaseApi firebaseApi;
|
||||
late FakeSessionLifecycleService fakeSession;
|
||||
late TokenModel tokenFixture;
|
||||
late Map<String, dynamic> signInRequestFixture;
|
||||
late Map<String, dynamic> signUpRequestFixture;
|
||||
@@ -55,6 +57,7 @@ void main() {
|
||||
mockAuthRepository = MockAuthRepository();
|
||||
mockPrefs = MockPrefs();
|
||||
firebaseApi = _RecordingFirebaseApi();
|
||||
fakeSession = FakeSessionLifecycleService();
|
||||
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
|
||||
@@ -87,7 +90,7 @@ void main() {
|
||||
test('начальное состояние - OAuthState', () {
|
||||
oauthCubit = OAuthCubit(
|
||||
authRepository: mockAuthRepository,
|
||||
firebaseApi: firebaseApi,
|
||||
firebaseApi: firebaseApi, sessionLifecycleService: fakeSession,
|
||||
prefs: mockPrefs,
|
||||
);
|
||||
expect(oauthCubit!.state, const OAuthState());
|
||||
@@ -96,7 +99,7 @@ void main() {
|
||||
test('signInViaSocialMedia - успешный вход через соцсеть', () async {
|
||||
oauthCubit = OAuthCubit(
|
||||
authRepository: mockAuthRepository,
|
||||
firebaseApi: firebaseApi,
|
||||
firebaseApi: firebaseApi, sessionLifecycleService: fakeSession,
|
||||
prefs: mockPrefs,
|
||||
);
|
||||
|
||||
@@ -129,7 +132,7 @@ void main() {
|
||||
test('signInViaSocialMedia - переход в состояние loading', () async {
|
||||
oauthCubit = OAuthCubit(
|
||||
authRepository: mockAuthRepository,
|
||||
firebaseApi: firebaseApi,
|
||||
firebaseApi: firebaseApi, sessionLifecycleService: fakeSession,
|
||||
prefs: mockPrefs,
|
||||
);
|
||||
|
||||
@@ -160,7 +163,7 @@ void main() {
|
||||
test('signInViaSocialMedia - обработка ошибки', () async {
|
||||
oauthCubit = OAuthCubit(
|
||||
authRepository: mockAuthRepository,
|
||||
firebaseApi: firebaseApi,
|
||||
firebaseApi: firebaseApi, sessionLifecycleService: fakeSession,
|
||||
prefs: mockPrefs,
|
||||
);
|
||||
|
||||
@@ -189,7 +192,7 @@ void main() {
|
||||
test('signUpViaSocialMedia - успешная регистрация через соцсеть', () async {
|
||||
oauthCubit = OAuthCubit(
|
||||
authRepository: mockAuthRepository,
|
||||
firebaseApi: firebaseApi,
|
||||
firebaseApi: firebaseApi, sessionLifecycleService: fakeSession,
|
||||
prefs: mockPrefs,
|
||||
);
|
||||
|
||||
@@ -237,8 +240,7 @@ void main() {
|
||||
final loadedState = oauthCubit!.state as OAuthStateLoaded;
|
||||
expect(loadedState.token, tokenFixture.token);
|
||||
expect(await TokenStorage.getTokenFromStorage(), tokenFixture.token);
|
||||
expect(firebaseApi.registerPushTokenCalls, 1);
|
||||
expect(firebaseApi.hadAuthToken, isTrue);
|
||||
expect(fakeSession.onAuthenticatedCalls, 1);
|
||||
});
|
||||
|
||||
test(
|
||||
@@ -246,7 +248,7 @@ void main() {
|
||||
() async {
|
||||
oauthCubit = OAuthCubit(
|
||||
authRepository: mockAuthRepository,
|
||||
firebaseApi: firebaseApi,
|
||||
firebaseApi: firebaseApi, sessionLifecycleService: fakeSession,
|
||||
prefs: mockPrefs,
|
||||
);
|
||||
|
||||
@@ -289,7 +291,7 @@ void main() {
|
||||
test('signUpViaSocialMedia - обработка ошибки валидации email', () async {
|
||||
oauthCubit = OAuthCubit(
|
||||
authRepository: mockAuthRepository,
|
||||
firebaseApi: firebaseApi,
|
||||
firebaseApi: firebaseApi, sessionLifecycleService: fakeSession,
|
||||
prefs: mockPrefs,
|
||||
);
|
||||
|
||||
@@ -350,7 +352,7 @@ void main() {
|
||||
() async {
|
||||
oauthCubit = OAuthCubit(
|
||||
authRepository: mockAuthRepository,
|
||||
firebaseApi: firebaseApi,
|
||||
firebaseApi: firebaseApi, sessionLifecycleService: fakeSession,
|
||||
prefs: mockPrefs,
|
||||
);
|
||||
|
||||
@@ -379,7 +381,7 @@ void main() {
|
||||
test('requestOAuthVerification - обработка ошибки', () async {
|
||||
oauthCubit = OAuthCubit(
|
||||
authRepository: mockAuthRepository,
|
||||
firebaseApi: firebaseApi,
|
||||
firebaseApi: firebaseApi, sessionLifecycleService: fakeSession,
|
||||
prefs: mockPrefs,
|
||||
);
|
||||
|
||||
@@ -403,7 +405,7 @@ void main() {
|
||||
() async {
|
||||
oauthCubit = OAuthCubit(
|
||||
authRepository: mockAuthRepository,
|
||||
firebaseApi: firebaseApi,
|
||||
firebaseApi: firebaseApi, sessionLifecycleService: fakeSession,
|
||||
prefs: mockPrefs,
|
||||
);
|
||||
|
||||
@@ -458,15 +460,14 @@ void main() {
|
||||
final loadedState = oauthCubit!.state as OAuthStateLoaded;
|
||||
expect(loadedState.token, tokenFixture.token);
|
||||
expect(await TokenStorage.getTokenFromStorage(), tokenFixture.token);
|
||||
expect(firebaseApi.registerPushTokenCalls, 1);
|
||||
expect(firebaseApi.hadAuthToken, isTrue);
|
||||
expect(fakeSession.onAuthenticatedCalls, 1);
|
||||
},
|
||||
);
|
||||
|
||||
test('confirmOAuthVerification - обработка ошибки', () async {
|
||||
oauthCubit = OAuthCubit(
|
||||
authRepository: mockAuthRepository,
|
||||
firebaseApi: firebaseApi,
|
||||
firebaseApi: firebaseApi, sessionLifecycleService: fakeSession,
|
||||
prefs: mockPrefs,
|
||||
);
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../../../fixtures/doubles/auth_doubles.dart';
|
||||
import '../../../../fixtures/doubles/profile_doubles.dart';
|
||||
import '../../../../fixtures/doubles/session_doubles.dart';
|
||||
import '../../../../fixtures/fixture_reader.dart';
|
||||
import 'basic_widget_test.mocks.dart';
|
||||
|
||||
@@ -36,7 +37,7 @@ void main() {
|
||||
mockFirebaseApi = MockFirebaseApi();
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi);
|
||||
authCubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: FakeSessionLifecycleService());
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
@@ -55,7 +56,7 @@ void main() {
|
||||
|
||||
testWidgets('should create AuthCubit successfully', (WidgetTester tester) async {
|
||||
// Arrange & Act
|
||||
final cubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi);
|
||||
final cubit = AuthCubit(authRepository: authRepository, prefs: mockPrefs, profileRepository: profileRepository, firebaseApi: mockFirebaseApi, sessionLifecycleService: FakeSessionLifecycleService());
|
||||
|
||||
// Assert
|
||||
expect(cubit, isA<AuthCubit>());
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_state.dart';
|
||||
import 'package:eatvio_app/features/profile/models/profile_model.dart';
|
||||
import 'package:eatvio_app/features/profile/repositories/profile_repository.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mocktail/mocktail.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class MockProfileRepository extends Mock implements ProfileRepository {}
|
||||
|
||||
const _profileA = ProfileModel(
|
||||
id: 1,
|
||||
slug: 'user-a',
|
||||
name: 'User A',
|
||||
email: 'a@example.com',
|
||||
phoneConfirmationState: 'confirmed',
|
||||
isPublicProfile: true,
|
||||
isBlockedByMe: false,
|
||||
isBlockedByAuthor: false,
|
||||
isBlockedByUser: false,
|
||||
isEntitySubscribedByMe: false,
|
||||
profilePhotoUrl: 'avatars/a.png',
|
||||
roles: [],
|
||||
badges: [],
|
||||
subscriptions: [],
|
||||
subscribers: [],
|
||||
);
|
||||
|
||||
const _profileB = ProfileModel(
|
||||
id: 2,
|
||||
slug: 'user-b',
|
||||
name: 'User B',
|
||||
email: 'b@example.com',
|
||||
phoneConfirmationState: 'confirmed',
|
||||
isPublicProfile: true,
|
||||
isBlockedByMe: false,
|
||||
isBlockedByAuthor: false,
|
||||
isBlockedByUser: false,
|
||||
isEntitySubscribedByMe: false,
|
||||
profilePhotoUrl: 'avatars/b.png',
|
||||
roles: [],
|
||||
badges: [],
|
||||
subscriptions: [],
|
||||
subscribers: [],
|
||||
);
|
||||
|
||||
const _details = ProfileDetailsModel(
|
||||
firstName: 'User',
|
||||
lastName: 'Test',
|
||||
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,
|
||||
);
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
late MockProfileRepository repository;
|
||||
ProfileAvatarCubit? cubit;
|
||||
|
||||
setUp(() async {
|
||||
await sl.reset();
|
||||
SharedPreferences.setMockInitialValues({'token': 'token-a'});
|
||||
TokenStorage.clearCache();
|
||||
repository = MockProfileRepository();
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
if (cubit != null && !cubit!.isClosed) {
|
||||
await cubit!.close();
|
||||
}
|
||||
cubit = null;
|
||||
await sl.reset();
|
||||
TokenStorage.clearCache();
|
||||
});
|
||||
|
||||
void stubSuccessfulProfile(ProfileModel profile) {
|
||||
when(() => repository.getMyProfile()).thenAnswer((_) async => profile);
|
||||
when(
|
||||
() => repository.getMyProfileDetails(),
|
||||
).thenAnswer((_) async => _details);
|
||||
}
|
||||
|
||||
test('reset emits loading and clears the cached profile', () async {
|
||||
stubSuccessfulProfile(_profileA);
|
||||
cubit = ProfileAvatarCubit(profileRepository: repository);
|
||||
|
||||
await cubit!.ensureFreshForCurrentSession();
|
||||
expect(cubit!.state, isA<ProfileAvatarStateLoaded>());
|
||||
|
||||
cubit!.reset();
|
||||
expect(cubit!.state, isA<ProfileAvatarStateLoading>());
|
||||
|
||||
await cubit!.ensureFreshForCurrentSession();
|
||||
|
||||
verify(() => repository.getMyProfile()).called(2);
|
||||
expect(cubit!.state, isA<ProfileAvatarStateLoaded>());
|
||||
});
|
||||
|
||||
test('late getMyProfile completion after reset is ignored', () async {
|
||||
final profileCompleter = Completer<ProfileModel>();
|
||||
when(
|
||||
() => repository.getMyProfile(),
|
||||
).thenAnswer((_) => profileCompleter.future);
|
||||
when(
|
||||
() => repository.getMyProfileDetails(),
|
||||
).thenAnswer((_) async => _details);
|
||||
|
||||
cubit = ProfileAvatarCubit(profileRepository: repository);
|
||||
|
||||
final pendingRequest = cubit!.getMyProfile();
|
||||
await pumpEventQueue();
|
||||
expect(cubit!.state, isA<ProfileAvatarStateLoading>());
|
||||
|
||||
cubit!.reset();
|
||||
profileCompleter.complete(_profileA);
|
||||
await pendingRequest;
|
||||
await pumpEventQueue();
|
||||
|
||||
expect(cubit!.state, isA<ProfileAvatarStateLoading>());
|
||||
verifyNever(() => repository.getMyProfileDetails());
|
||||
});
|
||||
|
||||
test(
|
||||
'ensureFreshForCurrentSession does not refetch for the same token',
|
||||
() async {
|
||||
stubSuccessfulProfile(_profileA);
|
||||
cubit = ProfileAvatarCubit(profileRepository: repository);
|
||||
|
||||
await cubit!.ensureFreshForCurrentSession();
|
||||
await cubit!.ensureFreshForCurrentSession();
|
||||
|
||||
verify(() => repository.getMyProfile()).called(1);
|
||||
expect(cubit!.state, isA<ProfileAvatarStateLoaded>());
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'ensureFreshForCurrentSession refetches after the token changes',
|
||||
() async {
|
||||
final profiles = <ProfileModel>[_profileA, _profileB];
|
||||
when(
|
||||
() => repository.getMyProfile(),
|
||||
).thenAnswer((_) async => profiles.removeAt(0));
|
||||
when(
|
||||
() => repository.getMyProfileDetails(),
|
||||
).thenAnswer((_) async => _details);
|
||||
|
||||
cubit = ProfileAvatarCubit(profileRepository: repository);
|
||||
|
||||
await cubit!.ensureFreshForCurrentSession();
|
||||
final firstState = cubit!.state as ProfileAvatarStateLoaded;
|
||||
expect(firstState.profile.id, _profileA.id);
|
||||
|
||||
await TokenStorage.saveTokenInStorage('token-b');
|
||||
await cubit!.ensureFreshForCurrentSession();
|
||||
|
||||
final secondState = cubit!.state as ProfileAvatarStateLoaded;
|
||||
expect(secondState.profile.id, _profileB.id);
|
||||
expect(secondState.profile.profilePhotoUrl, _profileB.profilePhotoUrl);
|
||||
verify(() => repository.getMyProfile()).called(2);
|
||||
},
|
||||
);
|
||||
|
||||
test('errors emit ProfileAvatarStateError and do not navigate', () async {
|
||||
when(
|
||||
() => repository.getMyProfile(),
|
||||
).thenAnswer((_) async => throw Exception('profile request failed'));
|
||||
|
||||
cubit = ProfileAvatarCubit(profileRepository: repository);
|
||||
|
||||
await cubit!.getMyProfile();
|
||||
|
||||
expect(cubit!.state, isA<ProfileAvatarStateError>());
|
||||
expect(
|
||||
(cubit!.state as ProfileAvatarStateError).errorMessage,
|
||||
contains('profile request failed'),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:eatvio_app/core/token_storage.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_cubit.dart';
|
||||
import 'package:eatvio_app/features/bottom_navigation_bar/presentation/bloc/profile_avatar_cubit/profile_avatar_state.dart';
|
||||
import 'package:eatvio_app/features/profile/models/profile_model.dart';
|
||||
@@ -5,6 +6,7 @@ import 'package:eatvio_app/features/profile/repositories/profile_repository.dart
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mockito/annotations.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'profile_avatar_cubit_test.mocks.dart';
|
||||
|
||||
@@ -16,6 +18,8 @@ void main() {
|
||||
late MockProfileRepository mockRepository;
|
||||
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({'token': 'test-token'});
|
||||
TokenStorage.clearCache();
|
||||
mockRepository = MockProfileRepository();
|
||||
});
|
||||
|
||||
|
||||
@@ -78,6 +78,66 @@ void main() {
|
||||
meta: const ChatMetaModel(lastPage: 1),
|
||||
);
|
||||
|
||||
const planForChosenPlanUpdates = 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,
|
||||
author: Author(
|
||||
authorSlug: 'author',
|
||||
authorName: 'Author Name',
|
||||
authorProfileIcon: 'https://example.com/icon.jpg',
|
||||
authorIsMe: false,
|
||||
),
|
||||
totalLikes: 10,
|
||||
totalViews: 100,
|
||||
totalComments: 5,
|
||||
isFavorite: false,
|
||||
minPriceOfOptions: 1000,
|
||||
maxPriceOfOptions: 2000,
|
||||
wasLikedByMe: false,
|
||||
);
|
||||
|
||||
ChosenPlanModel buildChosenPlan(
|
||||
int id,
|
||||
ChosenPlanStateEnum chosenPlanState,
|
||||
) {
|
||||
return ChosenPlanModel(
|
||||
id: id,
|
||||
optionType: 'options1',
|
||||
startDate: DateTime.now(),
|
||||
chosenPlanState: chosenPlanState,
|
||||
chatId: 'chat-id',
|
||||
consultantId: 1,
|
||||
plan: planForChosenPlanUpdates,
|
||||
);
|
||||
}
|
||||
|
||||
void stubChatChannel({
|
||||
required Stream<ChannelReadEvent> chosenPlanStream,
|
||||
}) {
|
||||
when(mockWsManager.client).thenReturn(MockPusherChannelsClient());
|
||||
when(
|
||||
mockWsManager.directChatStream,
|
||||
).thenAnswer((_) => const Stream<ChannelReadEvent>.empty());
|
||||
when(
|
||||
mockWsManager.clientTypingStream,
|
||||
).thenAnswer((_) => const Stream<ChannelReadEvent>.empty());
|
||||
when(
|
||||
mockWsManager.chosenPlanStateChangedStream,
|
||||
).thenAnswer((_) => chosenPlanStream);
|
||||
}
|
||||
|
||||
setUp(() {
|
||||
mockChatRepository = MockChatRepository();
|
||||
mockCardsRepository = MockCardsRepository();
|
||||
@@ -721,6 +781,160 @@ void main() {
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'chosenPlanStateChangedStream - перезапрашивает план и обновляет state',
|
||||
() async {
|
||||
const uuid = 'room-uuid';
|
||||
const planId = 321;
|
||||
final chosenPlan = buildChosenPlan(
|
||||
planId,
|
||||
ChosenPlanStateEnum.stateStarted,
|
||||
);
|
||||
final updatedPlan = chosenPlan.copyWith(
|
||||
chosenPlanState: ChosenPlanStateEnum.statePaid,
|
||||
);
|
||||
final controller = StreamController<ChannelReadEvent>.broadcast();
|
||||
|
||||
when(
|
||||
mockChatRepository.getChatRoom(uuid),
|
||||
).thenAnswer((_) async => testChatRoom.copyWith(chosenPlanId: planId));
|
||||
when(
|
||||
mockChatRepository.getChatMessages(uuid, 1),
|
||||
).thenAnswer((_) async => testChatMessages);
|
||||
when(
|
||||
mockChatRepository.getChosenPlan(id: planId),
|
||||
).thenAnswer((_) async => chosenPlan);
|
||||
stubChatChannel(chosenPlanStream: controller.stream);
|
||||
|
||||
await chatRoomCubit.initChat(uuid);
|
||||
expect(chatRoomCubit.state, isA<ChatRoomStateLoaded>());
|
||||
|
||||
when(
|
||||
mockChatRepository.getChosenPlan(id: planId),
|
||||
).thenAnswer((_) async => updatedPlan);
|
||||
clearInteractions(mockChatRepository);
|
||||
|
||||
controller.add(_FakeChannelReadEvent());
|
||||
await Future<void>.delayed(const Duration(milliseconds: 350));
|
||||
|
||||
verify(mockChatRepository.getChosenPlan(id: planId)).called(1);
|
||||
final state = chatRoomCubit.state as ChatRoomStateLoaded;
|
||||
expect(
|
||||
state.chatRoom.chosenPlan?.chosenPlanState,
|
||||
ChosenPlanStateEnum.statePaid,
|
||||
);
|
||||
|
||||
await controller.close();
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'chosenPlanStateChangedStream - использует chosenPlan.id если chosenPlanId null',
|
||||
() async {
|
||||
const orderId = 'alfa_c29_k15138_t1712345678_r1234';
|
||||
const conversationUuid = 'fbd81429-8019-499a-80e8-e3933cc4d872';
|
||||
const planId = 654;
|
||||
final chosenPlan = buildChosenPlan(
|
||||
planId,
|
||||
ChosenPlanStateEnum.stateStarted,
|
||||
);
|
||||
final updatedPlan = chosenPlan.copyWith(
|
||||
chosenPlanState: ChosenPlanStateEnum.statePaid,
|
||||
);
|
||||
final controller = StreamController<ChannelReadEvent>.broadcast();
|
||||
|
||||
when(
|
||||
mockChatRepository.resolveOrderIdToConversation(orderId: orderId),
|
||||
).thenAnswer(
|
||||
(_) async => OrderIdToConversationModel(
|
||||
chosenPlanId: planId,
|
||||
conversationUuid: conversationUuid,
|
||||
),
|
||||
);
|
||||
when(
|
||||
mockChatRepository.getChatRoom(conversationUuid),
|
||||
).thenAnswer((_) async => testChatRoom);
|
||||
when(
|
||||
mockChatRepository.getChatMessages(conversationUuid, 1),
|
||||
).thenAnswer((_) async => testChatMessages);
|
||||
when(
|
||||
mockChatRepository.getChosenPlan(id: planId),
|
||||
).thenAnswer((_) async => chosenPlan);
|
||||
stubChatChannel(chosenPlanStream: controller.stream);
|
||||
|
||||
await chatRoomCubit.initChat(null, orderId: orderId);
|
||||
final loaded = chatRoomCubit.state as ChatRoomStateLoaded;
|
||||
expect(loaded.chatRoom.chosenPlanId, isNull);
|
||||
expect(loaded.chatRoom.chosenPlan?.id, planId);
|
||||
|
||||
when(
|
||||
mockChatRepository.getChosenPlan(id: planId),
|
||||
).thenAnswer((_) async => updatedPlan);
|
||||
clearInteractions(mockChatRepository);
|
||||
|
||||
controller.add(_FakeChannelReadEvent());
|
||||
await Future<void>.delayed(const Duration(milliseconds: 350));
|
||||
|
||||
verify(mockChatRepository.getChosenPlan(id: planId)).called(1);
|
||||
final state = chatRoomCubit.state as ChatRoomStateLoaded;
|
||||
expect(
|
||||
state.chatRoom.chosenPlan?.chosenPlanState,
|
||||
ChosenPlanStateEnum.statePaid,
|
||||
);
|
||||
|
||||
await controller.close();
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'chosenPlanStateChangedStream - дебаунсит повторные события',
|
||||
() async {
|
||||
const uuid = 'room-uuid';
|
||||
const planId = 987;
|
||||
final chosenPlan = buildChosenPlan(
|
||||
planId,
|
||||
ChosenPlanStateEnum.stateStarted,
|
||||
);
|
||||
final updatedPlan = chosenPlan.copyWith(
|
||||
chosenPlanState: ChosenPlanStateEnum.statePaid,
|
||||
);
|
||||
final controller = StreamController<ChannelReadEvent>.broadcast();
|
||||
|
||||
when(
|
||||
mockChatRepository.getChatRoom(uuid),
|
||||
).thenAnswer((_) async => testChatRoom.copyWith(chosenPlanId: planId));
|
||||
when(
|
||||
mockChatRepository.getChatMessages(uuid, 1),
|
||||
).thenAnswer((_) async => testChatMessages);
|
||||
when(
|
||||
mockChatRepository.getChosenPlan(id: planId),
|
||||
).thenAnswer((_) async => chosenPlan);
|
||||
stubChatChannel(chosenPlanStream: controller.stream);
|
||||
|
||||
await chatRoomCubit.initChat(uuid);
|
||||
expect(chatRoomCubit.state, isA<ChatRoomStateLoaded>());
|
||||
|
||||
when(
|
||||
mockChatRepository.getChosenPlan(id: planId),
|
||||
).thenAnswer((_) async => updatedPlan);
|
||||
clearInteractions(mockChatRepository);
|
||||
|
||||
controller
|
||||
..add(_FakeChannelReadEvent())
|
||||
..add(_FakeChannelReadEvent());
|
||||
await Future<void>.delayed(const Duration(milliseconds: 350));
|
||||
|
||||
verify(mockChatRepository.getChosenPlan(id: planId)).called(1);
|
||||
final state = chatRoomCubit.state as ChatRoomStateLoaded;
|
||||
expect(
|
||||
state.chatRoom.chosenPlan?.chosenPlanState,
|
||||
ChosenPlanStateEnum.statePaid,
|
||||
);
|
||||
|
||||
await controller.close();
|
||||
},
|
||||
);
|
||||
|
||||
test('choseStartPlanDate - устанавливает дату начала плана', () async {
|
||||
const uuid = 'room-uuid';
|
||||
const planId = 123;
|
||||
@@ -2578,3 +2792,8 @@ void main() {
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
class _FakeChannelReadEvent extends Fake implements ChannelReadEvent {
|
||||
@override
|
||||
dynamic get data => null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
import 'package:eatvio_app/features/chat/presentation/utils/chat_banner_resolver.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/widgets/notification_banner.dart';
|
||||
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
|
||||
import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart';
|
||||
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
ConsultationProgress _progress(
|
||||
ChosenPlanStateEnum state, {
|
||||
bool hasPersonalDiet = false,
|
||||
}) {
|
||||
return mapConsultationProgress(
|
||||
state: state,
|
||||
hasPersonalDiet: hasPersonalDiet,
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('resolveChatBanner — карта консультанта', () {
|
||||
test('in_coordination без карты просит добавить карту', () {
|
||||
final banner = resolveChatBanner(
|
||||
progress: _progress(ChosenPlanStateEnum.stateInCoordination),
|
||||
amIConsultant: true,
|
||||
hasCard: false,
|
||||
state: ChosenPlanStateEnum.stateInCoordination,
|
||||
);
|
||||
|
||||
expect(banner, BannerType.card);
|
||||
});
|
||||
|
||||
test('in_coordination с картой просит выбрать дату', () {
|
||||
final banner = resolveChatBanner(
|
||||
progress: _progress(ChosenPlanStateEnum.stateInCoordination),
|
||||
amIConsultant: true,
|
||||
hasCard: true,
|
||||
state: ChosenPlanStateEnum.stateInCoordination,
|
||||
);
|
||||
|
||||
expect(banner, BannerType.date);
|
||||
});
|
||||
|
||||
test('paid + notProposed + диета просит предложить диету', () {
|
||||
final banner = resolveChatBanner(
|
||||
progress: _progress(
|
||||
ChosenPlanStateEnum.statePaid,
|
||||
hasPersonalDiet: true,
|
||||
),
|
||||
amIConsultant: true,
|
||||
hasCard: true,
|
||||
state: ChosenPlanStateEnum.statePaid,
|
||||
);
|
||||
|
||||
expect(banner, BannerType.setPersonalDiet);
|
||||
});
|
||||
|
||||
test(
|
||||
'personal_diet_setted/started/in_progress + proposed просят сменить диету',
|
||||
() {
|
||||
const states = [
|
||||
ChosenPlanStateEnum.personalDietSet,
|
||||
ChosenPlanStateEnum.stateStarted,
|
||||
ChosenPlanStateEnum.stateInProgress,
|
||||
];
|
||||
|
||||
for (final state in states) {
|
||||
final banner = resolveChatBanner(
|
||||
progress: _progress(state, hasPersonalDiet: true),
|
||||
amIConsultant: true,
|
||||
hasCard: true,
|
||||
state: state,
|
||||
);
|
||||
|
||||
expect(
|
||||
banner,
|
||||
BannerType.changePersonalDiet,
|
||||
reason: 'state=${state.name}',
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test('last_day_finished не просит менять диету (нет баннера)', () {
|
||||
final banner = resolveChatBanner(
|
||||
progress: _progress(
|
||||
ChosenPlanStateEnum.stateLastDayFinished,
|
||||
hasPersonalDiet: true,
|
||||
),
|
||||
amIConsultant: true,
|
||||
hasCard: true,
|
||||
state: ChosenPlanStateEnum.stateLastDayFinished,
|
||||
);
|
||||
|
||||
expect(banner, isNot(BannerType.changePersonalDiet));
|
||||
expect(banner, isNull);
|
||||
});
|
||||
|
||||
test('done не просит менять диету (collectCharge)', () {
|
||||
final banner = resolveChatBanner(
|
||||
progress: _progress(
|
||||
ChosenPlanStateEnum.stateDone,
|
||||
hasPersonalDiet: true,
|
||||
),
|
||||
amIConsultant: true,
|
||||
hasCard: true,
|
||||
state: ChosenPlanStateEnum.stateDone,
|
||||
);
|
||||
|
||||
expect(banner, isNot(BannerType.changePersonalDiet));
|
||||
expect(banner, BannerType.collectCharge);
|
||||
});
|
||||
});
|
||||
|
||||
group('resolveChatBanner — карта клиента', () {
|
||||
test('start_date_has_been_set просит оплатить', () {
|
||||
final banner = resolveChatBanner(
|
||||
progress: _progress(ChosenPlanStateEnum.stateStartDateHasBeenSet),
|
||||
amIConsultant: false,
|
||||
hasCard: true,
|
||||
state: ChosenPlanStateEnum.stateStartDateHasBeenSet,
|
||||
);
|
||||
|
||||
expect(banner, BannerType.payment);
|
||||
});
|
||||
|
||||
test('pending_payment просит оплатить', () {
|
||||
final banner = resolveChatBanner(
|
||||
progress: _progress(ChosenPlanStateEnum.statePendingPayment),
|
||||
amIConsultant: false,
|
||||
hasCard: true,
|
||||
state: ChosenPlanStateEnum.statePendingPayment,
|
||||
);
|
||||
|
||||
expect(banner, BannerType.payment);
|
||||
});
|
||||
|
||||
test('paid + notProposed не показывает diet-баннер клиенту', () {
|
||||
final banner = resolveChatBanner(
|
||||
progress: _progress(
|
||||
ChosenPlanStateEnum.statePaid,
|
||||
hasPersonalDiet: true,
|
||||
),
|
||||
amIConsultant: false,
|
||||
hasCard: true,
|
||||
state: ChosenPlanStateEnum.statePaid,
|
||||
);
|
||||
|
||||
expect(banner, isNull);
|
||||
});
|
||||
|
||||
test(
|
||||
'personal_diet_setted + proposed не показывает diet-баннер клиенту',
|
||||
() {
|
||||
final banner = resolveChatBanner(
|
||||
progress: _progress(
|
||||
ChosenPlanStateEnum.personalDietSet,
|
||||
hasPersonalDiet: true,
|
||||
),
|
||||
amIConsultant: false,
|
||||
hasCard: true,
|
||||
state: ChosenPlanStateEnum.personalDietSet,
|
||||
);
|
||||
|
||||
expect(banner, isNull);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
group('resolveChatBanner — терминальные фазы', () {
|
||||
test('canceled не показывает баннер', () {
|
||||
expect(
|
||||
resolveChatBanner(
|
||||
progress: _progress(ChosenPlanStateEnum.stateCanceledByTheInitiator),
|
||||
amIConsultant: true,
|
||||
hasCard: true,
|
||||
state: ChosenPlanStateEnum.stateCanceledByTheInitiator,
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
expect(
|
||||
resolveChatBanner(
|
||||
progress: _progress(ChosenPlanStateEnum.stateCanceledByTheInitiator),
|
||||
amIConsultant: false,
|
||||
hasCard: true,
|
||||
state: ChosenPlanStateEnum.stateCanceledByTheInitiator,
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
});
|
||||
|
||||
test('payment_failed не показывает баннер', () {
|
||||
expect(
|
||||
resolveChatBanner(
|
||||
progress: _progress(ChosenPlanStateEnum.statePaymentFailed),
|
||||
amIConsultant: true,
|
||||
hasCard: true,
|
||||
state: ChosenPlanStateEnum.statePaymentFailed,
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
expect(
|
||||
resolveChatBanner(
|
||||
progress: _progress(ChosenPlanStateEnum.statePaymentFailed),
|
||||
amIConsultant: false,
|
||||
hasCard: true,
|
||||
state: ChosenPlanStateEnum.statePaymentFailed,
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
});
|
||||
|
||||
test('нет progress или state — нет баннера', () {
|
||||
expect(
|
||||
resolveChatBanner(
|
||||
progress: null,
|
||||
amIConsultant: true,
|
||||
hasCard: true,
|
||||
state: ChosenPlanStateEnum.statePaid,
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
expect(
|
||||
resolveChatBanner(
|
||||
progress: _progress(ChosenPlanStateEnum.statePaid),
|
||||
amIConsultant: true,
|
||||
hasCard: true,
|
||||
state: null,
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/features/chat/presentation/widgets/chat_consultation_header.dart';
|
||||
import 'package:eatvio_app/features/consultations/presentation/widgets/consultation_progress_plank.dart';
|
||||
import 'package:eatvio_app/features/consultations/models/consultation_progress.dart';
|
||||
import 'package:eatvio_app/features/consultations/presentation/widgets/personal_diet_status_chip.dart';
|
||||
import 'package:eatvio_app/features/consultations/utils/consultation_progress_mapper.dart';
|
||||
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||
import 'package:eatvio_app/generated/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
Widget _wrap(Widget child) {
|
||||
return MaterialApp(
|
||||
theme: ThemeHelper().themeData(),
|
||||
localizationsDelegates: const [
|
||||
S.delegate,
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
supportedLocales: const [Locale('ru')],
|
||||
home: Scaffold(body: Center(child: child)),
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('ChatConsultationHeader', () {
|
||||
testWidgets('вызывает onInfoTap по тапу на info', (tester) async {
|
||||
var tapped = 0;
|
||||
final progress = mapConsultationProgress(
|
||||
state: ChosenPlanStateEnum.stateInited,
|
||||
hasPersonalDiet: false,
|
||||
);
|
||||
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
ChatConsultationHeader(
|
||||
progress: progress,
|
||||
showInfoButton: true,
|
||||
onInfoTap: () => tapped++,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.info_outline_rounded));
|
||||
await tester.pump();
|
||||
|
||||
expect(tapped, 1);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'personal_diet_setted показывает плашку и чип вместе с баннером замены',
|
||||
(tester) async {
|
||||
final progress = mapConsultationProgress(
|
||||
state: ChosenPlanStateEnum.personalDietSet,
|
||||
hasPersonalDiet: true,
|
||||
personalDietName: 'Индивидуальный план питания',
|
||||
);
|
||||
expect(progress.showProgressPlank, isTrue);
|
||||
expect(progress.dietStatus, PersonalDietStatus.proposed);
|
||||
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
ChatConsultationHeader(
|
||||
progress: progress,
|
||||
showInfoButton: false,
|
||||
onInfoTap: () {},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final s = S.of(tester.element(find.byType(ChatConsultationHeader)));
|
||||
|
||||
expect(find.text(s.order_in_progress), findsNWidgets(2));
|
||||
expect(find.byType(PersonalDietStatusChip), findsOneWidget);
|
||||
expect(
|
||||
find.text(s.personal_diet_proposed_named('Индивидуальный план питания')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.byType(ConsultationProgressPlank), findsOneWidget);
|
||||
expect(find.byIcon(Icons.check), findsNWidgets(2));
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -526,11 +526,11 @@ void main() {
|
||||
},
|
||||
);
|
||||
|
||||
test('getChatByUserSlug - возвращает 404 при отсутствии чата', () async {
|
||||
test('getChatByUserSlug - возвращает null, если в ответе нет id', () async {
|
||||
const slug = 'user-slug';
|
||||
final response = HttpResponse(
|
||||
{},
|
||||
Response(requestOptions: RequestOptions(path: ''), statusCode: 404),
|
||||
Response(requestOptions: RequestOptions(path: ''), statusCode: 200),
|
||||
);
|
||||
|
||||
when(
|
||||
@@ -539,7 +539,7 @@ void main() {
|
||||
|
||||
final result = await chatRepository.getChatByUserSlug(slug);
|
||||
|
||||
expect(result, '404');
|
||||
expect(result, isNull);
|
||||
verify(mockChatService.getChatByUserSlug(slug: slug)).called(1);
|
||||
});
|
||||
|
||||
|
||||
@@ -16,5 +16,29 @@ void main() {
|
||||
expect(find.byType(BecomeConsultantScreen), findsOneWidget);
|
||||
expect(find.text('Стать консультантом'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('keeps the bottom action above the system navigation area', (tester) async {
|
||||
const bottomInset = 34.0;
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
theme: ThemeHelper().themeData(),
|
||||
builder: (context, child) => MediaQuery(
|
||||
data: MediaQuery.of(context).copyWith(padding: const EdgeInsets.only(bottom: bottomInset)),
|
||||
child: child!,
|
||||
),
|
||||
home: const BecomeConsultantScreen(),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final buttonRect = tester.getRect(
|
||||
find.ancestor(of: find.text('Начать регистрацию'), matching: find.byType(Ink)).first,
|
||||
);
|
||||
final viewHeight = tester.view.physicalSize.height / tester.view.devicePixelRatio;
|
||||
|
||||
expect(buttonRect.bottom, lessThanOrEqualTo(viewHeight - bottomInset));
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -156,6 +156,57 @@ void main() {
|
||||
});
|
||||
|
||||
group('ConsultationModel', () {
|
||||
test('fromJson parses chat_id', () {
|
||||
final json = {
|
||||
'id': 1,
|
||||
'chat_id': 'direct-chat-uuid',
|
||||
'last_state': 'started',
|
||||
'plan_title': 'Test Plan',
|
||||
'user_name': 'User 1',
|
||||
'user_slug': 'user-1',
|
||||
'consultant_payment': 1000.0,
|
||||
'duration': 30,
|
||||
'current_diary_day': 5,
|
||||
'user_profile_photo_url': 'photo.jpg',
|
||||
'consultation_option_price': 2000,
|
||||
'start_date': '2024-01-01T00:00:00Z',
|
||||
'end_date': '2024-01-31T00:00:00Z',
|
||||
'consultant_id': 1,
|
||||
'diaries': [],
|
||||
'personal_diet_id': null,
|
||||
'personal_diet_name': 'Индивидуальный план питания',
|
||||
};
|
||||
|
||||
final model = ConsultationModel.fromJson(json);
|
||||
|
||||
expect(model.chatId, 'direct-chat-uuid');
|
||||
expect(model.personalDietName, 'Индивидуальный план питания');
|
||||
});
|
||||
|
||||
test('fromJson allows missing chat_id', () {
|
||||
final json = {
|
||||
'id': 1,
|
||||
'last_state': 'started',
|
||||
'plan_title': 'Test Plan',
|
||||
'user_name': 'User 1',
|
||||
'user_slug': 'user-1',
|
||||
'consultant_payment': 1000.0,
|
||||
'duration': 30,
|
||||
'current_diary_day': 5,
|
||||
'user_profile_photo_url': 'photo.jpg',
|
||||
'consultation_option_price': 2000,
|
||||
'start_date': '2024-01-01T00:00:00Z',
|
||||
'end_date': '2024-01-31T00:00:00Z',
|
||||
'consultant_id': 1,
|
||||
'diaries': [],
|
||||
'personal_diet_id': null,
|
||||
};
|
||||
|
||||
final model = ConsultationModel.fromJson(json);
|
||||
|
||||
expect(model.chatId, isNull);
|
||||
});
|
||||
|
||||
test('toJson serializes ConsultationModel correctly', () {
|
||||
final model = ConsultationModel(
|
||||
id: 1,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user