diff --git a/lib/features/settings/models/oauth_account_model.dart b/lib/features/settings/models/oauth_account_model.dart new file mode 100644 index 00000000..27942119 --- /dev/null +++ b/lib/features/settings/models/oauth_account_model.dart @@ -0,0 +1,44 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'oauth_account_model.freezed.dart'; +part 'oauth_account_model.g.dart'; + +@freezed +abstract class OAuthAccountModel with _$OAuthAccountModel { + const factory OAuthAccountModel({ + @JsonKey(name: 'oauth_id') required String oauthId, + required String name, + required String email, + required String phone, + @JsonKey(name: 'linked_at') required DateTime linkedAt, + }) = _OAuthAccountModel; + + factory OAuthAccountModel.fromJson(Map json) => _$OAuthAccountModelFromJson(json); +} + +@freezed +abstract class OAuthAccountsResponseModel with _$OAuthAccountsResponseModel { + const factory OAuthAccountsResponseModel({required bool success, required OAuthAccountsDataModel data}) = _OAuthAccountsResponseModel; + + factory OAuthAccountsResponseModel.fromJson(Map json) => _$OAuthAccountsResponseModelFromJson(json); +} + +@freezed +abstract class OAuthAccountsDataModel with _$OAuthAccountsDataModel { + const factory OAuthAccountsDataModel({ + @JsonKey(fromJson: _oauthAccountFromJson) OAuthAccountModel? vk, + @JsonKey(fromJson: _oauthAccountFromJson) OAuthAccountModel? yandex, + }) = _OAuthAccountsDataModel; + + factory OAuthAccountsDataModel.fromJson(Map json) => _$OAuthAccountsDataModelFromJson(json); +} + +// Custom converter to handle both empty array [] and object +OAuthAccountModel? _oauthAccountFromJson(dynamic json) { + if (json == null) return null; + if (json is List && json.isEmpty) return null; + if (json is Map) { + return OAuthAccountModel.fromJson(json); + } + return null; +} diff --git a/lib/features/settings/models/oauth_attach_request.dart b/lib/features/settings/models/oauth_attach_request.dart new file mode 100644 index 00000000..600fb320 --- /dev/null +++ b/lib/features/settings/models/oauth_attach_request.dart @@ -0,0 +1,17 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'oauth_attach_request.freezed.dart'; +part 'oauth_attach_request.g.dart'; + +@freezed +abstract class OAuthAttachRequest with _$OAuthAttachRequest { + const factory OAuthAttachRequest({ + required String provider, + @JsonKey(name: 'client_id') String? clientId, + @JsonKey(name: 'access_token') required String accessToken, + @JsonKey(name: 'refresh_token') required String refreshToken, + }) = _OAuthAttachRequest; + + factory OAuthAttachRequest.fromJson(Map json) => _$OAuthAttachRequestFromJson(json); +} + diff --git a/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart b/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart index 2a64e2e9..ed123203 100644 --- a/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart +++ b/lib/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart @@ -4,6 +4,8 @@ import 'package:eatvio_app/features/consultations/repositories/consultations_rep import 'package:eatvio_app/features/plans/enums/chosen_plan_state_enum.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; import 'package:eatvio_app/features/profile/repositories/profile_repository.dart'; +import 'package:eatvio_app/features/settings/models/oauth_account_model.dart'; +import 'package:eatvio_app/features/settings/models/oauth_attach_request.dart'; import 'package:eatvio_app/features/settings/models/profile_settings_model.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_state.dart'; import 'package:eatvio_app/features/settings/repositories/service_repository.dart'; @@ -26,6 +28,7 @@ class SettingsCubit extends Cubit { final profile = await profileRepository.getMyProfile(); late final ConsultationRequestModel? consultantInfo; late final bool hasActiveConsultation; + late final OAuthAccountsDataModel? oauthAccounts; try { if (profile.phoneConfirmationState.contains('confirmed')) { @@ -43,6 +46,13 @@ class SettingsCubit extends Cubit { hasActiveConsultation = false; } + try { + final oauthResponse = await settingsRepository.getOAuthAccounts(); + oauthAccounts = oauthResponse.data; + } catch (e) { + oauthAccounts = null; + } + try { emit( SettingsState.loaded( @@ -51,6 +61,7 @@ class SettingsCubit extends Cubit { profile: profile, consultationRequestModel: consultantInfo, hasActiveConsultation: hasActiveConsultation, + oauthAccounts: oauthAccounts, ), ); } catch (e) { @@ -87,6 +98,35 @@ class SettingsCubit extends Cubit { } } + Future linkOAuthAccount({ + required String provider, + required String accessToken, + required String refreshToken, + String? clientId, + }) async { + try { + final request = OAuthAttachRequest( + provider: provider, + clientId: clientId, + accessToken: accessToken, + refreshToken: refreshToken, + ); + await settingsRepository.linkOAuthAccount(request: request); + await init(); + } catch (e) { + rethrow; + } + } + + Future unlinkOAuthAccount({required String provider}) async { + try { + await settingsRepository.unlinkOAuthAccount(provider: provider); + await init(); + } catch (e) { + rethrow; + } + } + Future _checkActiveConsultation() async { try { final userPurchases = await consultationsRepository.getUserPurchases(null, null); diff --git a/lib/features/settings/presentation/bloc/settings_cubit/settings_state.dart b/lib/features/settings/presentation/bloc/settings_cubit/settings_state.dart index 86471f31..b8746dd9 100644 --- a/lib/features/settings/presentation/bloc/settings_cubit/settings_state.dart +++ b/lib/features/settings/presentation/bloc/settings_cubit/settings_state.dart @@ -1,5 +1,6 @@ import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/settings/models/oauth_account_model.dart'; import 'package:eatvio_app/features/settings/models/profile_settings_model.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; @@ -17,6 +18,7 @@ abstract class SettingsState with _$SettingsState { required ProfileModel profile, ConsultationRequestModel? consultationRequestModel, required bool hasActiveConsultation, + OAuthAccountsDataModel? oauthAccounts, }) = SettingsStateLoaded; const factory SettingsState.error({ diff --git a/lib/features/settings/presentation/pages/settings_screen.dart b/lib/features/settings/presentation/pages/settings_screen.dart index ad42a7b4..af34ed38 100644 --- a/lib/features/settings/presentation/pages/settings_screen.dart +++ b/lib/features/settings/presentation/pages/settings_screen.dart @@ -6,6 +6,7 @@ import 'package:eatvio_app/core/widgets/custom_outlined_button.dart'; import 'package:eatvio_app/core/widgets/data_error_widget.dart'; import 'package:eatvio_app/core/widgets/loader.dart'; import 'package:eatvio_app/core/widgets/show_error_dialog.dart'; +import 'package:eatvio_app/features/auth/sdk/social_auth_facade.dart'; import 'package:eatvio_app/features/consultant/become_consultant/models/consultation_request_model.dart'; import 'package:eatvio_app/features/settings/entities/settings_entity.dart'; import 'package:eatvio_app/features/settings/presentation/bloc/settings_cubit/settings_cubit.dart'; @@ -16,6 +17,7 @@ import 'package:eatvio_app/generated/l10n.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_svg/flutter_svg.dart'; import 'package:go_router/go_router.dart'; class SettingsScreen extends StatefulWidget { @@ -39,12 +41,7 @@ class _SettingsScreenState extends State { return AlertDialog( title: const Text('Предупреждение'), content: const Text('Во время консультации этот параметр нельзя отключить'), - actions: [ - TextButton( - onPressed: () => Navigator.of(context).pop(), - child: const Text('Понятно'), - ), - ], + actions: [TextButton(onPressed: () => Navigator.of(context).pop(), child: const Text('Понятно'))], ); }, ); @@ -80,6 +77,7 @@ class _SettingsScreenState extends State { const SizedBox(height: 12), _becomeConsultantButton(state), _deleteAccountButton(state, settingsCubit), + _oauthAccounts(state, settingsCubit), ], ), ), @@ -328,6 +326,326 @@ class _SettingsScreenState extends State { ), ); } + + Widget _oauthAccounts(SettingsStateLoaded state, SettingsCubit settingsCubit) { + final isVkLinked = state.oauthAccounts?.vk != null; + final isYandexLinked = state.oauthAccounts?.yandex != null; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Padding( + padding: EdgeInsets.symmetric(horizontal: 16), + child: Text( + 'Привязанные аккаунты', + style: TextStyle(fontSize: 16, height: 1, color: Colors.grey, fontFamily: 'Mulish'), + ), + ), + const SizedBox(height: 12), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + _OAuthAccountButton( + onTap: () => _onVkPressed(state, settingsCubit), + backgroundColor: const Color(0xFF2787F5), + tooltip: 'VK ID', + icon: SvgPicture.asset('assets/icons/vk_logo.svg', height: 24, width: 24), + isLinked: isVkLinked, + accountName: state.oauthAccounts?.vk?.name, + ), + const SizedBox(width: 12), + _OAuthAccountButton( + onTap: () => _onOkPressed(state, settingsCubit), + backgroundColor: const Color(0xFFF58220), + tooltip: 'Одноклассники', + icon: SvgPicture.asset('assets/icons/ok_logo.svg', height: 24, width: 24), + isLinked: isVkLinked, + accountName: state.oauthAccounts?.vk?.name, + ), + const SizedBox(width: 12), + _OAuthAccountButton( + onTap: () => _onMailRuPressed(state, settingsCubit), + backgroundColor: const Color(0xFF005FF9), + tooltip: 'Mail.ru', + icon: SvgPicture.asset('assets/icons/mail_logo.svg', height: 24, width: 24), + isLinked: isVkLinked, + accountName: state.oauthAccounts?.vk?.name, + ), + const SizedBox(width: 12), + _OAuthAccountButton( + onTap: () => _onYandexPressed(state, settingsCubit), + backgroundColor: const Color(0xFFFFCC00), + tooltip: 'Яндекс ID', + icon: SvgPicture.asset('assets/icons/yandex_logo.svg', height: 24, width: 24), + isLinked: isYandexLinked, + accountName: state.oauthAccounts?.yandex?.name, + ), + ], + ), + ), + const SizedBox(height: 12), + ], + ); + } + + Future _onVkPressed(SettingsStateLoaded state, SettingsCubit settingsCubit) async { + if (state.oauthAccounts?.vk != null) { + // Отвязываем аккаунт + if (!mounted) return; + final shouldUnlink = await _showUnlinkConfirmationDialog(context, 'VK ID'); + if (shouldUnlink == true) { + try { + await settingsCubit.unlinkOAuthAccount(provider: 'vk'); + } catch (e) { + if (mounted) { + showErrorDialog(context, description: 'Не удалось отвязать аккаунт'); + } + } + } + return; + } + + try { + if (!mounted) return; + + final authResult = await SocialAuthFacade.signInWithVkAndFetchProfile(context: context); + if (authResult == null) return; + + try { + await settingsCubit.linkOAuthAccount( + provider: 'vk', + accessToken: authResult.accessToken, + refreshToken: authResult.refreshToken ?? '', + clientId: authResult.clientId, + ); + } catch (e) { + if (mounted) { + showErrorDialog(context, description: 'Не удалось привязать аккаунт'); + } + } + } catch (e) { + if (mounted) { + showErrorDialog(context, description: 'Не удалось привязать аккаунт'); + } + } + } + + Future _onOkPressed(SettingsStateLoaded state, SettingsCubit settingsCubit) async { + if (state.oauthAccounts?.vk != null) { + // Отвязываем аккаунт (OK использует тот же VK ID провайдер) + if (!mounted) return; + final shouldUnlink = await _showUnlinkConfirmationDialog(context, 'Одноклассники'); + if (shouldUnlink == true) { + try { + await settingsCubit.unlinkOAuthAccount(provider: 'vk'); + } catch (e) { + if (mounted) { + showErrorDialog(context, description: 'Не удалось отвязать аккаунт'); + } + } + } + return; + } + + try { + if (!mounted) return; + + final authResult = await SocialAuthFacade.signInWithOkAndFetchProfile(); + if (authResult == null) return; + + try { + await settingsCubit.linkOAuthAccount( + provider: 'vk', + accessToken: authResult.accessToken, + refreshToken: authResult.refreshToken ?? '', + clientId: authResult.clientId, + ); + } catch (e) { + if (mounted) { + showErrorDialog(context, description: 'Не удалось привязать аккаунт'); + } + } + } catch (e) { + if (mounted) { + showErrorDialog(context, description: 'Не удалось привязать аккаунт'); + } + } + } + + Future _onMailRuPressed(SettingsStateLoaded state, SettingsCubit settingsCubit) async { + if (state.oauthAccounts?.vk != null) { + // Отвязываем аккаунт (Mail.ru использует тот же VK ID провайдер) + if (!mounted) return; + final shouldUnlink = await _showUnlinkConfirmationDialog(context, 'Mail.ru'); + if (shouldUnlink == true) { + try { + await settingsCubit.unlinkOAuthAccount(provider: 'vk'); + } catch (e) { + if (mounted) { + showErrorDialog(context, description: 'Не удалось отвязать аккаунт'); + } + } + } + return; + } + + try { + if (!mounted) return; + + final authResult = await SocialAuthFacade.signInWithMailRuAndFetchProfile(); + if (authResult == null) return; + + try { + await settingsCubit.linkOAuthAccount( + provider: 'vk', + accessToken: authResult.accessToken, + refreshToken: authResult.refreshToken ?? '', + clientId: authResult.clientId, + ); + } catch (e) { + if (mounted) { + showErrorDialog(context, description: 'Не удалось привязать аккаунт'); + } + } + } catch (e) { + if (mounted) { + showErrorDialog(context, description: 'Не удалось привязать аккаунт'); + } + } + } + + Future _onYandexPressed(SettingsStateLoaded state, SettingsCubit settingsCubit) async { + if (state.oauthAccounts?.yandex != null) { + // Отвязываем аккаунт + if (!mounted) return; + final shouldUnlink = await _showUnlinkConfirmationDialog(context, 'Яндекс ID'); + if (shouldUnlink == true) { + try { + await settingsCubit.unlinkOAuthAccount(provider: 'yandex'); + } catch (e) { + if (mounted) { + showErrorDialog(context, description: 'Не удалось отвязать аккаунт'); + } + } + } + return; + } + + try { + if (!mounted) return; + + final authResult = await SocialAuthFacade.signInWithYandex(); + if (authResult == null) { + if (mounted) { + showErrorDialog(context, description: 'Не удалось авторизоваться через Яндекс'); + } + return; + } + + // Проверяем, что refreshToken не пустой для Яндекс + if (authResult.refreshToken == null || authResult.refreshToken!.isEmpty) { + if (mounted) { + showErrorDialog(context, description: 'Не удалось получить токен обновления от Яндекс'); + } + return; + } + + // Проверяем, что clientId не пустой для Яндекс + if (authResult.clientId.isEmpty) { + if (mounted) { + showErrorDialog(context, description: 'Не удалось получить client ID от Яндекс'); + } + return; + } + + try { + await settingsCubit.linkOAuthAccount( + provider: 'yandex', + accessToken: authResult.accessToken, + refreshToken: authResult.refreshToken!, + clientId: authResult.clientId, + ); + } catch (e) { + if (mounted) { + showErrorDialog(context, description: 'Не удалось привязать аккаунт: ${e.toString()}'); + } + } + } catch (e) { + if (mounted) { + showErrorDialog(context, description: 'Не удалось привязать аккаунт: ${e.toString()}'); + } + } + } + + Future _showUnlinkConfirmationDialog(BuildContext context, String providerName) { + return showDialog( + context: context, + builder: (context) => CupertinoAlertDialog( + title: const Text('Отвязать аккаунт'), + content: Text('Вы точно хотите отвязать аккаунт $providerName?'), + actions: [ + CupertinoDialogAction( + onPressed: () { + Navigator.of(context).pop(false); + }, + child: const Text('Отмена'), + ), + CupertinoDialogAction( + onPressed: () { + Navigator.of(context).pop(true); + }, + isDestructiveAction: true, + child: const Text('Отвязать'), + ), + ], + ), + ); + } +} + +class _OAuthAccountButton extends StatelessWidget { + const _OAuthAccountButton({ + required this.onTap, + required this.icon, + required this.backgroundColor, + required this.tooltip, + required this.isLinked, + this.accountName, + }); + + final VoidCallback onTap; + final Widget icon; + final Color backgroundColor; + final String tooltip; + final bool isLinked; + final String? accountName; + + @override + Widget build(BuildContext context) { + return Expanded( + child: Opacity( + opacity: isLinked ? 0.5 : 1.0, + child: Tooltip( + message: tooltip, + child: InkWell( + borderRadius: BorderRadius.circular(20), + onTap: onTap, + child: Ink( + height: 48, + decoration: BoxDecoration( + color: Colors.transparent, + borderRadius: BorderRadius.circular(20), + border: Border.all(color: const Color(0xFFDBDBDB), width: 1), + ), + child: Center(child: icon), + ), + ), + ), + ), + ); + } } class DeleteAccountBottomSheet extends StatefulWidget { diff --git a/lib/features/settings/repositories/service_repository.dart b/lib/features/settings/repositories/service_repository.dart index eb462de3..139ee31e 100644 --- a/lib/features/settings/repositories/service_repository.dart +++ b/lib/features/settings/repositories/service_repository.dart @@ -1,4 +1,6 @@ import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/settings/models/oauth_account_model.dart'; +import 'package:eatvio_app/features/settings/models/oauth_attach_request.dart'; import 'package:eatvio_app/features/settings/models/profile_settings_model.dart'; import 'package:eatvio_app/features/settings/services/settings_service.dart'; @@ -15,25 +17,41 @@ class SettingsRepository { } } - Future updateProfileSettings({ - required ProfileSettingsModel profileSettingsModel, - }) async { + Future updateProfileSettings({required ProfileSettingsModel profileSettingsModel}) async { try { - return await settingsService.updateProfileSettings( - data: profileSettingsModel.toJson(), - ); + return await settingsService.updateProfileSettings(data: profileSettingsModel.toJson()); } catch (e) { rethrow; } } - Future updateProfileDetails({ - required ProfileDetailsModel profileDetailsModel, - }) async { + Future updateProfileDetails({required ProfileDetailsModel profileDetailsModel}) async { try { - return await settingsService.updateProfileDetails( - data: profileDetailsModel.toJson(), - ); + return await settingsService.updateProfileDetails(data: profileDetailsModel.toJson()); + } catch (e) { + rethrow; + } + } + + Future getOAuthAccounts() async { + try { + return await settingsService.getOAuthAccounts(); + } catch (e) { + rethrow; + } + } + + Future linkOAuthAccount({required OAuthAttachRequest request}) async { + try { + return await settingsService.linkOAuthAccount(request); + } catch (e) { + rethrow; + } + } + + Future unlinkOAuthAccount({required String provider}) async { + try { + return await settingsService.unlinkOAuthAccount(provider); } catch (e) { rethrow; } diff --git a/lib/features/settings/services/settings_service.dart b/lib/features/settings/services/settings_service.dart index d17b5842..c83f4c41 100644 --- a/lib/features/settings/services/settings_service.dart +++ b/lib/features/settings/services/settings_service.dart @@ -1,5 +1,7 @@ import 'package:dio/dio.dart'; import 'package:eatvio_app/features/profile/models/profile_model.dart'; +import 'package:eatvio_app/features/settings/models/oauth_account_model.dart'; +import 'package:eatvio_app/features/settings/models/oauth_attach_request.dart'; import 'package:eatvio_app/features/settings/models/profile_settings_model.dart'; import 'package:retrofit/retrofit.dart'; @@ -13,12 +15,17 @@ abstract class SettingsService { Future getProfileSettings(); @PUT('/api/profile/settings/update') - Future updateProfileSettings({ - @Body() required Map data, - }); + Future updateProfileSettings({@Body() required Map data}); @PUT('/api/profile/update') - Future updateProfileDetails({ - @Body() required Map data, - }); + Future updateProfileDetails({@Body() required Map data}); + + @GET('/api/oauth/accounts') + Future getOAuthAccounts(); + + @POST('/api/oauth/attach') + Future linkOAuthAccount(@Body() OAuthAttachRequest request); + + @DELETE('/api/oauth/accounts/{provider}') + Future unlinkOAuthAccount(@Path('provider') String provider); }