forked from eatvio/eatvio_app
Compare commits
32 Commits
android-ci
...
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 | |||
| 2668907f60 | |||
| 56ab9b65f9 | |||
| 85bc2c6d5c | |||
| f58892bdeb | |||
| f14f426381 | |||
| 6a31880a85 | |||
|
|
f6f9764811 |
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';
|
||||
|
||||
@@ -277,7 +278,7 @@ class CubitRegistrations {
|
||||
),
|
||||
);
|
||||
sl.registerFactory<ConsultationsCubit>(
|
||||
() => ConsultationsCubit(consultationsRepository: sl()),
|
||||
() => ConsultationsCubit(consultationsRepository: sl(), chatRepository: sl()),
|
||||
);
|
||||
sl.registerFactory<ConsultantCommentsCubit>(
|
||||
() => ConsultantCommentsCubit(diaryRepository: sl()),
|
||||
@@ -319,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()));
|
||||
|
||||
@@ -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()),
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -14,6 +14,7 @@ import 'package:eatvio_app/features/menu/presentation/bloc/menu_cubit/menu_state
|
||||
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';
|
||||
@@ -49,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(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -277,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',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -145,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);
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
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/models/consultation_model.dart';
|
||||
import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_cubit.dart';
|
||||
import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_state.dart';
|
||||
@@ -8,14 +9,21 @@ import 'package:mocktail/mocktail.dart';
|
||||
|
||||
class MockConsultationsRepository extends Mock implements ConsultationsRepository {}
|
||||
|
||||
class MockChatRepository extends Mock implements ChatRepository {}
|
||||
|
||||
void main() {
|
||||
group('ConsultationsCubit', () {
|
||||
late ConsultationsCubit cubit;
|
||||
late MockConsultationsRepository mockRepository;
|
||||
late MockChatRepository mockChatRepository;
|
||||
|
||||
setUp(() {
|
||||
mockRepository = MockConsultationsRepository();
|
||||
cubit = ConsultationsCubit(consultationsRepository: mockRepository);
|
||||
mockChatRepository = MockChatRepository();
|
||||
cubit = ConsultationsCubit(
|
||||
consultationsRepository: mockRepository,
|
||||
chatRepository: mockChatRepository,
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
@@ -47,5 +55,33 @@ void main() {
|
||||
|
||||
expect(cubit.state.state, BaseState.error);
|
||||
});
|
||||
|
||||
test('getChatIdByUserSlug - возвращает id чата', () async {
|
||||
when(() => mockChatRepository.getChatByUserSlug('john-doe'))
|
||||
.thenAnswer((_) async => 'chat-uuid');
|
||||
|
||||
final chatId = await cubit.getChatIdByUserSlug('john-doe');
|
||||
|
||||
expect(chatId, 'chat-uuid');
|
||||
verify(() => mockChatRepository.getChatByUserSlug('john-doe')).called(1);
|
||||
});
|
||||
|
||||
test('getChatIdByUserSlug - возвращает null при ошибке', () async {
|
||||
when(() => mockChatRepository.getChatByUserSlug(any()))
|
||||
.thenThrow(Exception('Error'));
|
||||
|
||||
final chatId = await cubit.getChatIdByUserSlug('john-doe');
|
||||
|
||||
expect(chatId, isNull);
|
||||
});
|
||||
|
||||
test('getChatIdByUserSlug - возвращает null когда чата нет', () async {
|
||||
when(() => mockChatRepository.getChatByUserSlug(any()))
|
||||
.thenAnswer((_) async => null);
|
||||
|
||||
final chatId = await cubit.getChatIdByUserSlug('john-doe');
|
||||
|
||||
expect(chatId, isNull);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:eatvio_app/core/app_config.dart';
|
||||
import 'package:eatvio_app/core/app_initializer.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/features/consultations/models/consultation_model.dart';
|
||||
import 'package:eatvio_app/features/consultations/presentation/cubit/consultations_cubit.dart';
|
||||
import 'package:eatvio_app/features/consultations/presentation/widgets/consultation_card_widget.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/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:mocktail/mocktail.dart';
|
||||
import 'package:network_image_mock/network_image_mock.dart';
|
||||
|
||||
class MockConsultationsCubit extends Mock implements ConsultationsCubit {}
|
||||
|
||||
void main() {
|
||||
group('ConsultationCardWidget smoke', () {
|
||||
setUpAll(() async {
|
||||
@@ -28,6 +36,20 @@ void main() {
|
||||
AppConfig(buildType: AppBuildType.tests)
|
||||
..setBaseUrl('http://localhost'),
|
||||
);
|
||||
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('PonnamKarthik/fluttertoast'),
|
||||
(MethodCall methodCall) async => null,
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('PonnamKarthik/fluttertoast'),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
final mockConsultation = ConsultationModel(
|
||||
@@ -64,7 +86,8 @@ void main() {
|
||||
personalDietId: null,
|
||||
);
|
||||
|
||||
Widget wrap(Widget child) {
|
||||
Widget wrap(Widget child, {ConsultationsCubit? cubit}) {
|
||||
final consultationsCubit = cubit ?? MockConsultationsCubit();
|
||||
return MaterialApp.router(
|
||||
theme: ThemeHelper().themeData(),
|
||||
localizationsDelegates: const [
|
||||
@@ -77,7 +100,20 @@ void main() {
|
||||
routerConfig: GoRouter(
|
||||
initialLocation: '/',
|
||||
routes: [
|
||||
GoRoute(path: '/', builder: (context, state) => child),
|
||||
GoRoute(
|
||||
path: '/',
|
||||
builder: (context, state) => BlocProvider<ConsultationsCubit>.value(
|
||||
value: consultationsCubit,
|
||||
child: child,
|
||||
),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/chat-screen',
|
||||
name: 'chatScreen',
|
||||
builder: (context, state) => Scaffold(
|
||||
body: Text('chat:${(state.extra as Map)['uuid']}'),
|
||||
),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/profile-screen',
|
||||
name: 'profileScreen',
|
||||
@@ -117,6 +153,29 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('shows personal diet name in status chip', (tester) async {
|
||||
final consultation = mockConsultation.copyWith(
|
||||
personalDietId: 1,
|
||||
personalDietName: 'Индивидуальный план питания',
|
||||
);
|
||||
|
||||
await mockNetworkImagesFor(() async {
|
||||
await tester.pumpWidget(
|
||||
wrap(ConsultationCardWidget(consultationsModel: consultation)),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final s = S.of(tester.element(find.byType(ConsultationCardWidget)));
|
||||
|
||||
expect(
|
||||
find.text(
|
||||
s.personal_diet_proposed_named('Индивидуальный план питания'),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('renders diary days', (tester) async {
|
||||
await mockNetworkImagesFor(() async {
|
||||
await tester.pumpWidget(
|
||||
@@ -163,5 +222,118 @@ void main() {
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('opens chat with consultation user when chat icon tapped', (
|
||||
tester,
|
||||
) async {
|
||||
final cubit = MockConsultationsCubit();
|
||||
when(() => cubit.stream).thenAnswer((_) => const Stream.empty());
|
||||
when(() => cubit.getChatIdByUserSlug('john-doe'))
|
||||
.thenAnswer((_) async => 'chat-uuid');
|
||||
|
||||
await mockNetworkImagesFor(() async {
|
||||
await tester.pumpWidget(
|
||||
wrap(
|
||||
ConsultationCardWidget(consultationsModel: mockConsultation),
|
||||
cubit: cubit,
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.byIcon(Icons.chat_outlined));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('chat:chat-uuid'), findsOneWidget);
|
||||
verify(() => cubit.getChatIdByUserSlug('john-doe')).called(1);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'opens chat directly with chat id without requesting it again',
|
||||
(tester) async {
|
||||
final cubit = MockConsultationsCubit();
|
||||
when(() => cubit.stream).thenAnswer((_) => const Stream.empty());
|
||||
final consultationWithChatId = mockConsultation.copyWith(
|
||||
chatId: 'direct-chat-uuid',
|
||||
);
|
||||
|
||||
await mockNetworkImagesFor(() async {
|
||||
await tester.pumpWidget(
|
||||
wrap(
|
||||
ConsultationCardWidget(
|
||||
consultationsModel: consultationWithChatId,
|
||||
),
|
||||
cubit: cubit,
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.byIcon(Icons.chat_outlined));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('chat:direct-chat-uuid'), findsOneWidget);
|
||||
verifyNever(() => cubit.getChatIdByUserSlug(any()));
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('shows error and stays on card when chat id is null', (
|
||||
tester,
|
||||
) async {
|
||||
final cubit = MockConsultationsCubit();
|
||||
when(() => cubit.stream).thenAnswer((_) => const Stream.empty());
|
||||
when(() => cubit.getChatIdByUserSlug('john-doe'))
|
||||
.thenAnswer((_) async => null);
|
||||
|
||||
await mockNetworkImagesFor(() async {
|
||||
await tester.pumpWidget(
|
||||
wrap(
|
||||
ConsultationCardWidget(consultationsModel: mockConsultation),
|
||||
cubit: cubit,
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.byIcon(Icons.chat_outlined));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.pump(const Duration(seconds: 3));
|
||||
|
||||
expect(find.textContaining('chat:'), findsNothing);
|
||||
expect(
|
||||
find.byType(ConsultationCardWidget),
|
||||
findsOneWidget,
|
||||
);
|
||||
verify(() => cubit.getChatIdByUserSlug('john-doe')).called(1);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('does not request chat id twice while first is pending', (
|
||||
tester,
|
||||
) async {
|
||||
final cubit = MockConsultationsCubit();
|
||||
when(() => cubit.stream).thenAnswer((_) => const Stream.empty());
|
||||
final completer = Completer<String?>();
|
||||
when(() => cubit.getChatIdByUserSlug('john-doe'))
|
||||
.thenAnswer((_) => completer.future);
|
||||
|
||||
await mockNetworkImagesFor(() async {
|
||||
await tester.pumpWidget(
|
||||
wrap(
|
||||
ConsultationCardWidget(consultationsModel: mockConsultation),
|
||||
cubit: cubit,
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.byIcon(Icons.chat_outlined));
|
||||
await tester.tap(find.byIcon(Icons.chat_outlined));
|
||||
|
||||
completer.complete('chat-uuid');
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('chat:chat-uuid'), findsOneWidget);
|
||||
verify(() => cubit.getChatIdByUserSlug('john-doe')).called(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/features/consultations/presentation/widgets/consultation_progress_plank.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('ConsultationProgressPlank', () {
|
||||
testWidgets('не строит шаги при showProgressPlank=false', (tester) async {
|
||||
final progress = mapConsultationProgress(
|
||||
state: ChosenPlanStateEnum.stateConfirmedByConsultant,
|
||||
hasPersonalDiet: true,
|
||||
);
|
||||
expect(progress.showProgressPlank, isFalse);
|
||||
|
||||
await tester.pumpWidget(
|
||||
_wrap(ConsultationProgressPlank(progress: progress)),
|
||||
);
|
||||
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byType(ConsultationProgressPlank),
|
||||
matching: find.byType(SizedBox),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.byIcon(Icons.check), findsNothing);
|
||||
expect(find.byType(Text), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'рисует 4 шага с иконками и подписями при showProgressPlank=true',
|
||||
(tester) async {
|
||||
final progress = mapConsultationProgress(
|
||||
state: ChosenPlanStateEnum.stateDone,
|
||||
hasPersonalDiet: false,
|
||||
);
|
||||
expect(progress.showProgressPlank, isTrue);
|
||||
|
||||
await tester.pumpWidget(
|
||||
_wrap(ConsultationProgressPlank(progress: progress)),
|
||||
);
|
||||
|
||||
final s = S.of(tester.element(find.byType(ConsultationProgressPlank)));
|
||||
|
||||
expect(find.byIcon(Icons.check), findsNWidgets(4));
|
||||
expect(find.text(s.startDateHasBeenSet), findsOneWidget);
|
||||
expect(find.text(s.order_paid), findsOneWidget);
|
||||
expect(find.text(s.order_in_progress), findsOneWidget);
|
||||
expect(find.text(s.done), findsOneWidget);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('подписи шагов центрированы под своими кружками', (
|
||||
tester,
|
||||
) async {
|
||||
final progress = mapConsultationProgress(
|
||||
state: ChosenPlanStateEnum.stateDone,
|
||||
hasPersonalDiet: false,
|
||||
);
|
||||
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
SizedBox(
|
||||
width: 360,
|
||||
child: ConsultationProgressPlank(progress: progress),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
for (var index = 0; index < 4; index++) {
|
||||
final circle = tester.getCenter(
|
||||
find.byKey(ValueKey('consultation_step_circle_$index')),
|
||||
);
|
||||
final label = tester.getCenter(
|
||||
find.byKey(ValueKey('consultation_step_label_$index')),
|
||||
);
|
||||
expect(label.dx, closeTo(circle.dx, 0.5));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import 'package:eatvio_app/core/theme/theme_helper.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)),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _chip(
|
||||
ChosenPlanStateEnum state, {
|
||||
bool hasPersonalDiet = true,
|
||||
String? personalDietName,
|
||||
}) {
|
||||
return PersonalDietStatusChip(
|
||||
progress: mapConsultationProgress(
|
||||
state: state,
|
||||
hasPersonalDiet: hasPersonalDiet,
|
||||
personalDietName: personalDietName,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
group('PersonalDietStatusChip', () {
|
||||
testWidgets('notRequired + active ничего не показывает', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(_chip(ChosenPlanStateEnum.stateInited, hasPersonalDiet: false)),
|
||||
);
|
||||
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byType(PersonalDietStatusChip),
|
||||
matching: find.byType(SizedBox),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.byType(Text), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('proposed показывает personal_diet_proposed', (tester) async {
|
||||
await tester.pumpWidget(_wrap(_chip(ChosenPlanStateEnum.stateStarted)));
|
||||
|
||||
final s = S.of(tester.element(find.byType(PersonalDietStatusChip)));
|
||||
|
||||
expect(find.text(s.personal_diet_proposed), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('proposed с названием показывает имя диеты', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(
|
||||
_chip(
|
||||
ChosenPlanStateEnum.stateStarted,
|
||||
personalDietName: 'Индивидуальный план питания',
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final s = S.of(tester.element(find.byType(PersonalDietStatusChip)));
|
||||
|
||||
expect(
|
||||
find.text(s.personal_diet_proposed_named('Индивидуальный план питания')),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('notProposed показывает personal_diet_not_proposed', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(_wrap(_chip(ChosenPlanStateEnum.statePaid)));
|
||||
|
||||
final s = S.of(tester.element(find.byType(PersonalDietStatusChip)));
|
||||
|
||||
expect(find.text(s.personal_diet_not_proposed), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('canceled показывает orderCanceled', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(_chip(ChosenPlanStateEnum.stateCanceledByTheInitiator)),
|
||||
);
|
||||
|
||||
final s = S.of(tester.element(find.byType(PersonalDietStatusChip)));
|
||||
|
||||
expect(find.text(s.orderCanceled), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('paymentFailed показывает payment_failed', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_wrap(_chip(ChosenPlanStateEnum.statePaymentFailed)),
|
||||
);
|
||||
|
||||
final s = S.of(tester.element(find.byType(PersonalDietStatusChip)));
|
||||
|
||||
expect(find.text(s.payment_failed), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
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';
|
||||
|
||||
typedef _Expected = ({
|
||||
Set<ConsultationStep> steps,
|
||||
bool plank,
|
||||
PersonalDietStatus diet,
|
||||
ConsultationPhase phase,
|
||||
});
|
||||
|
||||
const _startDate = ConsultationStep.startDate;
|
||||
const _paid = ConsultationStep.paid;
|
||||
const _inProgress = ConsultationStep.inProgress;
|
||||
const _finished = ConsultationStep.finished;
|
||||
|
||||
final Map<ChosenPlanStateEnum, _Expected> _expectations = {
|
||||
ChosenPlanStateEnum.stateInited: (
|
||||
steps: {},
|
||||
plank: false,
|
||||
diet: PersonalDietStatus.notProposed,
|
||||
phase: ConsultationPhase.active,
|
||||
),
|
||||
ChosenPlanStateEnum.stateStartDateHasBeenSet: (
|
||||
steps: {_startDate},
|
||||
plank: true,
|
||||
diet: PersonalDietStatus.notProposed,
|
||||
phase: ConsultationPhase.active,
|
||||
),
|
||||
ChosenPlanStateEnum.stateInCoordination: (
|
||||
steps: {},
|
||||
plank: true,
|
||||
diet: PersonalDietStatus.notProposed,
|
||||
phase: ConsultationPhase.active,
|
||||
),
|
||||
ChosenPlanStateEnum.stateStarted: (
|
||||
steps: {_startDate, _paid, _inProgress},
|
||||
plank: true,
|
||||
diet: PersonalDietStatus.proposed,
|
||||
phase: ConsultationPhase.active,
|
||||
),
|
||||
ChosenPlanStateEnum.stateInProgress: (
|
||||
steps: {_startDate, _paid, _inProgress},
|
||||
plank: true,
|
||||
diet: PersonalDietStatus.proposed,
|
||||
phase: ConsultationPhase.active,
|
||||
),
|
||||
ChosenPlanStateEnum.statePendingPayment: (
|
||||
steps: {_startDate},
|
||||
plank: true,
|
||||
diet: PersonalDietStatus.notProposed,
|
||||
phase: ConsultationPhase.active,
|
||||
),
|
||||
ChosenPlanStateEnum.stateConfirmedByConsultant: (
|
||||
steps: {},
|
||||
plank: false,
|
||||
diet: PersonalDietStatus.notProposed,
|
||||
phase: ConsultationPhase.active,
|
||||
),
|
||||
ChosenPlanStateEnum.statePaid: (
|
||||
steps: {_startDate, _paid},
|
||||
plank: true,
|
||||
diet: PersonalDietStatus.notProposed,
|
||||
phase: ConsultationPhase.active,
|
||||
),
|
||||
ChosenPlanStateEnum.stateCanceledByTheInitiator: (
|
||||
steps: {},
|
||||
plank: false,
|
||||
diet: PersonalDietStatus.notRequired,
|
||||
phase: ConsultationPhase.canceled,
|
||||
),
|
||||
ChosenPlanStateEnum.stateLastDayStarted: (
|
||||
steps: {_startDate, _paid, _inProgress},
|
||||
plank: true,
|
||||
diet: PersonalDietStatus.proposed,
|
||||
phase: ConsultationPhase.active,
|
||||
),
|
||||
ChosenPlanStateEnum.stateLastDayFinished: (
|
||||
steps: {_startDate, _paid, _inProgress},
|
||||
plank: true,
|
||||
diet: PersonalDietStatus.proposed,
|
||||
phase: ConsultationPhase.active,
|
||||
),
|
||||
ChosenPlanStateEnum.stateComplained: (
|
||||
steps: {_startDate, _paid, _inProgress},
|
||||
plank: true,
|
||||
diet: PersonalDietStatus.proposed,
|
||||
phase: ConsultationPhase.active,
|
||||
),
|
||||
ChosenPlanStateEnum.stateDone: (
|
||||
steps: {_startDate, _paid, _inProgress, _finished},
|
||||
plank: true,
|
||||
diet: PersonalDietStatus.proposed,
|
||||
phase: ConsultationPhase.active,
|
||||
),
|
||||
ChosenPlanStateEnum.personalDietSet: (
|
||||
steps: {_startDate, _paid},
|
||||
plank: true,
|
||||
diet: PersonalDietStatus.proposed,
|
||||
phase: ConsultationPhase.active,
|
||||
),
|
||||
ChosenPlanStateEnum.stateChargeWasCollected: (
|
||||
steps: {_startDate, _paid, _inProgress, _finished},
|
||||
plank: false,
|
||||
diet: PersonalDietStatus.proposed,
|
||||
phase: ConsultationPhase.active,
|
||||
),
|
||||
ChosenPlanStateEnum.statePaymentFailed: (
|
||||
steps: {_startDate},
|
||||
plank: false,
|
||||
diet: PersonalDietStatus.notRequired,
|
||||
phase: ConsultationPhase.paymentFailed,
|
||||
),
|
||||
};
|
||||
|
||||
void main() {
|
||||
group('mapConsultationProgress — все состояния', () {
|
||||
test('таблица покрывает ровно все 16 состояний', () {
|
||||
expect(_expectations.length, 16);
|
||||
expect(_expectations.keys.toSet(), ChosenPlanStateEnum.values.toSet());
|
||||
});
|
||||
|
||||
for (final entry in _expectations.entries) {
|
||||
test('${entry.key.name} маппится во все поля ConsultationProgress', () {
|
||||
final progress = mapConsultationProgress(
|
||||
state: entry.key,
|
||||
hasPersonalDiet: true,
|
||||
);
|
||||
|
||||
expect(progress.completedSteps, unorderedEquals(entry.value.steps));
|
||||
expect(progress.showProgressPlank, entry.value.plank);
|
||||
expect(progress.dietStatus, entry.value.diet);
|
||||
expect(progress.phase, entry.value.phase);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
group('mapConsultationProgress — ключевые сценарии', () {
|
||||
test('in_coordination показывает плашку без завершённых шагов', () {
|
||||
final progress = mapConsultationProgress(
|
||||
state: ChosenPlanStateEnum.stateInCoordination,
|
||||
hasPersonalDiet: true,
|
||||
);
|
||||
|
||||
expect(progress.showProgressPlank, isTrue);
|
||||
expect(progress.completedSteps, isEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'personal_diet_setted показывает плашку и завершает startDate+paid',
|
||||
() {
|
||||
final progress = mapConsultationProgress(
|
||||
state: ChosenPlanStateEnum.personalDietSet,
|
||||
hasPersonalDiet: true,
|
||||
);
|
||||
|
||||
expect(progress.showProgressPlank, isTrue);
|
||||
expect(progress.completedSteps, unorderedEquals([_startDate, _paid]));
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'started/in_progress/last_day_started/last_day_finished/complained — 3 шага',
|
||||
() {
|
||||
const states = [
|
||||
ChosenPlanStateEnum.stateStarted,
|
||||
ChosenPlanStateEnum.stateInProgress,
|
||||
ChosenPlanStateEnum.stateLastDayStarted,
|
||||
ChosenPlanStateEnum.stateLastDayFinished,
|
||||
ChosenPlanStateEnum.stateComplained,
|
||||
];
|
||||
|
||||
for (final state in states) {
|
||||
final progress = mapConsultationProgress(
|
||||
state: state,
|
||||
hasPersonalDiet: true,
|
||||
);
|
||||
|
||||
expect(
|
||||
progress.completedSteps,
|
||||
unorderedEquals([_startDate, _paid, _inProgress]),
|
||||
reason: 'state=${state.name}',
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test('done/charge_was_collected — 4 шага', () {
|
||||
const states = [
|
||||
ChosenPlanStateEnum.stateDone,
|
||||
ChosenPlanStateEnum.stateChargeWasCollected,
|
||||
];
|
||||
|
||||
for (final state in states) {
|
||||
final progress = mapConsultationProgress(
|
||||
state: state,
|
||||
hasPersonalDiet: true,
|
||||
);
|
||||
|
||||
expect(
|
||||
progress.completedSteps,
|
||||
unorderedEquals([_startDate, _paid, _inProgress, _finished]),
|
||||
reason: 'state=${state.name}',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
'canceled — фаза canceled и dietStatus notRequired даже при диете',
|
||||
() {
|
||||
final progress = mapConsultationProgress(
|
||||
state: ChosenPlanStateEnum.stateCanceledByTheInitiator,
|
||||
hasPersonalDiet: true,
|
||||
);
|
||||
|
||||
expect(progress.phase, ConsultationPhase.canceled);
|
||||
expect(progress.isCanceled, isTrue);
|
||||
expect(progress.dietStatus, PersonalDietStatus.notRequired);
|
||||
},
|
||||
);
|
||||
|
||||
test('payment_failed — фаза paymentFailed и только startDate', () {
|
||||
final progress = mapConsultationProgress(
|
||||
state: ChosenPlanStateEnum.statePaymentFailed,
|
||||
hasPersonalDiet: true,
|
||||
);
|
||||
|
||||
expect(progress.phase, ConsultationPhase.paymentFailed);
|
||||
expect(progress.isPaymentFailed, isTrue);
|
||||
expect(progress.completedSteps, unorderedEquals([_startDate]));
|
||||
});
|
||||
|
||||
test('hasPersonalDiet=false даёт notRequired для любого состояния', () {
|
||||
for (final state in ChosenPlanStateEnum.values) {
|
||||
final progress = mapConsultationProgress(
|
||||
state: state,
|
||||
hasPersonalDiet: false,
|
||||
);
|
||||
|
||||
expect(
|
||||
progress.dietStatus,
|
||||
PersonalDietStatus.notRequired,
|
||||
reason: 'state=${state.name}',
|
||||
);
|
||||
expect(progress.hasDietChip, isFalse, reason: 'state=${state.name}');
|
||||
}
|
||||
});
|
||||
|
||||
test('paid с диетой даёт notProposed', () {
|
||||
final progress = mapConsultationProgress(
|
||||
state: ChosenPlanStateEnum.statePaid,
|
||||
hasPersonalDiet: true,
|
||||
);
|
||||
|
||||
expect(progress.dietStatus, PersonalDietStatus.notProposed);
|
||||
});
|
||||
|
||||
test('personal_diet_setted/started/proposed дают proposed', () {
|
||||
const states = [
|
||||
ChosenPlanStateEnum.personalDietSet,
|
||||
ChosenPlanStateEnum.stateStarted,
|
||||
];
|
||||
|
||||
for (final state in states) {
|
||||
final progress = mapConsultationProgress(
|
||||
state: state,
|
||||
hasPersonalDiet: true,
|
||||
);
|
||||
|
||||
expect(
|
||||
progress.dietStatus,
|
||||
PersonalDietStatus.proposed,
|
||||
reason: 'state=${state.name}',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('personalDietName передаётся в ConsultationProgress', () {
|
||||
final progress = mapConsultationProgress(
|
||||
state: ChosenPlanStateEnum.personalDietSet,
|
||||
hasPersonalDiet: true,
|
||||
personalDietName: 'Индивидуальный план питания',
|
||||
);
|
||||
|
||||
expect(progress.personalDietName, 'Индивидуальный план питания');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -27,9 +27,7 @@ void main() {
|
||||
await tester.pumpWidget(
|
||||
createTestWidget(
|
||||
const ChosenDietWidgetContent(
|
||||
currentDietDay: 5,
|
||||
dietName: 'Test Diet',
|
||||
dietDuration: 14,
|
||||
dietId: 1,
|
||||
),
|
||||
),
|
||||
@@ -38,15 +36,14 @@ void main() {
|
||||
|
||||
expect(find.byType(ChosenDietWidgetContent), findsOneWidget);
|
||||
expect(find.text('Test Diet'), findsOneWidget);
|
||||
expect(find.textContaining('из 14'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('displays current day and duration', (tester) async {
|
||||
testWidgets('does not display current day and duration', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
createTestWidget(
|
||||
const ChosenDietWidgetContent(
|
||||
currentDietDay: 7,
|
||||
dietName: 'Test Diet',
|
||||
dietDuration: 21,
|
||||
dietId: 1,
|
||||
),
|
||||
),
|
||||
@@ -54,15 +51,14 @@ void main() {
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byType(ChosenDietWidgetContent), findsOneWidget);
|
||||
expect(find.textContaining('из 21'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('displays diet name with underline', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
createTestWidget(
|
||||
const ChosenDietWidgetContent(
|
||||
currentDietDay: 1,
|
||||
dietName: 'My Diet',
|
||||
dietDuration: 7,
|
||||
dietId: 1,
|
||||
),
|
||||
),
|
||||
@@ -70,6 +66,7 @@ void main() {
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('My Diet'), findsOneWidget);
|
||||
expect(find.textContaining('из 7'), findsNothing);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -100,6 +100,17 @@ void main() {
|
||||
await tester.pumpWidget(wrap(const ChosenDietWidget(), cubit));
|
||||
await tester.pump();
|
||||
expect(find.text('Diet'), findsOneWidget);
|
||||
expect(find.textContaining('из 7'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('ChosenDietWidget hides diet day while plan keeps its day', (tester) async {
|
||||
final cubit = FakeDiaryCubit(loadedState(hasDiet: true, hasPlan: true));
|
||||
await tester.pumpWidget(wrap(const Column(children: [ChosenPlanWidget(), ChosenDietWidget()]), cubit));
|
||||
await tester.pump();
|
||||
expect(find.text('Plan'), findsOneWidget);
|
||||
expect(find.textContaining('из 30'), findsOneWidget);
|
||||
expect(find.text('Diet'), findsOneWidget);
|
||||
expect(find.textContaining('из 7'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('AddProductButtonWidget renders for loaded state', (tester) async {
|
||||
|
||||
@@ -107,6 +107,11 @@ void main() {
|
||||
name: 'myPlansScreen',
|
||||
builder: (context, state) => const Scaffold(body: Text('My Plans')),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/video-call-recordings-screen',
|
||||
name: 'videoCallRecordingsScreen',
|
||||
builder: (context, state) => const Scaffold(body: Text('My Consultations')),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/consultant-finances-screen',
|
||||
name: 'consultantFinancesScreen',
|
||||
@@ -152,6 +157,7 @@ void main() {
|
||||
|
||||
expect(find.text('Меню'), findsOneWidget);
|
||||
expect(find.text('Настройки профиля'), findsOneWidget);
|
||||
expect(find.text('Мои консультации'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('renders menu screen for consultant', (tester) async {
|
||||
@@ -171,6 +177,7 @@ void main() {
|
||||
expect(find.text('Мои рецепты'), findsOneWidget);
|
||||
expect(find.text('Мои диеты'), findsOneWidget);
|
||||
expect(find.text('Мои планы'), findsOneWidget);
|
||||
expect(find.text('Мои консультации'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -92,6 +92,7 @@ void main() {
|
||||
DiaryReminderForUsersNotification.fromJson(base, NotificationType.diaryReminderForUsers);
|
||||
DiaryReminderForUsersNotification.fromJson({'created_at': c, 'data': <String, dynamic>{}}, NotificationType.diaryReminderForUsers);
|
||||
PersonalDietIsDefinedToCustomerNotification.fromJson(base, NotificationType.personalDietIsDefinedToCustomer);
|
||||
PersonalDietIsDefinedToAuthorNotification.fromJson(base, NotificationType.personalDietIsDefinedToAuthor);
|
||||
ConsultantEducationUpdatedNotification.fromJson(base, NotificationType.consultantEducationUpdated);
|
||||
ComplaintRegisteredNotification.fromJson(base, NotificationType.complaintRegistered);
|
||||
ContentUnpublishedNotification.fromJson(base, NotificationType.contentUnpublished);
|
||||
|
||||
@@ -50,6 +50,7 @@ void main() {
|
||||
'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,
|
||||
};
|
||||
|
||||
cases.forEach((key, expected) {
|
||||
@@ -671,6 +672,34 @@ void main() {
|
||||
expect(notification.type, NotificationType.personalizedDietIsDefined);
|
||||
});
|
||||
|
||||
test('PersonalDietIsDefinedToAuthorNotification.fromJson parses all fields', () {
|
||||
final json = {
|
||||
'chosen_plan_id': 12,
|
||||
'diet_id': 34,
|
||||
'plan_name': 'Plan',
|
||||
'user_name': 'Client',
|
||||
'consultant_name': 'Consultant',
|
||||
'diet_name': 'Personal diet',
|
||||
'role': 'consultant',
|
||||
'peer_slug': 'client-slug',
|
||||
'peer_image_path': 'avatars/client.png',
|
||||
'created_at': '2024-01-30T12:00:00Z',
|
||||
};
|
||||
|
||||
final notification = PersonalDietIsDefinedToAuthorNotification.fromJson(
|
||||
json,
|
||||
NotificationType.personalDietIsDefinedToAuthor,
|
||||
isRead: false,
|
||||
);
|
||||
|
||||
expect(notification.chosenPlanId, 12);
|
||||
expect(notification.dietId, 34);
|
||||
expect(notification.userName, 'Client');
|
||||
expect(notification.dietName, 'Personal diet');
|
||||
expect(notification.peerSlug, 'client-slug');
|
||||
expect(notification.type, NotificationType.personalDietIsDefinedToAuthor);
|
||||
});
|
||||
|
||||
test('ChosenPlanFinishedToClientNotification.fromJson parses all fields', () {
|
||||
final json = {
|
||||
'plan_name': 'Finished Plan',
|
||||
|
||||
@@ -1212,6 +1212,89 @@ void main() {
|
||||
expect(find.byType(NotificationWidget), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('displays PersonalDietIsDefinedToAuthorNotification', (
|
||||
tester,
|
||||
) async {
|
||||
final notification = PersonalDietIsDefinedToAuthorNotification(
|
||||
type: NotificationType.personalDietIsDefinedToAuthor,
|
||||
isRead: false,
|
||||
createdAt: testDate,
|
||||
chosenPlanId: 1,
|
||||
dietId: 1,
|
||||
planName: 'Plan',
|
||||
userName: 'Client',
|
||||
consultantName: 'Consultant',
|
||||
dietName: 'Test Diet',
|
||||
role: 'consultant',
|
||||
peerSlug: 'client-slug',
|
||||
peerImagePath: '',
|
||||
);
|
||||
|
||||
await tester.pumpWidget(createTestWidget(notification));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(
|
||||
find.text('Вы предложили персональную диету пользователю Client, выбранная диета: «Test Diet»'),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'displays PersonalDietIsDefinedToAuthorNotification with fallback user name',
|
||||
(tester) async {
|
||||
final notification = PersonalDietIsDefinedToAuthorNotification(
|
||||
type: NotificationType.personalDietIsDefinedToAuthor,
|
||||
isRead: false,
|
||||
createdAt: testDate,
|
||||
chosenPlanId: 1,
|
||||
dietId: 1,
|
||||
planName: 'Plan',
|
||||
userName: '',
|
||||
consultantName: 'Consultant',
|
||||
dietName: 'Test Diet',
|
||||
role: 'consultant',
|
||||
peerSlug: 'client-slug',
|
||||
peerImagePath: '',
|
||||
);
|
||||
|
||||
await tester.pumpWidget(createTestWidget(notification));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(
|
||||
find.text('Вы предложили персональную диету пользователю Пользователь, выбранная диета: «Test Diet»'),
|
||||
findsOneWidget,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'displays PersonalDietIsDefinedToAuthorNotification without diet name',
|
||||
(tester) async {
|
||||
final notification = PersonalDietIsDefinedToAuthorNotification(
|
||||
type: NotificationType.personalDietIsDefinedToAuthor,
|
||||
isRead: false,
|
||||
createdAt: testDate,
|
||||
chosenPlanId: 1,
|
||||
dietId: 1,
|
||||
planName: 'Plan',
|
||||
userName: 'Client',
|
||||
consultantName: 'Consultant',
|
||||
dietName: '',
|
||||
role: 'consultant',
|
||||
peerSlug: 'client-slug',
|
||||
peerImagePath: '',
|
||||
);
|
||||
|
||||
await tester.pumpWidget(createTestWidget(notification));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(
|
||||
find.text('Вы предложили персональную диету пользователю Client'),
|
||||
findsOneWidget,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('displays UnknownNotification', (tester) async {
|
||||
final notification = UnknownNotification(
|
||||
type: NotificationType.unknown,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/features/notifications/models/notification_model.dart';
|
||||
import 'package:eatvio_app/features/notifications/service/notifications_service.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mockito/annotations.dart';
|
||||
@@ -1454,6 +1455,42 @@ void main() {
|
||||
expect(result, isNotNull);
|
||||
expect(result!['notifications'], isA<List>());
|
||||
expect(result['notifications'].length, 1);
|
||||
expect(result['notifications'].first, isA<PersonalDietIsDefinedToCustomerNotification>());
|
||||
});
|
||||
|
||||
test('getNotifications - обрабатывает PersonalDietIsDefinedToAuthor', () async {
|
||||
const page = 1;
|
||||
final response = Response(
|
||||
data: {
|
||||
'data': [
|
||||
{
|
||||
'type': 'personal-diet-is-defined-to-author',
|
||||
'data': {
|
||||
'diet_name': 'Test Diet',
|
||||
'diet_id': 1,
|
||||
'user_name': 'Client',
|
||||
},
|
||||
'read_at': null,
|
||||
'created_at': '2024-01-01T12:00:00Z',
|
||||
},
|
||||
],
|
||||
'current_page': 1,
|
||||
'last_page': 1,
|
||||
'per_page': 10,
|
||||
'total': 1,
|
||||
},
|
||||
statusCode: 200,
|
||||
requestOptions: RequestOptions(path: '/api/profile/notifications'),
|
||||
);
|
||||
|
||||
when(mockDio.get(any)).thenAnswer((_) async => response);
|
||||
|
||||
final result = await notificationsService.getNotifications(page: page);
|
||||
|
||||
expect(result, isNotNull);
|
||||
expect(result!['notifications'], isA<List>());
|
||||
expect(result['notifications'].length, 1);
|
||||
expect(result['notifications'].first, isA<PersonalDietIsDefinedToAuthorNotification>());
|
||||
});
|
||||
|
||||
test('getNotifications - обрабатывает UserDailyReportCompleted', () async {
|
||||
|
||||
@@ -243,12 +243,12 @@ void main() {
|
||||
expect(find.byType(InfoByOrderScreen), findsOneWidget);
|
||||
});
|
||||
|
||||
ChosenPlanModel donePlan() {
|
||||
ChosenPlanModel donePlan({ChosenPlanStateEnum state = ChosenPlanStateEnum.stateDone}) {
|
||||
return ChosenPlanModel(
|
||||
id: 1,
|
||||
optionType: 'options1',
|
||||
startDate: DateTime(2024, 1, 1),
|
||||
chosenPlanState: ChosenPlanStateEnum.stateDone,
|
||||
chosenPlanState: state,
|
||||
chatId: 'chat-1',
|
||||
consultantId: 1,
|
||||
plan: const PlanModel(
|
||||
@@ -320,6 +320,7 @@ void main() {
|
||||
|
||||
expect(find.byType(CollectChargeBanner), findsOneWidget);
|
||||
expect(find.text('Получить выплату'), findsOneWidget);
|
||||
expect(find.text('Отменить консультацию'), findsNothing);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -337,6 +338,22 @@ void main() {
|
||||
|
||||
expect(find.byType(CollectChargeBanner), findsNothing);
|
||||
expect(find.text('Получить выплату'), findsNothing);
|
||||
expect(find.text('Отменить консультацию'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('shows cancel action for cancellable post-paid plan', (
|
||||
WidgetTester tester,
|
||||
) async {
|
||||
when(
|
||||
mockChatRepository.getChosenPlan(id: anyNamed('id')),
|
||||
).thenAnswer((_) async => donePlan(state: ChosenPlanStateEnum.stateStarted));
|
||||
|
||||
await mockNetworkImagesFor(() async {
|
||||
await tester.pumpWidget(createTestWidget(planId: 1));
|
||||
await tester.pumpAndSettle();
|
||||
});
|
||||
|
||||
expect(find.text('Отменить консультацию'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ void main() {
|
||||
return formResult;
|
||||
}
|
||||
|
||||
Future<void> mockSbp(BuildContext context, {required int planId}) async {
|
||||
Future<void> mockSbp(BuildContext context, {required int planId, double? amount}) async {
|
||||
sbpCalled = true;
|
||||
sbpPlanId = planId;
|
||||
}
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:eatvio_app/core/app_config.dart';
|
||||
import 'package:eatvio_app/core/app_initializer.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/widgets/loader.dart';
|
||||
import 'package:eatvio_app/features/chat/models/payment_model.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/widgets/sbp_banks_bottom_sheet.dart';
|
||||
import 'package:eatvio_app/features/payment/presentation/widgets/sbp_qr_bottom_sheet.dart';
|
||||
import 'package:eatvio_app/features/payment/repositories/payment_repository.dart';
|
||||
import 'package:eatvio_app/features/payment/repositories/sbp_repository.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';
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:mockito/annotations.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:qr_flutter/qr_flutter.dart';
|
||||
import 'package:sbp/models/c2bmembers_model.dart';
|
||||
|
||||
import '../../../../fixtures/fixture_reader.dart';
|
||||
@@ -21,9 +29,21 @@ import 'sbp_banks_bottom_sheet_test.mocks.dart';
|
||||
@GenerateNiceMocks([
|
||||
MockSpec<PaymentRepository>(),
|
||||
MockSpec<SbpRepository>(),
|
||||
MockSpec<ChatRepository>(),
|
||||
])
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
// AppConfig в конструкторе читает EnvConfig (dotenv) — инициализируем.
|
||||
setUpAll(() async {
|
||||
await dotenv.load(
|
||||
fileName: 'test.env',
|
||||
isOptional: true,
|
||||
mergeWith: const {
|
||||
'BASE_URL': 'https://eatvio.ru',
|
||||
'DEV_BASE_URL': 'https://dev2.eatvio.com',
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
group('SbpBanksBottomSheet', () {
|
||||
late MockPaymentRepository mockPaymentRepository;
|
||||
@@ -183,5 +203,66 @@ void main() {
|
||||
expect(find.byType(Loader), findsNothing);
|
||||
expect(find.text('Нет установленных банков'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('QR-кнопка доступна до загрузки списка банков', (tester) async {
|
||||
const planId = 12;
|
||||
final banksCompleter = Completer<List<C2bmemberModel>>();
|
||||
|
||||
when(
|
||||
mockPaymentRepository.startPaymentProcess(planId: planId),
|
||||
).thenAnswer((_) async => alfaPayment);
|
||||
when(mockSbpRepository.getInstalledBanks()).thenAnswer((_) => banksCompleter.future);
|
||||
sl.registerLazySingleton<AppConfig>(
|
||||
() => AppConfig(buildType: AppBuildType.tests),
|
||||
);
|
||||
sl.registerLazySingleton<ChatRepository>(() => MockChatRepository());
|
||||
|
||||
await tester.pumpWidget(createTestWidget(planId: planId));
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
|
||||
// Банки ещё грузятся (Loader), а QR-кнопка уже доступна.
|
||||
expect(find.byType(Loader), findsOneWidget);
|
||||
expect(find.text('Оплатить по QR-коду'), findsOneWidget);
|
||||
|
||||
banksCompleter.complete([installedBank]);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(Loader), findsNothing);
|
||||
expect(find.text('Сбербанк'), findsOneWidget);
|
||||
expect(find.text('Оплатить по QR-коду'), findsOneWidget);
|
||||
|
||||
await GetIt.I.reset();
|
||||
});
|
||||
|
||||
testWidgets('после старта оплаты показывает кнопку QR и открывает QR-шит', (tester) async {
|
||||
const planId = 12;
|
||||
|
||||
when(
|
||||
mockPaymentRepository.startPaymentProcess(planId: planId),
|
||||
).thenAnswer((_) async => alfaPayment);
|
||||
when(mockSbpRepository.getInstalledBanks()).thenAnswer((_) async => [installedBank]);
|
||||
sl.registerLazySingleton<AppConfig>(
|
||||
() => AppConfig(buildType: AppBuildType.tests),
|
||||
);
|
||||
sl.registerLazySingleton<ChatRepository>(() => MockChatRepository());
|
||||
|
||||
await tester.pumpWidget(createTestWidget(planId: planId));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Оплатить по QR-коду'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.text('Оплатить по QR-коду'));
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
expect(find.byType(SbpQrBottomSheet), findsOneWidget);
|
||||
expect(find.byType(QrImageView), findsOneWidget);
|
||||
|
||||
// Закрываем QR-шит (останавливает polling-таймер).
|
||||
tester.state<NavigatorState>(find.byType(Navigator).first).pop();
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
|
||||
await GetIt.I.reset();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
import 'package:eatvio_app/core/app_config.dart';
|
||||
import 'package:eatvio_app/core/app_initializer.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/features/chat/repositories/chat_repository.dart';
|
||||
import 'package:eatvio_app/features/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/features/payment/repositories/payment_repository.dart';
|
||||
import 'package:eatvio_app/features/payment/repositories/sbp_repository.dart';
|
||||
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||
import 'package:eatvio_app/features/plans/models/chosen_plan_model.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';
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:mockito/annotations.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:qr_flutter/qr_flutter.dart';
|
||||
|
||||
import 'sbp_qr_bottom_sheet_test.mocks.dart';
|
||||
|
||||
@GenerateNiceMocks([
|
||||
MockSpec<PaymentRepository>(),
|
||||
MockSpec<SbpRepository>(),
|
||||
MockSpec<ChatRepository>(),
|
||||
MockSpec<ChosenPlanModel>(),
|
||||
])
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
const planId = 12;
|
||||
const checkoutUrl = 'https://qr.nspk.ru/AD10106TB0BVFTBG9DQ96NKJEIVVTKIO';
|
||||
|
||||
group('SbpQrBottomSheet', () {
|
||||
late MockPaymentRepository mockPaymentRepository;
|
||||
late MockSbpRepository mockSbpRepository;
|
||||
late MockChatRepository mockChatRepository;
|
||||
late MockChosenPlanModel mockPlan;
|
||||
late ConsultationPaymentCubit cubit;
|
||||
late Future<bool?>? sheetResult;
|
||||
|
||||
setUp(() async {
|
||||
await GetIt.I.reset();
|
||||
// AppConfig в конструкторе читает EnvConfig (dotenv) — инициализируем.
|
||||
await dotenv.load(
|
||||
fileName: 'test.env',
|
||||
isOptional: true,
|
||||
mergeWith: const {
|
||||
'BASE_URL': 'https://eatvio.ru',
|
||||
'DEV_BASE_URL': 'https://dev2.eatvio.com',
|
||||
},
|
||||
);
|
||||
sl.registerLazySingleton<AppConfig>(
|
||||
() => AppConfig(buildType: AppBuildType.tests),
|
||||
);
|
||||
sl.registerLazySingleton<ChatRepository>(() => mockChatRepository);
|
||||
|
||||
mockPaymentRepository = MockPaymentRepository();
|
||||
mockSbpRepository = MockSbpRepository();
|
||||
mockChatRepository = MockChatRepository();
|
||||
mockPlan = MockChosenPlanModel();
|
||||
cubit = ConsultationPaymentCubit(
|
||||
paymentRepository: mockPaymentRepository,
|
||||
sbpRepository: mockSbpRepository,
|
||||
);
|
||||
cubit.emit(
|
||||
ConsultationPaymentState(
|
||||
isLoading: false,
|
||||
checkoutUrl: checkoutUrl,
|
||||
),
|
||||
);
|
||||
sheetResult = null;
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await GetIt.I.reset();
|
||||
await cubit.close();
|
||||
});
|
||||
|
||||
Future<void> pumpApp(WidgetTester tester, {double? amount}) {
|
||||
return tester.pumpWidget(
|
||||
MaterialApp(
|
||||
theme: ThemeHelper().themeData(),
|
||||
localizationsDelegates: const [
|
||||
S.delegate,
|
||||
GlobalMaterialLocalizations.delegate,
|
||||
GlobalWidgetsLocalizations.delegate,
|
||||
GlobalCupertinoLocalizations.delegate,
|
||||
],
|
||||
supportedLocales: const [Locale('ru')],
|
||||
home: Scaffold(
|
||||
body: Builder(
|
||||
builder: (context) => Center(
|
||||
child: ElevatedButton(
|
||||
onPressed: () => sheetResult = showSbpQrBottomSheet(
|
||||
context,
|
||||
planId: planId,
|
||||
cubit: cubit,
|
||||
amount: amount,
|
||||
),
|
||||
child: const Text('open'),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> openSheet(WidgetTester tester, {double? amount}) async {
|
||||
await pumpApp(tester, amount: amount);
|
||||
await tester.tap(find.text('open'));
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
/// Закрывает шит, чтобы остановить polling-таймер в конце теста.
|
||||
Future<void> closeSheet(WidgetTester tester) async {
|
||||
final navigator = tester.state<NavigatorState>(
|
||||
find.byType(Navigator).first,
|
||||
);
|
||||
navigator.pop();
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
void stubPlanState(ChosenPlanStateEnum state) {
|
||||
when(mockChatRepository.getChosenPlan(id: planId))
|
||||
.thenAnswer((_) async => mockPlan);
|
||||
when(mockPlan.chosenPlanState).thenReturn(state);
|
||||
}
|
||||
|
||||
/// Перерегистрирует DI с AppConfig, смотрящим на конкретный base URL.
|
||||
Future<void> useApiBaseUrl(String baseUrl) async {
|
||||
await GetIt.I.reset();
|
||||
sl.registerLazySingleton<AppConfig>(
|
||||
() => AppConfig(buildType: AppBuildType.tests)..setBaseUrl(baseUrl),
|
||||
);
|
||||
sl.registerLazySingleton<ChatRepository>(() => mockChatRepository);
|
||||
}
|
||||
|
||||
testWidgets('рендерит QR-код из checkout_url и инструкцию', (tester) async {
|
||||
stubPlanState(ChosenPlanStateEnum.statePendingPayment);
|
||||
|
||||
await openSheet(tester);
|
||||
|
||||
expect(find.byKey(const ValueKey('sbp_qr_code')), findsOneWidget);
|
||||
expect(find.byType(QrImageView), findsOneWidget);
|
||||
expect(find.text('Оплата по QR-коду'), findsOneWidget);
|
||||
expect(find.text('Ожидание оплаты…'), findsOneWidget);
|
||||
|
||||
await closeSheet(tester);
|
||||
});
|
||||
|
||||
testWidgets('показывает сумму, если передана', (tester) async {
|
||||
stubPlanState(ChosenPlanStateEnum.statePendingPayment);
|
||||
|
||||
await openSheet(tester, amount: 1200);
|
||||
|
||||
expect(find.text('Сумма к оплате'), findsOneWidget);
|
||||
expect(find.text('1200 ₽'), findsOneWidget);
|
||||
|
||||
await closeSheet(tester);
|
||||
});
|
||||
|
||||
testWidgets('не показывает сумму, если не передана', (tester) async {
|
||||
stubPlanState(ChosenPlanStateEnum.statePendingPayment);
|
||||
|
||||
await openSheet(tester);
|
||||
|
||||
expect(find.text('Сумма к оплате'), findsNothing);
|
||||
|
||||
await closeSheet(tester);
|
||||
});
|
||||
|
||||
testWidgets('показывает тестовую кнопку на stage-стенде (dev2)', (tester) async {
|
||||
stubPlanState(ChosenPlanStateEnum.statePendingPayment);
|
||||
await useApiBaseUrl('https://dev2.eatvio.com');
|
||||
|
||||
await openSheet(tester);
|
||||
|
||||
expect(find.text('Открыть тестовую оплату'), findsOneWidget);
|
||||
|
||||
await closeSheet(tester);
|
||||
});
|
||||
|
||||
testWidgets('показывает тестовую кнопку на стенде-поддомене прод-хоста', (tester) async {
|
||||
stubPlanState(ChosenPlanStateEnum.statePendingPayment);
|
||||
// Поддомен eatvio.ru — стенд (например, hasan), а не прод.
|
||||
await useApiBaseUrl('https://ubooquiequ7ohz9ias3aik4a-hasan.eatvio.ru');
|
||||
|
||||
await openSheet(tester);
|
||||
|
||||
expect(find.text('Открыть тестовую оплату'), findsOneWidget);
|
||||
|
||||
await closeSheet(tester);
|
||||
});
|
||||
|
||||
testWidgets('скрывает тестовую кнопку на продуктовом API', (tester) async {
|
||||
stubPlanState(ChosenPlanStateEnum.statePendingPayment);
|
||||
await useApiBaseUrl('https://eatvio.ru');
|
||||
|
||||
await openSheet(tester);
|
||||
|
||||
expect(find.text('Открыть тестовую оплату'), findsNothing);
|
||||
// Сам QR при этом работает.
|
||||
expect(find.byType(QrImageView), findsOneWidget);
|
||||
|
||||
await closeSheet(tester);
|
||||
});
|
||||
|
||||
testWidgets('скрывает тестовую кнопку на продуктовом API (eatvio.com)', (tester) async {
|
||||
stubPlanState(ChosenPlanStateEnum.statePendingPayment);
|
||||
await useApiBaseUrl('https://eatvio.com');
|
||||
|
||||
await openSheet(tester);
|
||||
|
||||
expect(find.text('Открыть тестовую оплату'), findsNothing);
|
||||
|
||||
await closeSheet(tester);
|
||||
});
|
||||
|
||||
testWidgets('при оплате (statePaid) показывает успех и закрывает шит', (tester) async {
|
||||
stubPlanState(ChosenPlanStateEnum.statePaid);
|
||||
|
||||
await openSheet(tester);
|
||||
|
||||
// Первый poll выполняется сразу в initState.
|
||||
await tester.pump();
|
||||
expect(find.text('Оплата прошла успешно!'), findsOneWidget);
|
||||
|
||||
// Автозакрытие через 2 секунды.
|
||||
await tester.pump(const Duration(seconds: 2));
|
||||
await tester.pump();
|
||||
expect(find.byType(SbpQrBottomSheet), findsNothing);
|
||||
expect(await sheetResult, isTrue);
|
||||
});
|
||||
|
||||
testWidgets('до оплаты продолжает ждать', (tester) async {
|
||||
stubPlanState(ChosenPlanStateEnum.statePendingPayment);
|
||||
|
||||
await openSheet(tester);
|
||||
|
||||
await tester.pump(const Duration(seconds: 3));
|
||||
await tester.pump();
|
||||
|
||||
expect(find.text('Оплата прошла успешно!'), findsNothing);
|
||||
expect(find.text('Ожидание оплаты…'), findsOneWidget);
|
||||
|
||||
await closeSheet(tester);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -34,6 +34,7 @@ void main() {
|
||||
expect(cubit.state.consultationsWithDiet, isEmpty);
|
||||
expect(cubit.state.consultationsWithoutDiet, isEmpty);
|
||||
expect(cubit.state.dietName, isEmpty);
|
||||
expect(cubit.state.dietDuration, 0);
|
||||
expect(cubit.state.isLoading, isFalse);
|
||||
expect(cubit.state.error, isNull);
|
||||
});
|
||||
@@ -71,6 +72,7 @@ void main() {
|
||||
await cubit.setDietName(dietId);
|
||||
|
||||
expect(cubit.state.dietName, equals(dietName));
|
||||
expect(cubit.state.dietDuration, 30);
|
||||
expect(cubit.state.isLoading, isFalse);
|
||||
verify(mockDietRepository.getDiet(dietId)).called(1);
|
||||
});
|
||||
@@ -161,6 +163,7 @@ void main() {
|
||||
await cubit.getConsultationWithPersonalDiets(dietId);
|
||||
|
||||
expect(cubit.state.dietName, equals(dietName));
|
||||
expect(cubit.state.dietDuration, 30);
|
||||
expect(cubit.state.consultationsWithDiet.length, 1);
|
||||
expect(cubit.state.consultationsWithoutDiet.length, 1);
|
||||
expect(cubit.state.isLoading, isFalse);
|
||||
@@ -216,6 +219,8 @@ void main() {
|
||||
consultationId: consultationId,
|
||||
dietId: dietId,
|
||||
)).called(1);
|
||||
verify(mockPersonalDietSuggestionRepository.getConsultationWithPersonalDiets()).called(2);
|
||||
verify(mockDietRepository.getDiet(dietId)).called(2);
|
||||
});
|
||||
|
||||
test('reattachDietToConsultation - успешное переприкрепление диеты', () async {
|
||||
@@ -265,6 +270,8 @@ void main() {
|
||||
consultationId: consultationId,
|
||||
dietId: dietId,
|
||||
)).called(1);
|
||||
verify(mockPersonalDietSuggestionRepository.getConsultationWithPersonalDiets()).called(2);
|
||||
verify(mockDietRepository.getDiet(dietId)).called(2);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ void main() {
|
||||
expect(state.consultationsWithDiet, isEmpty);
|
||||
expect(state.consultationsWithoutDiet, isEmpty);
|
||||
expect(state.dietName, '');
|
||||
expect(state.dietDuration, 0);
|
||||
expect(state.isLoading, isFalse);
|
||||
expect(state.error, isNull);
|
||||
});
|
||||
@@ -16,6 +17,7 @@ void main() {
|
||||
test('creates instance with custom values', () {
|
||||
final state = PersonalDietSuggestionState(
|
||||
dietName: 'Test Diet',
|
||||
dietDuration: 14,
|
||||
isLoading: true,
|
||||
error: 'Test error',
|
||||
);
|
||||
@@ -23,6 +25,7 @@ void main() {
|
||||
expect(state.consultationsWithDiet, isEmpty);
|
||||
expect(state.consultationsWithoutDiet, isEmpty);
|
||||
expect(state.dietName, 'Test Diet');
|
||||
expect(state.dietDuration, 14);
|
||||
expect(state.isLoading, isTrue);
|
||||
expect(state.error, 'Test error');
|
||||
});
|
||||
@@ -31,14 +34,15 @@ void main() {
|
||||
final original = PersonalDietSuggestionState();
|
||||
final updated = original.copyWith(
|
||||
dietName: 'New Diet',
|
||||
dietDuration: 7,
|
||||
isLoading: true,
|
||||
);
|
||||
|
||||
expect(updated.dietName, 'New Diet');
|
||||
expect(updated.dietDuration, 7);
|
||||
expect(updated.isLoading, isTrue);
|
||||
expect(updated.consultationsWithDiet, original.consultationsWithDiet);
|
||||
expect(updated.error, original.error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'package:eatvio_app/core/app_config.dart';
|
||||
import 'package:eatvio_app/core/app_initializer.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/utils/localization_utils.dart';
|
||||
import 'package:eatvio_app/features/consultations/models/consultation_model.dart';
|
||||
import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart';
|
||||
import 'package:eatvio_app/features/personal_diet_suggestion/cubit/personal_diet_suggestion_cubit.dart';
|
||||
@@ -34,6 +35,7 @@ void main() {
|
||||
|
||||
final mockConsultation = ConsultationModel(
|
||||
id: 1,
|
||||
chatId: 'chat-1',
|
||||
chosenPlanState: ChosenPlanStateEnum.stateInProgress,
|
||||
planTitle: 'Test Plan',
|
||||
userName: 'Test User',
|
||||
@@ -68,6 +70,32 @@ void main() {
|
||||
path: '/personal-diet-suggestion',
|
||||
builder: (context, state) => const Scaffold(body: Text('Personal Diet')),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/chat-select-screen',
|
||||
name: 'chatSelectScreen',
|
||||
builder: (context, state) => const Scaffold(body: Text('Chats')),
|
||||
),
|
||||
GoRoute(
|
||||
path: '/chat-screen',
|
||||
name: 'chatScreen',
|
||||
builder: (context, state) {
|
||||
final uuid = state.uri.queryParameters['uuid'];
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: BackButton(
|
||||
onPressed: () {
|
||||
if (context.canPop()) {
|
||||
GoRouter.of(context).pop();
|
||||
return;
|
||||
}
|
||||
GoRouter.of(context).go('/chat-select-screen');
|
||||
},
|
||||
),
|
||||
),
|
||||
body: Text('Chat $uuid'),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
@@ -201,7 +229,7 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('shows success bottom sheet after successful diet attachment', (tester) async {
|
||||
testWidgets('opens chat after successful diet attachment', (tester) async {
|
||||
await mockNetworkImagesFor(() async {
|
||||
final cubit = MockPersonalDietSuggestionCubit();
|
||||
|
||||
@@ -226,7 +254,99 @@ void main() {
|
||||
await tester.tap(offerButton);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('«Test Diet» предложена пользователю Test User'), findsOneWidget);
|
||||
expect(find.text('Chat chat-1'), findsOneWidget);
|
||||
verify(cubit.attachDietToConsultation(consultationId: 1)).called(1);
|
||||
|
||||
await tester.tap(find.byType(BackButton));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Chats'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('opens chat after successful diet reattachment', (tester) async {
|
||||
await mockNetworkImagesFor(() async {
|
||||
final cubit = MockPersonalDietSuggestionCubit();
|
||||
final consultationWithDiet = ConsultationModel(
|
||||
id: 1,
|
||||
chatId: 'chat-2',
|
||||
chosenPlanState: ChosenPlanStateEnum.stateInProgress,
|
||||
planTitle: 'Test Plan',
|
||||
userName: 'Test User',
|
||||
userSlug: 'test-user',
|
||||
consultantPayment: 1000.0,
|
||||
duration: 7,
|
||||
currentDiaryDay: 3,
|
||||
userProfilePhotoUrl: '/avatar.jpg',
|
||||
consultationOptionPrice: 500,
|
||||
startDate: DateTime(2025, 1, 1),
|
||||
endDate: DateTime(2025, 1, 8),
|
||||
consultantId: 1,
|
||||
diaries: [],
|
||||
personalDietId: 1,
|
||||
);
|
||||
|
||||
when(cubit.state).thenReturn(PersonalDietSuggestionState());
|
||||
when(cubit.stream).thenAnswer((_) => const Stream.empty());
|
||||
when(cubit.close()).thenAnswer((_) async => Future<void>.value());
|
||||
when(cubit.reattachDietToConsultation(consultationId: 1)).thenAnswer((_) async => true);
|
||||
|
||||
await tester.pumpWidget(
|
||||
BlocProvider<PersonalDietSuggestionCubit>.value(
|
||||
value: cubit,
|
||||
child: wrap(ConsultationWidget(consultationModel: consultationWithDiet, dietName: 'Test Diet')),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final changeButton = find.text(S.of(tester.element(find.byType(ConsultationWidget))).changeDiet);
|
||||
await tester.tap(changeButton);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final offerButton = find.text(S.of(tester.element(find.byType(ConsultationWidget))).toOffer);
|
||||
await tester.tap(offerButton);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Chat chat-2'), findsOneWidget);
|
||||
verify(cubit.reattachDietToConsultation(consultationId: 1)).called(1);
|
||||
verifyNever(cubit.attachDietToConsultation(consultationId: 1));
|
||||
|
||||
await tester.tap(find.byType(BackButton));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Chats'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('stays on screen when chat id is missing after success', (tester) async {
|
||||
await mockNetworkImagesFor(() async {
|
||||
final cubit = MockPersonalDietSuggestionCubit();
|
||||
|
||||
when(cubit.state).thenReturn(PersonalDietSuggestionState());
|
||||
when(cubit.stream).thenAnswer((_) => const Stream.empty());
|
||||
when(cubit.close()).thenAnswer((_) async => Future<void>.value());
|
||||
when(cubit.attachDietToConsultation(consultationId: 1)).thenAnswer((_) async => true);
|
||||
|
||||
await tester.pumpWidget(
|
||||
BlocProvider<PersonalDietSuggestionCubit>.value(
|
||||
value: cubit,
|
||||
child: wrap(
|
||||
ConsultationWidget(
|
||||
consultationModel: mockConsultation.copyWith(chatId: null),
|
||||
dietName: 'Test Diet',
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.text('Предложить диету'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text(S.of(tester.element(find.byType(ConsultationWidget))).toOffer));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.textContaining('Chat '), findsNothing);
|
||||
expect(find.text('Test User'), findsOneWidget);
|
||||
verify(cubit.attachDietToConsultation(consultationId: 1)).called(1);
|
||||
});
|
||||
});
|
||||
@@ -279,7 +399,7 @@ void main() {
|
||||
|
||||
expect(find.text('Test User'), findsOneWidget);
|
||||
expect(find.text('Test Plan'), findsOneWidget);
|
||||
expect(find.text('Старт: Test User'), findsOneWidget);
|
||||
expect(find.text('Старт: 01.01.2025'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -318,7 +438,71 @@ void main() {
|
||||
|
||||
expect(find.text('Test User'), findsOneWidget);
|
||||
expect(find.text('Test Plan'), findsOneWidget);
|
||||
expect(find.text('Старт: Test User'), findsNothing);
|
||||
expect(find.text('Старт: 01.01.2025'), findsNothing);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('disables CTA when plan duration differs from diet duration', (tester) async {
|
||||
await mockNetworkImagesFor(() async {
|
||||
final cubit = MockPersonalDietSuggestionCubit();
|
||||
final consultation = ConsultationModel(
|
||||
id: 1,
|
||||
chosenPlanState: ChosenPlanStateEnum.stateInProgress,
|
||||
planTitle: 'Test Plan',
|
||||
userName: 'Test User',
|
||||
userSlug: 'test-user',
|
||||
consultantPayment: 1000.0,
|
||||
duration: 14,
|
||||
currentDiaryDay: 3,
|
||||
userProfilePhotoUrl: '/avatar.jpg',
|
||||
consultationOptionPrice: 500,
|
||||
startDate: DateTime(2025, 1, 1),
|
||||
endDate: DateTime(2025, 1, 15),
|
||||
consultantId: 1,
|
||||
diaries: [],
|
||||
personalDietId: null,
|
||||
);
|
||||
|
||||
when(cubit.state).thenReturn(PersonalDietSuggestionState());
|
||||
when(cubit.stream).thenAnswer((_) => const Stream.empty());
|
||||
when(cubit.close()).thenAnswer((_) async => Future<void>.value());
|
||||
|
||||
await tester.pumpWidget(
|
||||
BlocProvider<PersonalDietSuggestionCubit>.value(
|
||||
value: cubit,
|
||||
child: wrap(
|
||||
ConsultationWidget(
|
||||
consultationModel: consultation,
|
||||
dietName: 'Test Diet',
|
||||
dietDuration: 7,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final s = S.of(tester.element(find.byType(ConsultationWidget)));
|
||||
expect(
|
||||
find.text(
|
||||
s.personal_diet_duration_mismatch(
|
||||
7,
|
||||
getDayForm(7, s),
|
||||
14,
|
||||
getDayForm(14, s),
|
||||
),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
final button = tester.widget<OutlinedButton>(find.byType(OutlinedButton));
|
||||
expect(button.onPressed, isNull);
|
||||
expect(
|
||||
button.style?.backgroundColor?.resolve({WidgetState.disabled}),
|
||||
appTheme.dividerColor,
|
||||
);
|
||||
expect(
|
||||
tester.widget<Text>(find.text(s.suggestDiet)).style?.color,
|
||||
appTheme.gray,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'package:eatvio_app/core/app_config.dart';
|
||||
import 'package:eatvio_app/core/app_initializer.dart';
|
||||
import 'package:eatvio_app/core/locator_service.dart';
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/core/utils/localization_utils.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';
|
||||
import 'package:eatvio_app/features/personal_diet_suggestion/presentation/personal_diet_suggestion_screen.dart';
|
||||
@@ -84,5 +85,31 @@ void main() {
|
||||
|
||||
expect(find.textContaining('Test Diet Name'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('shows diet duration hint and empty state', (tester) async {
|
||||
final cubit = MockPersonalDietSuggestionCubit();
|
||||
const dietDuration = 7;
|
||||
final state = PersonalDietSuggestionState(
|
||||
isLoading: false,
|
||||
dietName: 'Test Diet',
|
||||
dietDuration: dietDuration,
|
||||
consultationsWithDiet: [],
|
||||
consultationsWithoutDiet: [],
|
||||
);
|
||||
|
||||
when(cubit.state).thenReturn(state);
|
||||
when(cubit.stream).thenAnswer((_) => Stream.value(state));
|
||||
when(cubit.close()).thenAnswer((_) async => Future<void>.value());
|
||||
|
||||
await tester.pumpWidget(wrap(const PersonalDietSuggestionScreenContent(), cubit));
|
||||
await tester.pump();
|
||||
|
||||
final s = S.of(tester.element(find.byType(PersonalDietSuggestionScreenContent)));
|
||||
expect(
|
||||
find.text(s.personal_diet_duration_hint(dietDuration, getDayForm(dietDuration, s))),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.text(s.no_active_personal_diet_consultations), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -68,41 +68,33 @@ void main() {
|
||||
test('attachPersonalDiet - успешное прикрепление диеты', () async {
|
||||
const consultationId = 1;
|
||||
const dietId = 2;
|
||||
final body = {'diet_id': dietId};
|
||||
|
||||
when(mockService.attachPersonalDiet(
|
||||
consultationId: consultationId,
|
||||
dietId: dietId,
|
||||
)).thenAnswer((_) async => {});
|
||||
when(mockService.attachPersonalDiet(consultationId, body))
|
||||
.thenAnswer((_) async => {});
|
||||
|
||||
await repository.attachPersonalDiet(
|
||||
consultationId: consultationId,
|
||||
dietId: dietId,
|
||||
);
|
||||
|
||||
verify(mockService.attachPersonalDiet(
|
||||
consultationId: consultationId,
|
||||
dietId: dietId,
|
||||
)).called(1);
|
||||
verify(mockService.attachPersonalDiet(consultationId, body)).called(1);
|
||||
});
|
||||
|
||||
test('reattachPersonalDiet - успешное переприкрепление диеты', () async {
|
||||
const consultationId = 1;
|
||||
const dietId = 2;
|
||||
final body = {'diet_id': dietId};
|
||||
|
||||
when(mockService.reattachPersonalDiet(
|
||||
consultationId: consultationId,
|
||||
dietId: dietId,
|
||||
)).thenAnswer((_) async => {});
|
||||
when(mockService.reattachPersonalDiet(consultationId, body))
|
||||
.thenAnswer((_) async => {});
|
||||
|
||||
await repository.reattachPersonalDiet(
|
||||
consultationId: consultationId,
|
||||
dietId: dietId,
|
||||
);
|
||||
|
||||
verify(mockService.reattachPersonalDiet(
|
||||
consultationId: consultationId,
|
||||
dietId: dietId,
|
||||
)).called(1);
|
||||
verify(mockService.reattachPersonalDiet(consultationId, body)).called(1);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -15,55 +15,48 @@ void main() {
|
||||
|
||||
setUp(() {
|
||||
mockDio = MockDio();
|
||||
when(mockDio.options).thenReturn(BaseOptions(baseUrl: 'http://localhost'));
|
||||
service = PersonalDietSuggestionService(mockDio);
|
||||
});
|
||||
|
||||
test('getConsultationWithPersonalDiets - успешное получение консультаций', () async {
|
||||
final mockData = {
|
||||
'data': [],
|
||||
'links': {},
|
||||
'meta': {
|
||||
'current_page': 1,
|
||||
'last_page': 1,
|
||||
'total': 0,
|
||||
'per_page': 10,
|
||||
},
|
||||
};
|
||||
late RequestOptions capturedRequest;
|
||||
|
||||
when(mockDio.get(
|
||||
'/api/consultations',
|
||||
queryParameters: anyNamed('queryParameters'),
|
||||
)).thenAnswer((_) async => Response(
|
||||
requestOptions: RequestOptions(path: '/api/consultations'),
|
||||
statusCode: 200,
|
||||
data: mockData,
|
||||
));
|
||||
when(mockDio.fetch<Map<String, dynamic>>(any)).thenAnswer((invocation) async {
|
||||
capturedRequest = invocation.positionalArguments.first as RequestOptions;
|
||||
return Response<Map<String, dynamic>>(
|
||||
requestOptions: capturedRequest,
|
||||
statusCode: 200,
|
||||
data: mockData,
|
||||
);
|
||||
});
|
||||
|
||||
final result = await service.getConsultationWithPersonalDiets();
|
||||
|
||||
expect(result, isA<ConsultationPaginationModel>());
|
||||
verify(mockDio.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',
|
||||
},
|
||||
)).called(1);
|
||||
expect(capturedRequest.path, '/api/consultations');
|
||||
expect(capturedRequest.method, 'GET');
|
||||
expect(capturedRequest.queryParameters, {
|
||||
r'filters[plan][has_personal_diet][$personal_diet]': '1',
|
||||
r'filters[last_state][$notIn][]': [
|
||||
'done',
|
||||
'charge_was_collected',
|
||||
'complained',
|
||||
'last_day_finished',
|
||||
'last_day_started',
|
||||
'canceled_by_the_initiator',
|
||||
'inited',
|
||||
],
|
||||
r'sort[]': ['start_date:desc'],
|
||||
});
|
||||
verify(mockDio.fetch<Map<String, dynamic>>(any)).called(1);
|
||||
});
|
||||
|
||||
test('getConsultationWithPersonalDiets - пробрасывает ошибку', () async {
|
||||
when(mockDio.get(
|
||||
any,
|
||||
queryParameters: anyNamed('queryParameters'),
|
||||
)).thenThrow(DioException(
|
||||
when(mockDio.fetch<Map<String, dynamic>>(any)).thenThrow(DioException(
|
||||
requestOptions: RequestOptions(path: '/api/consultations'),
|
||||
));
|
||||
|
||||
@@ -75,74 +68,70 @@ void main() {
|
||||
|
||||
test('attachPersonalDiet - успешное прикрепление диеты', () async {
|
||||
const consultationId = 1;
|
||||
const dietId = 2;
|
||||
final body = {'diet_id': 2};
|
||||
late RequestOptions capturedRequest;
|
||||
|
||||
when(mockDio.post(
|
||||
'/api/chosen_plans/$consultationId/attach_diet',
|
||||
data: anyNamed('data'),
|
||||
)).thenAnswer((_) async => Response(
|
||||
requestOptions: RequestOptions(path: '/api/chosen_plans/$consultationId/attach_diet'),
|
||||
statusCode: 200,
|
||||
));
|
||||
when(mockDio.fetch<void>(any)).thenAnswer((invocation) async {
|
||||
capturedRequest = invocation.positionalArguments.first as RequestOptions;
|
||||
return Response<void>(
|
||||
requestOptions: capturedRequest,
|
||||
statusCode: 200,
|
||||
);
|
||||
});
|
||||
|
||||
await service.attachPersonalDiet(consultationId: consultationId, dietId: dietId);
|
||||
await service.attachPersonalDiet(consultationId, body);
|
||||
|
||||
verify(mockDio.post(
|
||||
'/api/chosen_plans/$consultationId/attach_diet',
|
||||
data: {'diet_id': dietId},
|
||||
)).called(1);
|
||||
expect(capturedRequest.path, '/api/chosen_plans/$consultationId/attach_diet');
|
||||
expect(capturedRequest.method, 'POST');
|
||||
expect(capturedRequest.data, body);
|
||||
verify(mockDio.fetch<void>(any)).called(1);
|
||||
});
|
||||
|
||||
test('attachPersonalDiet - пробрасывает ошибку', () async {
|
||||
const consultationId = 1;
|
||||
const dietId = 2;
|
||||
final body = {'diet_id': 2};
|
||||
|
||||
when(mockDio.post(
|
||||
any,
|
||||
data: anyNamed('data'),
|
||||
)).thenThrow(DioException(
|
||||
when(mockDio.fetch<void>(any)).thenThrow(DioException(
|
||||
requestOptions: RequestOptions(path: '/api/chosen_plans/$consultationId/attach_diet'),
|
||||
));
|
||||
|
||||
expect(
|
||||
() => service.attachPersonalDiet(consultationId: consultationId, dietId: dietId),
|
||||
() => service.attachPersonalDiet(consultationId, body),
|
||||
throwsA(isA<DioException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('reattachPersonalDiet - успешное повторное прикрепление диеты', () async {
|
||||
const consultationId = 1;
|
||||
const dietId = 3;
|
||||
final body = {'diet_id': 3};
|
||||
late RequestOptions capturedRequest;
|
||||
|
||||
when(mockDio.post(
|
||||
'/api/chosen_plans/$consultationId/re_attach_diet',
|
||||
data: anyNamed('data'),
|
||||
)).thenAnswer((_) async => Response(
|
||||
requestOptions: RequestOptions(path: '/api/chosen_plans/$consultationId/re_attach_diet'),
|
||||
statusCode: 200,
|
||||
));
|
||||
when(mockDio.fetch<void>(any)).thenAnswer((invocation) async {
|
||||
capturedRequest = invocation.positionalArguments.first as RequestOptions;
|
||||
return Response<void>(
|
||||
requestOptions: capturedRequest,
|
||||
statusCode: 200,
|
||||
);
|
||||
});
|
||||
|
||||
await service.reattachPersonalDiet(consultationId: consultationId, dietId: dietId);
|
||||
await service.reattachPersonalDiet(consultationId, body);
|
||||
|
||||
verify(mockDio.post(
|
||||
'/api/chosen_plans/$consultationId/re_attach_diet',
|
||||
data: {'diet_id': dietId},
|
||||
)).called(1);
|
||||
expect(capturedRequest.path, '/api/chosen_plans/$consultationId/re_attach_diet');
|
||||
expect(capturedRequest.method, 'POST');
|
||||
expect(capturedRequest.data, body);
|
||||
verify(mockDio.fetch<void>(any)).called(1);
|
||||
});
|
||||
|
||||
test('reattachPersonalDiet - пробрасывает ошибку', () async {
|
||||
const consultationId = 1;
|
||||
const dietId = 3;
|
||||
final body = {'diet_id': 3};
|
||||
|
||||
when(mockDio.post(
|
||||
any,
|
||||
data: anyNamed('data'),
|
||||
)).thenThrow(DioException(
|
||||
when(mockDio.fetch<void>(any)).thenThrow(DioException(
|
||||
requestOptions: RequestOptions(path: '/api/chosen_plans/$consultationId/re_attach_diet'),
|
||||
));
|
||||
|
||||
expect(
|
||||
() => service.reattachPersonalDiet(consultationId: consultationId, dietId: dietId),
|
||||
() => service.reattachPersonalDiet(consultationId, body),
|
||||
throwsA(isA<DioException>()),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -61,6 +61,47 @@ void main() {
|
||||
expect(ChosenPlanStateEnum.stateConfirmedByConsultant.isStateAfterPaidState(), isTrue);
|
||||
});
|
||||
|
||||
test('canShowCancelAction returns true for cancellable states', () {
|
||||
expect(ChosenPlanStateEnum.stateInited.canShowCancelAction, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateInCoordination.canShowCancelAction, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateStartDateHasBeenSet.canShowCancelAction, isTrue);
|
||||
expect(ChosenPlanStateEnum.statePendingPayment.canShowCancelAction, isTrue);
|
||||
expect(ChosenPlanStateEnum.statePaid.canShowCancelAction, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateStarted.canShowCancelAction, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateInProgress.canShowCancelAction, isTrue);
|
||||
});
|
||||
|
||||
test('canShowCancelAction returns false for non-cancellable states', () {
|
||||
expect(ChosenPlanStateEnum.personalDietSet.canShowCancelAction, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateLastDayStarted.canShowCancelAction, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateLastDayFinished.canShowCancelAction, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateComplained.canShowCancelAction, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateDone.canShowCancelAction, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateChargeWasCollected.canShowCancelAction, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateCanceledByTheInitiator.canShowCancelAction, isFalse);
|
||||
expect(ChosenPlanStateEnum.statePaymentFailed.canShowCancelAction, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateConfirmedByConsultant.canShowCancelAction, isFalse);
|
||||
});
|
||||
|
||||
test('isCancelAfterPaidState returns true only for post-paid cancellable states', () {
|
||||
expect(ChosenPlanStateEnum.statePaid.isCancelAfterPaidState, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateStarted.isCancelAfterPaidState, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateInProgress.isCancelAfterPaidState, isTrue);
|
||||
expect(ChosenPlanStateEnum.stateInited.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateInCoordination.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateStartDateHasBeenSet.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.statePendingPayment.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.statePaymentFailed.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateConfirmedByConsultant.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.personalDietSet.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateLastDayStarted.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateLastDayFinished.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateComplained.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateDone.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateChargeWasCollected.isCancelAfterPaidState, isFalse);
|
||||
expect(ChosenPlanStateEnum.stateCanceledByTheInitiator.isCancelAfterPaidState, isFalse);
|
||||
});
|
||||
|
||||
test('getActiveStates returns correct states', () {
|
||||
final activeStates = ChosenPlanStateEnum.getActiveStates();
|
||||
|
||||
|
||||
@@ -60,6 +60,7 @@ void main() {
|
||||
'last_state': 'initied',
|
||||
'chat_id': 'chat-1',
|
||||
'consultant_id': 1,
|
||||
'personal_diet_name': 'Индивидуальный план питания',
|
||||
'plan': {
|
||||
'id': 1,
|
||||
'slug': 'test-plan',
|
||||
@@ -94,6 +95,7 @@ void main() {
|
||||
expect(chosenPlan.optionType, 'options1');
|
||||
expect(chosenPlan.chosenPlanState, ChosenPlanStateEnum.stateInited);
|
||||
expect(chosenPlan.chatId, 'chat-1');
|
||||
expect(chosenPlan.personalDietName, 'Индивидуальный план питания');
|
||||
});
|
||||
|
||||
test('toJson serializes ChosenPlanModel correctly', () {
|
||||
@@ -198,6 +200,66 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
group('chosenOption', () {
|
||||
const plan = 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,
|
||||
packet1Options: PacketOptions(items: ['one'], price: 100, short: 'packet-1', hasPersonalDiet: false),
|
||||
packet2Options: PacketOptions(items: ['two'], price: 200, short: 'packet-2', hasPersonalDiet: true),
|
||||
packet3Options: PacketOptions(items: ['three'], price: 300, short: 'packet-3', hasPersonalDiet: false),
|
||||
author: Author(
|
||||
authorSlug: 'author',
|
||||
authorName: 'Author Name',
|
||||
authorProfileIcon: 'https://example.com/icon.jpg',
|
||||
authorIsMe: false,
|
||||
isEntitySubscribedByMe: null,
|
||||
authorPlaceInRating: null,
|
||||
),
|
||||
totalLikes: 10,
|
||||
totalViews: 100,
|
||||
totalComments: 5,
|
||||
isFavorite: false,
|
||||
minPriceOfOptions: 100,
|
||||
maxPriceOfOptions: 300,
|
||||
wasLikedByMe: false,
|
||||
);
|
||||
|
||||
ChosenPlanModel modelWith(String optionType) => ChosenPlanModel(
|
||||
id: 1,
|
||||
optionType: optionType,
|
||||
startDate: DateTime(2024, 1, 1),
|
||||
chosenPlanState: ChosenPlanStateEnum.stateInited,
|
||||
chatId: 'chat-1',
|
||||
consultantId: 1,
|
||||
plan: plan,
|
||||
);
|
||||
|
||||
test('возвращает первую опцию для options1', () {
|
||||
expect(modelWith('options1').chosenOption?.short, 'packet-1');
|
||||
});
|
||||
|
||||
test('возвращает вторую опцию для options2', () {
|
||||
expect(modelWith('options2').chosenOption?.short, 'packet-2');
|
||||
});
|
||||
|
||||
test('возвращает третью опцию для options3', () {
|
||||
expect(modelWith('options3').chosenOption?.short, 'packet-3');
|
||||
});
|
||||
|
||||
test('возвращает null для неизвестного значения', () {
|
||||
expect(modelWith('unknown').chosenOption, isNull);
|
||||
expect(modelWith('1').chosenOption, isNull);
|
||||
expect(modelWith('').chosenOption, isNull);
|
||||
});
|
||||
});
|
||||
|
||||
group('parseChosenPlan', () {
|
||||
test('parseChosenPlan создает ChosenPlanModel из Map', () {
|
||||
final json = {
|
||||
@@ -207,6 +269,7 @@ void main() {
|
||||
'last_state': 'initied',
|
||||
'chat_id': 'chat-1',
|
||||
'consultant_id': 1,
|
||||
'personal_diet_name': 'Индивидуальный план питания',
|
||||
'plan': {
|
||||
'id': 1,
|
||||
'slug': 'test-plan',
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
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:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
group('VideoCallRecordingsPagination', () {
|
||||
test('parses fixture with ready and in_progress items', () {
|
||||
final json = jsonDecode(
|
||||
File('test/fixtures/video_call_recordings/recordings_page.json').readAsStringSync(),
|
||||
) as Map<String, dynamic>;
|
||||
|
||||
final page = VideoCallRecordingsPagination.fromJson(json);
|
||||
|
||||
expect(page.data, hasLength(2));
|
||||
expect(page.meta.currentPage, 1);
|
||||
expect(page.meta.lastPage, 1);
|
||||
expect(page.meta.perPage, 20);
|
||||
|
||||
final ready = page.data.first;
|
||||
expect(ready.id, 123);
|
||||
expect(ready.isReady, isTrue);
|
||||
expect(ready.durationSeconds, 187);
|
||||
expect(ready.fileUrl, isNotNull);
|
||||
expect(ready.counterpart?.name, 'Иван Петров');
|
||||
expect(ready.counterpart?.slug, 'ivan-petrov');
|
||||
|
||||
final processing = page.data.last;
|
||||
expect(processing.isInProgress, isTrue);
|
||||
expect(processing.durationSeconds, isNull);
|
||||
expect(processing.fileUrl, isNull);
|
||||
expect(processing.counterpart, isNull);
|
||||
expect(processing.previewUrl, contains('placeholder'));
|
||||
});
|
||||
});
|
||||
|
||||
group('formatRecordingDuration', () {
|
||||
test('formats seconds and hours', () {
|
||||
expect(formatRecordingDuration(null), '');
|
||||
expect(formatRecordingDuration(5), '00:05');
|
||||
expect(formatRecordingDuration(187), '03:07');
|
||||
expect(formatRecordingDuration(3661), '1:01:01');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import 'package:eatvio_app/core/models/pagination_model.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/recordings/presentation/cubit/video_call_recordings_cubit.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/repositories/video_call_recordings_repository.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mocktail/mocktail.dart';
|
||||
|
||||
class _MockRecordingsRepository extends Mock implements VideoCallRecordingsRepository {}
|
||||
|
||||
void main() {
|
||||
late _MockRecordingsRepository repository;
|
||||
late VideoCallRecordingsCubit cubit;
|
||||
|
||||
VideoCallRecordingsPagination page({
|
||||
required int currentPage,
|
||||
required int lastPage,
|
||||
required List<VideoCallRecordingModel> data,
|
||||
}) {
|
||||
return VideoCallRecordingsPagination(
|
||||
data: data,
|
||||
links: const Links(
|
||||
first: 'https://example.com?page=1',
|
||||
last: 'https://example.com?page=2',
|
||||
prev: null,
|
||||
next: null,
|
||||
),
|
||||
meta: Meta(
|
||||
currentPage: currentPage,
|
||||
from: 1,
|
||||
lastPage: lastPage,
|
||||
links: const [],
|
||||
perPage: 20,
|
||||
to: data.length,
|
||||
total: data.length,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
VideoCallRecordingModel recording(int id) {
|
||||
return VideoCallRecordingModel(
|
||||
id: id,
|
||||
status: 'ready',
|
||||
createdAt: DateTime.utc(2026, 9, 21, 10),
|
||||
previewUrl: 'https://example.com/preview.jpg',
|
||||
fileUrl: 'https://example.com/api/video-call/recordings/$id/file',
|
||||
);
|
||||
}
|
||||
|
||||
setUp(() {
|
||||
repository = _MockRecordingsRepository();
|
||||
cubit = VideoCallRecordingsCubit(repository: repository);
|
||||
});
|
||||
|
||||
tearDown(() async {
|
||||
await cubit.close();
|
||||
});
|
||||
|
||||
test('load fills recordings', () async {
|
||||
when(
|
||||
() => repository.getRecordings(page: 1, period: null),
|
||||
).thenAnswer(
|
||||
(_) async => page(currentPage: 1, lastPage: 1, data: [recording(1)]),
|
||||
);
|
||||
|
||||
await cubit.load();
|
||||
|
||||
expect(cubit.state.isLoading, isFalse);
|
||||
expect(cubit.state.recordings, hasLength(1));
|
||||
expect(cubit.state.error, isNull);
|
||||
});
|
||||
|
||||
test('setPeriod resets to page 1 and reloads', () async {
|
||||
when(
|
||||
() => repository.getRecordings(page: 1, period: null),
|
||||
).thenAnswer(
|
||||
(_) async => page(currentPage: 1, lastPage: 2, data: [recording(1)]),
|
||||
);
|
||||
when(
|
||||
() => repository.getRecordings(page: 1, period: RecordingPeriod.week),
|
||||
).thenAnswer(
|
||||
(_) async => page(currentPage: 1, lastPage: 1, data: [recording(2)]),
|
||||
);
|
||||
|
||||
await cubit.load();
|
||||
await cubit.setPeriod(RecordingPeriod.week);
|
||||
|
||||
expect(cubit.state.period, RecordingPeriod.week);
|
||||
expect(cubit.state.currentPage, 1);
|
||||
expect(cubit.state.recordings.single.id, 2);
|
||||
verify(() => repository.getRecordings(page: 1, period: RecordingPeriod.week)).called(1);
|
||||
});
|
||||
|
||||
test('loadNextPage appends recordings', () async {
|
||||
when(
|
||||
() => repository.getRecordings(page: 1, period: null),
|
||||
).thenAnswer(
|
||||
(_) async => page(currentPage: 1, lastPage: 2, data: [recording(1)]),
|
||||
);
|
||||
when(
|
||||
() => repository.getRecordings(page: 2, period: null),
|
||||
).thenAnswer(
|
||||
(_) async => page(currentPage: 2, lastPage: 2, data: [recording(2)]),
|
||||
);
|
||||
|
||||
await cubit.load();
|
||||
await cubit.loadNextPage();
|
||||
|
||||
expect(cubit.state.recordings.map((e) => e.id), [1, 2]);
|
||||
expect(cubit.state.currentPage, 2);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import 'package:eatvio_app/core/theme/theme_helper.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/models/video_call_recording_model.dart';
|
||||
import 'package:eatvio_app/features/video_calls/recordings/presentation/widgets/recording_card.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';
|
||||
import 'package:network_image_mock/network_image_mock.dart';
|
||||
|
||||
void main() {
|
||||
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: child),
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('ready card shows download and play', (tester) async {
|
||||
await mockNetworkImagesFor(() async {
|
||||
final recording = VideoCallRecordingModel(
|
||||
id: 1,
|
||||
status: 'ready',
|
||||
durationSeconds: 125,
|
||||
createdAt: DateTime.utc(2026, 5, 12, 14),
|
||||
previewUrl: 'https://example.com/preview.jpg',
|
||||
fileUrl: 'https://example.com/file',
|
||||
counterpart: const VideoCallRecordingCounterpartModel(
|
||||
name: 'Сидни',
|
||||
slug: 'sydney',
|
||||
profilePhotoUrl: 'https://example.com/a.jpg',
|
||||
),
|
||||
);
|
||||
|
||||
var played = false;
|
||||
var downloaded = false;
|
||||
|
||||
await tester.pumpWidget(
|
||||
wrap(
|
||||
RecordingCard(
|
||||
recording: recording,
|
||||
onPlay: () => played = true,
|
||||
onDownload: () => downloaded = true,
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Скачать'), findsOneWidget);
|
||||
expect(find.text('02:05'), findsOneWidget);
|
||||
expect(find.textContaining('обрабатывается'), findsNothing);
|
||||
|
||||
await tester.tap(find.byIcon(Icons.play_arrow));
|
||||
await tester.tap(find.text('Скачать'));
|
||||
expect(played, isTrue);
|
||||
expect(downloaded, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('in_progress card hides download and play', (tester) async {
|
||||
await mockNetworkImagesFor(() async {
|
||||
final recording = VideoCallRecordingModel(
|
||||
id: 2,
|
||||
status: 'in_progress',
|
||||
createdAt: DateTime.utc(2026, 5, 12, 14),
|
||||
previewUrl: 'https://example.com/placeholder.png',
|
||||
);
|
||||
|
||||
await tester.pumpWidget(
|
||||
wrap(
|
||||
RecordingCard(
|
||||
recording: recording,
|
||||
onPlay: () {},
|
||||
onDownload: () {},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
|
||||
expect(find.textContaining('обрабатывается'), findsOneWidget);
|
||||
expect(find.text('Скачать'), findsNothing);
|
||||
expect(find.byIcon(Icons.play_arrow), findsNothing);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
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/repositories/video_call_recordings_repository.dart';
|
||||
import 'package:eatvio_app/features/video_calls/services/video_call_service.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mocktail/mocktail.dart';
|
||||
|
||||
class _MockVideoCallService extends Mock implements VideoCallService {}
|
||||
|
||||
class _MockDio extends Mock implements Dio {}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUpAll(() {
|
||||
registerFallbackValue('');
|
||||
registerFallbackValue(Options());
|
||||
|
||||
const MethodChannel pathProviderChannel =
|
||||
MethodChannel('plugins.flutter.io/path_provider');
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(pathProviderChannel, (call) async {
|
||||
if (call.method == 'getTemporaryDirectory') {
|
||||
return '/tmp';
|
||||
}
|
||||
return null;
|
||||
});
|
||||
});
|
||||
|
||||
late _MockVideoCallService service;
|
||||
late _MockDio dio;
|
||||
late VideoCallRecordingsRepository repository;
|
||||
|
||||
setUp(() {
|
||||
service = _MockVideoCallService();
|
||||
dio = _MockDio();
|
||||
repository = VideoCallRecordingsRepository(
|
||||
videoCallService: service,
|
||||
dio: dio,
|
||||
);
|
||||
});
|
||||
|
||||
test('downloadRecordingFile maps 409 to RecordingNotReadyException', () async {
|
||||
when(
|
||||
() => dio.download(
|
||||
any(),
|
||||
any(),
|
||||
options: any(named: 'options'),
|
||||
),
|
||||
).thenThrow(
|
||||
DioException(
|
||||
requestOptions: RequestOptions(path: '/file'),
|
||||
response: Response(
|
||||
requestOptions: RequestOptions(path: '/file'),
|
||||
statusCode: 409,
|
||||
data: {
|
||||
'message': 'Not ready',
|
||||
'code': RecordingNotReadyException.code,
|
||||
},
|
||||
),
|
||||
type: DioExceptionType.badResponse,
|
||||
),
|
||||
);
|
||||
|
||||
await expectLater(
|
||||
repository.downloadRecordingFile(
|
||||
fileUrl: 'https://example.com/api/video-call/recordings/1/file',
|
||||
recordingId: 1,
|
||||
),
|
||||
throwsA(isA<RecordingNotReadyException>()),
|
||||
);
|
||||
});
|
||||
}
|
||||
2
test/fixtures/doubles/profile_doubles.dart
vendored
2
test/fixtures/doubles/profile_doubles.dart
vendored
@@ -69,7 +69,7 @@ class FixtureChatRepository extends ChatRepository {
|
||||
: super(chatService: _NoopChatService());
|
||||
|
||||
@override
|
||||
Future<String> getChatByUserSlug(String slug) async {
|
||||
Future<String?> getChatByUserSlug(String slug) async {
|
||||
return 'chat-uuid-123';
|
||||
}
|
||||
}
|
||||
|
||||
44
test/fixtures/video_call_recordings/recordings_page.json
vendored
Normal file
44
test/fixtures/video_call_recordings/recordings_page.json
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"id": 123,
|
||||
"status": "ready",
|
||||
"duration_seconds": 187,
|
||||
"size_bytes": 15728640,
|
||||
"created_at": "2026-09-21T10:00:00.000000Z",
|
||||
"preview_url": "https://example.com/storage/recordings/123/preview.jpg",
|
||||
"file_url": "https://example.com/api/video-call/recordings/123/file",
|
||||
"counterpart": {
|
||||
"name": "Иван Петров",
|
||||
"slug": "ivan-petrov",
|
||||
"profile_photo_url": "https://example.com/storage/users/ivan.jpg"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 122,
|
||||
"status": "in_progress",
|
||||
"duration_seconds": null,
|
||||
"size_bytes": null,
|
||||
"created_at": "2026-09-21T09:00:00.000000Z",
|
||||
"preview_url": "https://example.com/images/element-image-placeholder.png",
|
||||
"file_url": null,
|
||||
"counterpart": null
|
||||
}
|
||||
],
|
||||
"links": {
|
||||
"first": "https://example.com/api/video-call/recordings?page=1",
|
||||
"last": "https://example.com/api/video-call/recordings?page=1",
|
||||
"prev": null,
|
||||
"next": null
|
||||
},
|
||||
"meta": {
|
||||
"current_page": 1,
|
||||
"from": 1,
|
||||
"last_page": 1,
|
||||
"links": [],
|
||||
"path": "https://example.com/api/video-call/recordings",
|
||||
"per_page": 20,
|
||||
"to": 2,
|
||||
"total": 2
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user