refactor(legacy-account): migrate delete_account to AsyncNotifier + fix A1

This commit is contained in:
2026-04-21 22:12:51 +02:00
parent 21dcafec26
commit 6d49e604be
18 changed files with 469 additions and 705 deletions

View File

@@ -1,12 +1,15 @@
import 'package:account/src/features/delete_account/presentation/state/delete_account_view_model.dart';
import 'package:legacy_theme/legacy_theme.dart';
import 'dart:async';
import 'package:account/src/features/delete_account/presentation/widgets/confirm_dialog.dart';
import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:legacy_theme/legacy_theme.dart';
import 'package:legacy_ui/legacy_ui.dart';
import 'package:navigation/navigation.dart';
import 'package:sf_localizations/sf_localizations.dart';
import 'package:sf_shared/sf_shared.dart';
import 'package:sf_tracking/sf_tracking.dart';
import 'package:utils/utils.dart';
class DeleteAccountScreen extends ConsumerWidget {
@@ -16,12 +19,11 @@ class DeleteAccountScreen extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
return LegacyPageLayout(
title: context.translate(I18n.deleteAccount),
body: SingleChildScrollView(
child: Container(
margin: EdgeInsets.symmetric(horizontal: 10),
margin: const EdgeInsets.symmetric(horizontal: 10),
child: Column(
children: [
const _Header(),
@@ -36,30 +38,29 @@ class DeleteAccountScreen extends ConsumerWidget {
}
}
class _Header extends ConsumerWidget {
class _Header extends StatelessWidget {
const _Header();
@override
Widget build(BuildContext context, WidgetRef ref) {
Widget build(BuildContext context) {
return Container(
color: Theme.of(context).colorScheme.surfaceContainer,
width: double.infinity,
padding: SizeUtils.getByScreen(
small: EdgeInsets.symmetric(vertical: 20),
big: EdgeInsets.symmetric(vertical: 19),
small: const EdgeInsets.symmetric(vertical: 20),
big: const EdgeInsets.symmetric(vertical: 19),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
decoration: BoxDecoration(
color: Color(0xFF00A1C6),
color: const Color(0xFF00A1C6),
borderRadius: BorderRadius.circular(12),
),
padding: SizeUtils.getByScreen(
small: EdgeInsets.all(7),
big: EdgeInsets.all(6),
small: const EdgeInsets.all(7),
big: const EdgeInsets.all(6),
),
child: Icon(
Icons.power_settings_new_outlined,
@@ -79,12 +80,11 @@ class _Header extends ConsumerWidget {
}
}
class _BodySection extends ConsumerWidget {
class _BodySection extends StatelessWidget {
const _BodySection();
@override
Widget build(BuildContext context, WidgetRef ref) {
Widget build(BuildContext context) {
return Column(
children: [
Text(
@@ -112,38 +112,38 @@ class _RequestCancelSection extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final isLoading = ref.watch(
deleteAccountViewModelProvider.select((s) => s.isLoading),
);
final user = ref.watch(
deleteAccountViewModelProvider.select((s) => s.loggedUser),
);
return Padding(
padding: SizeUtils.getByScreen(
small: EdgeInsets.symmetric(horizontal: 14, vertical: 10),
big: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
small: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
big: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
),
child: PrimaryButton(
onPressed: () {
if (isLoading) return;
if (user == null) {
navigationContract.goTo(AppRoutes.legacyLogin);
return;
}
showDialog(
context: context,
builder: (context) => Dialog(
backgroundColor: Colors.transparent,
child: ConfirmDialog(navigationContract: navigationContract),
),
);
},
onPressed: () => _onDeletePressed(context, ref),
text: context.translate(I18n.requestCancelButton),
color: context.sfColors.legacyPrimary,
),
);
}
Future<void> _onDeletePressed(BuildContext context, WidgetRef ref) async {
unawaited(ref.read(sfTrackingProvider).legacyAccountDeletionInitiated());
final devices = await ref.read(legacyDevicesProvider.future);
if (!context.mounted) return;
if (devices.isNotEmpty) {
await showInfoDialog(
context,
I18n.accountDeletionHasDevices,
autoDismiss: null,
);
return;
}
if (!context.mounted) return;
showDialog<void>(
context: context,
builder: (_) => ConfirmDialog(navigationContract: navigationContract),
);
}
}

View File

@@ -0,0 +1,39 @@
import 'dart:async';
import 'package:account/src/core/providers/users_repository_provider.dart';
import 'package:legacy_auth/legacy_auth.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:sf_shared/sf_shared.dart';
import 'package:sf_tracking/sf_tracking.dart';
part 'delete_account_controller.g.dart';
@riverpod
class DeleteAccountController extends _$DeleteAccountController {
@override
FutureOr<void> build() {}
Future<void> verifyPassword({required String password}) async {
state = const AsyncLoading();
state = await AsyncValue.guard(() async {
final user = await ref.read(userInfoProvider.future);
await ref
.read(legacyLoginRepositoryProvider)
.login(email: user.email, password: password);
});
}
Future<void> submit() async {
state = const AsyncLoading();
state = await AsyncValue.guard(() async {
unawaited(
ref.read(sfTrackingProvider).legacyAccountDeletionConfirmed(),
);
final user = await ref.read(userInfoProvider.future);
await ref.read(usersRepositoryProvider).deleteUser(userId: user.id);
unawaited(
ref.read(sfTrackingProvider).legacyAccountDeletionCompleted(),
);
});
}
}

View File

@@ -0,0 +1,56 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'delete_account_controller.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(DeleteAccountController)
const deleteAccountControllerProvider = DeleteAccountControllerProvider._();
final class DeleteAccountControllerProvider
extends $AsyncNotifierProvider<DeleteAccountController, void> {
const DeleteAccountControllerProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'deleteAccountControllerProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$deleteAccountControllerHash();
@$internal
@override
DeleteAccountController create() => DeleteAccountController();
}
String _$deleteAccountControllerHash() =>
r'fec69b905e8020c9357500bdd4c75e70b2b0797d';
abstract class _$DeleteAccountController extends $AsyncNotifier<void> {
FutureOr<void> build();
@$mustCallSuper
@override
void runBuild() {
build();
final ref = this.ref as $Ref<AsyncValue<void>, void>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<AsyncValue<void>, void>,
AsyncValue<void>,
Object?,
Object?
>;
element.handleValue(ref, null);
}
}

View File

@@ -1,131 +0,0 @@
import 'dart:async';
import 'package:account/src/core/domain/repositories/users_repository.dart';
import 'package:account/src/core/providers/users_repository_provider.dart';
import 'package:account/src/features/delete_account/presentation/state/delete_account_view_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:sf_shared/sf_shared.dart';
import 'package:sf_tracking/sf_tracking.dart';
final deleteAccountViewModelProvider =
NotifierProvider.autoDispose<
DeleteAccountViewModel,
DeleteAccountViewState
>(DeleteAccountViewModel.new);
class DeleteAccountViewModel extends Notifier<DeleteAccountViewState> {
late final UsersRepository _usersRepository;
late final SharedDevicesRepository _devicesRepository;
late final SfTrackingRepository _tracking;
late final TextEditingController passwordController;
@override
DeleteAccountViewState build() {
_usersRepository = ref.read(usersRepositoryProvider);
_devicesRepository = ref.read(sharedDevicesRepositoryProvider);
_tracking = ref.read(sfTrackingProvider);
unawaited(_tracking.legacyAccountDeletionInitiated());
passwordController = TextEditingController();
passwordController.addListener(_onPasswordChanged);
ref.onDispose(disposeListeners);
Future.microtask(() => load());
return const DeleteAccountViewState();
}
Future<void> load() async {
final user = await ref.read(userInfoProvider.future);
setUser(user);
final devices = await _devicesRepository.getDevices();
setDevices(devices);
}
void setUser(UserEntity user) {
state = state.copyWith(loggedUser: user);
}
void setDevices(List<DeviceEntity> devices) {
state = state.copyWith(
deviceNames: devices.map((device) => device.carrierName!).toList(),
deleteDevices: List<bool>.generate(devices.length, (_) => false),
);
}
void toggleDeleteDevice(int index) {
List<bool> deleteDevices = state.deleteDevices;
deleteDevices[index] = !deleteDevices[index];
state = state.copyWith(deleteDevices: deleteDevices);
}
void _onPasswordChanged() {
final value = passwordController.text;
if (value == state.password) return;
state = state.copyWith(password: value, errorMessage: '');
}
bool _validateForm() {
if (state.password.trim().isEmpty) {
state = state.copyWith(errorMessage: 'errorMessagePasswordIsEmpty');
return false;
}
/*if (state.password.trim() != state.loggedUser.password.trim()) {
state = state.copyWith(errorMessage: 'errorMessagePasswordsDontMatch');
return false;
}*/
return true;
}
void nextStep() {
final step = state.confirmStep;
if (step == 0 && !_validateForm()) return;
state = state.copyWith(confirmStep: step + 1);
}
void resetConfirmStep() {
unawaited(_tracking.legacyAccountDeletionCancelled());
state = state.copyWith(confirmStep: 0);
}
Future<void> deleteAccount() async {
if (state.isLoading) return;
try {
state = state.copyWith(isLoading: true, isComplete: false);
unawaited(_tracking.legacyAccountDeletionConfirmed());
await _usersRepository.deleteUser(userId: state.loggedUser!.id);
if (!ref.mounted) return;
unawaited(_tracking.legacyAccountDeletionCompleted());
state = state.copyWith(isLoading: false, isComplete: true);
} catch (e) {
if (!ref.mounted) return;
_finishWithError(message: e.toString());
}
}
void _finishWithError({required String message}) {
state = state.copyWith(
isLoading: false,
isComplete: false,
errorMessage: message,
);
}
void disposeListeners() {
passwordController.removeListener(_onPasswordChanged);
passwordController.dispose();
}
}

View File

@@ -1,18 +0,0 @@
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:sf_shared/sf_shared.dart';
part 'delete_account_view_state.freezed.dart';
@freezed
abstract class DeleteAccountViewState with _$DeleteAccountViewState {
const factory DeleteAccountViewState({
UserEntity? loggedUser,
@Default('') String password,
@Default(false) bool isLoading,
@Default(false) bool isComplete,
@Default(0) int confirmStep,
@Default([]) List<String> deviceNames,
@Default([]) List<bool> deleteDevices,
@Default('') String errorMessage,
}) = _DeleteAccountViewState;
}

View File

@@ -1,328 +0,0 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'delete_account_view_state.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// dart format off
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$DeleteAccountViewState {
UserEntity? get loggedUser; String get password; bool get isLoading; bool get isComplete; int get confirmStep; List<String> get deviceNames; List<bool> get deleteDevices; String get errorMessage;
/// Create a copy of DeleteAccountViewState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$DeleteAccountViewStateCopyWith<DeleteAccountViewState> get copyWith => _$DeleteAccountViewStateCopyWithImpl<DeleteAccountViewState>(this as DeleteAccountViewState, _$identity);
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is DeleteAccountViewState&&(identical(other.loggedUser, loggedUser) || other.loggedUser == loggedUser)&&(identical(other.password, password) || other.password == password)&&(identical(other.isLoading, isLoading) || other.isLoading == isLoading)&&(identical(other.isComplete, isComplete) || other.isComplete == isComplete)&&(identical(other.confirmStep, confirmStep) || other.confirmStep == confirmStep)&&const DeepCollectionEquality().equals(other.deviceNames, deviceNames)&&const DeepCollectionEquality().equals(other.deleteDevices, deleteDevices)&&(identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage));
}
@override
int get hashCode => Object.hash(runtimeType,loggedUser,password,isLoading,isComplete,confirmStep,const DeepCollectionEquality().hash(deviceNames),const DeepCollectionEquality().hash(deleteDevices),errorMessage);
@override
String toString() {
return 'DeleteAccountViewState(loggedUser: $loggedUser, password: $password, isLoading: $isLoading, isComplete: $isComplete, confirmStep: $confirmStep, deviceNames: $deviceNames, deleteDevices: $deleteDevices, errorMessage: $errorMessage)';
}
}
/// @nodoc
abstract mixin class $DeleteAccountViewStateCopyWith<$Res> {
factory $DeleteAccountViewStateCopyWith(DeleteAccountViewState value, $Res Function(DeleteAccountViewState) _then) = _$DeleteAccountViewStateCopyWithImpl;
@useResult
$Res call({
UserEntity? loggedUser, String password, bool isLoading, bool isComplete, int confirmStep, List<String> deviceNames, List<bool> deleteDevices, String errorMessage
});
$UserEntityCopyWith<$Res>? get loggedUser;
}
/// @nodoc
class _$DeleteAccountViewStateCopyWithImpl<$Res>
implements $DeleteAccountViewStateCopyWith<$Res> {
_$DeleteAccountViewStateCopyWithImpl(this._self, this._then);
final DeleteAccountViewState _self;
final $Res Function(DeleteAccountViewState) _then;
/// Create a copy of DeleteAccountViewState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? loggedUser = freezed,Object? password = null,Object? isLoading = null,Object? isComplete = null,Object? confirmStep = null,Object? deviceNames = null,Object? deleteDevices = null,Object? errorMessage = null,}) {
return _then(_self.copyWith(
loggedUser: freezed == loggedUser ? _self.loggedUser : loggedUser // ignore: cast_nullable_to_non_nullable
as UserEntity?,password: null == password ? _self.password : password // ignore: cast_nullable_to_non_nullable
as String,isLoading: null == isLoading ? _self.isLoading : isLoading // ignore: cast_nullable_to_non_nullable
as bool,isComplete: null == isComplete ? _self.isComplete : isComplete // ignore: cast_nullable_to_non_nullable
as bool,confirmStep: null == confirmStep ? _self.confirmStep : confirmStep // ignore: cast_nullable_to_non_nullable
as int,deviceNames: null == deviceNames ? _self.deviceNames : deviceNames // ignore: cast_nullable_to_non_nullable
as List<String>,deleteDevices: null == deleteDevices ? _self.deleteDevices : deleteDevices // ignore: cast_nullable_to_non_nullable
as List<bool>,errorMessage: null == errorMessage ? _self.errorMessage : errorMessage // ignore: cast_nullable_to_non_nullable
as String,
));
}
/// Create a copy of DeleteAccountViewState
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$UserEntityCopyWith<$Res>? get loggedUser {
if (_self.loggedUser == null) {
return null;
}
return $UserEntityCopyWith<$Res>(_self.loggedUser!, (value) {
return _then(_self.copyWith(loggedUser: value));
});
}
}
/// Adds pattern-matching-related methods to [DeleteAccountViewState].
extension DeleteAccountViewStatePatterns on DeleteAccountViewState {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _DeleteAccountViewState value)? $default,{required TResult orElse(),}){
final _that = this;
switch (_that) {
case _DeleteAccountViewState() when $default != null:
return $default(_that);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _DeleteAccountViewState value) $default,){
final _that = this;
switch (_that) {
case _DeleteAccountViewState():
return $default(_that);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _DeleteAccountViewState value)? $default,){
final _that = this;
switch (_that) {
case _DeleteAccountViewState() when $default != null:
return $default(_that);case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( UserEntity? loggedUser, String password, bool isLoading, bool isComplete, int confirmStep, List<String> deviceNames, List<bool> deleteDevices, String errorMessage)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _DeleteAccountViewState() when $default != null:
return $default(_that.loggedUser,_that.password,_that.isLoading,_that.isComplete,_that.confirmStep,_that.deviceNames,_that.deleteDevices,_that.errorMessage);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( UserEntity? loggedUser, String password, bool isLoading, bool isComplete, int confirmStep, List<String> deviceNames, List<bool> deleteDevices, String errorMessage) $default,) {final _that = this;
switch (_that) {
case _DeleteAccountViewState():
return $default(_that.loggedUser,_that.password,_that.isLoading,_that.isComplete,_that.confirmStep,_that.deviceNames,_that.deleteDevices,_that.errorMessage);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( UserEntity? loggedUser, String password, bool isLoading, bool isComplete, int confirmStep, List<String> deviceNames, List<bool> deleteDevices, String errorMessage)? $default,) {final _that = this;
switch (_that) {
case _DeleteAccountViewState() when $default != null:
return $default(_that.loggedUser,_that.password,_that.isLoading,_that.isComplete,_that.confirmStep,_that.deviceNames,_that.deleteDevices,_that.errorMessage);case _:
return null;
}
}
}
/// @nodoc
class _DeleteAccountViewState implements DeleteAccountViewState {
const _DeleteAccountViewState({this.loggedUser, this.password = '', this.isLoading = false, this.isComplete = false, this.confirmStep = 0, final List<String> deviceNames = const [], final List<bool> deleteDevices = const [], this.errorMessage = ''}): _deviceNames = deviceNames,_deleteDevices = deleteDevices;
@override final UserEntity? loggedUser;
@override@JsonKey() final String password;
@override@JsonKey() final bool isLoading;
@override@JsonKey() final bool isComplete;
@override@JsonKey() final int confirmStep;
final List<String> _deviceNames;
@override@JsonKey() List<String> get deviceNames {
if (_deviceNames is EqualUnmodifiableListView) return _deviceNames;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(_deviceNames);
}
final List<bool> _deleteDevices;
@override@JsonKey() List<bool> get deleteDevices {
if (_deleteDevices is EqualUnmodifiableListView) return _deleteDevices;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(_deleteDevices);
}
@override@JsonKey() final String errorMessage;
/// Create a copy of DeleteAccountViewState
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$DeleteAccountViewStateCopyWith<_DeleteAccountViewState> get copyWith => __$DeleteAccountViewStateCopyWithImpl<_DeleteAccountViewState>(this, _$identity);
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _DeleteAccountViewState&&(identical(other.loggedUser, loggedUser) || other.loggedUser == loggedUser)&&(identical(other.password, password) || other.password == password)&&(identical(other.isLoading, isLoading) || other.isLoading == isLoading)&&(identical(other.isComplete, isComplete) || other.isComplete == isComplete)&&(identical(other.confirmStep, confirmStep) || other.confirmStep == confirmStep)&&const DeepCollectionEquality().equals(other._deviceNames, _deviceNames)&&const DeepCollectionEquality().equals(other._deleteDevices, _deleteDevices)&&(identical(other.errorMessage, errorMessage) || other.errorMessage == errorMessage));
}
@override
int get hashCode => Object.hash(runtimeType,loggedUser,password,isLoading,isComplete,confirmStep,const DeepCollectionEquality().hash(_deviceNames),const DeepCollectionEquality().hash(_deleteDevices),errorMessage);
@override
String toString() {
return 'DeleteAccountViewState(loggedUser: $loggedUser, password: $password, isLoading: $isLoading, isComplete: $isComplete, confirmStep: $confirmStep, deviceNames: $deviceNames, deleteDevices: $deleteDevices, errorMessage: $errorMessage)';
}
}
/// @nodoc
abstract mixin class _$DeleteAccountViewStateCopyWith<$Res> implements $DeleteAccountViewStateCopyWith<$Res> {
factory _$DeleteAccountViewStateCopyWith(_DeleteAccountViewState value, $Res Function(_DeleteAccountViewState) _then) = __$DeleteAccountViewStateCopyWithImpl;
@override @useResult
$Res call({
UserEntity? loggedUser, String password, bool isLoading, bool isComplete, int confirmStep, List<String> deviceNames, List<bool> deleteDevices, String errorMessage
});
@override $UserEntityCopyWith<$Res>? get loggedUser;
}
/// @nodoc
class __$DeleteAccountViewStateCopyWithImpl<$Res>
implements _$DeleteAccountViewStateCopyWith<$Res> {
__$DeleteAccountViewStateCopyWithImpl(this._self, this._then);
final _DeleteAccountViewState _self;
final $Res Function(_DeleteAccountViewState) _then;
/// Create a copy of DeleteAccountViewState
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? loggedUser = freezed,Object? password = null,Object? isLoading = null,Object? isComplete = null,Object? confirmStep = null,Object? deviceNames = null,Object? deleteDevices = null,Object? errorMessage = null,}) {
return _then(_DeleteAccountViewState(
loggedUser: freezed == loggedUser ? _self.loggedUser : loggedUser // ignore: cast_nullable_to_non_nullable
as UserEntity?,password: null == password ? _self.password : password // ignore: cast_nullable_to_non_nullable
as String,isLoading: null == isLoading ? _self.isLoading : isLoading // ignore: cast_nullable_to_non_nullable
as bool,isComplete: null == isComplete ? _self.isComplete : isComplete // ignore: cast_nullable_to_non_nullable
as bool,confirmStep: null == confirmStep ? _self.confirmStep : confirmStep // ignore: cast_nullable_to_non_nullable
as int,deviceNames: null == deviceNames ? _self._deviceNames : deviceNames // ignore: cast_nullable_to_non_nullable
as List<String>,deleteDevices: null == deleteDevices ? _self._deleteDevices : deleteDevices // ignore: cast_nullable_to_non_nullable
as List<bool>,errorMessage: null == errorMessage ? _self.errorMessage : errorMessage // ignore: cast_nullable_to_non_nullable
as String,
));
}
/// Create a copy of DeleteAccountViewState
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$UserEntityCopyWith<$Res>? get loggedUser {
if (_self.loggedUser == null) {
return null;
}
return $UserEntityCopyWith<$Res>(_self.loggedUser!, (value) {
return _then(_self.copyWith(loggedUser: value));
});
}
}
// dart format on

View File

@@ -1,239 +1,208 @@
import 'package:account/src/features/delete_account/presentation/state/delete_account_view_model.dart';
import 'dart:async';
import 'package:account/src/features/delete_account/presentation/providers/delete_account_controller.dart';
import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:navigation/app_routes.dart';
import 'package:navigation/navigation_contract.dart';
import 'package:sf_localizations/sf_localizations.dart';
import 'package:utils/utils.dart';
import 'package:legacy_theme/legacy_theme.dart';
import 'package:navigation/navigation.dart';
import 'package:sf_infrastructure/sf_infrastructure.dart';
import 'package:sf_localizations/sf_localizations.dart';
import 'package:sf_shared/sf_shared.dart';
import 'package:sf_tracking/sf_tracking.dart';
class ConfirmDialog extends ConsumerWidget {
class ConfirmDialog extends ConsumerStatefulWidget {
final NavigationContract navigationContract;
const ConfirmDialog({super.key, required this.navigationContract});
@override
Widget build(BuildContext context, WidgetRef ref) {
ConsumerState<ConfirmDialog> createState() => _ConfirmDialogState();
}
final state = ref.watch(deleteAccountViewModelProvider);
final viewModel = ref.read(deleteAccountViewModelProvider.notifier);
class _ConfirmDialogState extends ConsumerState<ConfirmDialog> {
late final TextEditingController _passwordController;
bool _showPassword = false;
int _step = 0;
final steps = [
_VerifyAccountStep(
email: state.loggedUser!.email,
passwordController: viewModel.passwordController,
errorMessage: state.errorMessage,
nextStep: viewModel.nextStep,
),
_ConfirmRequestStep(
toggleDeleteDevice: viewModel.toggleDeleteDevice,
deviceNames: state.deviceNames,
onCancel: () {
viewModel.resetConfirmStep();
Navigator.pop(context);
},
onSubmit: () async {
viewModel.deleteAccount();
if (!context.mounted) return;
@override
void initState() {
super.initState();
_passwordController = TextEditingController();
}
final isComplete = ref.read(
deleteAccountViewModelProvider.select((s) => s.isComplete),
@override
void dispose() {
_passwordController.dispose();
super.dispose();
}
void _onVerifyPassword() {
if (_passwordController.text.trim().isEmpty) return;
ref
.read(deleteAccountControllerProvider.notifier)
.verifyPassword(password: _passwordController.text);
}
void _onConfirmDelete() {
ref.read(deleteAccountControllerProvider.notifier).submit();
}
void _onCancel() {
unawaited(ref.read(sfTrackingProvider).legacyAccountDeletionCancelled());
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
ref.listen(deleteAccountControllerProvider, (prev, next) async {
if (prev == null || !prev.isLoading || next.isLoading) return;
if (next.hasError) {
await next.showErrorOn(context);
return;
}
if (_step == 0) {
setState(() => _step = 1);
} else {
await clearSessionData();
ref.invalidate(legacyDevicesProvider);
ref.invalidate(selectedDeviceProvider);
if (!context.mounted) return;
await showSuccessDialog(context, I18n.accountDeletedSuccess);
if (context.mounted) {
widget.navigationContract.goTo(AppRoutes.legacyLogin);
}
}
});
final isLoading = ref.watch(deleteAccountControllerProvider).isLoading;
return _step == 0
? _VerifyAccountStep(
email: ref.watch(userInfoProvider).value?.email ?? '',
passwordController: _passwordController,
showPassword: _showPassword,
onToggleShowPassword: () =>
setState(() => _showPassword = !_showPassword),
isLoading: isLoading,
onAccept: _onVerifyPassword,
onCancel: _onCancel,
)
: _ConfirmRequestStep(
isLoading: isLoading,
onConfirm: _onConfirmDelete,
onCancel: _onCancel,
);
if (isComplete) {
navigationContract.goTo(AppRoutes.legacyLogin);
}
},
),
];
return steps[state.confirmStep];
}
}
class _VerifyAccountStep extends StatelessWidget {
final String email;
final TextEditingController passwordController;
final String errorMessage;
final VoidCallback nextStep;
final bool showPassword;
final VoidCallback onToggleShowPassword;
final bool isLoading;
final VoidCallback onAccept;
final VoidCallback onCancel;
const _VerifyAccountStep({
required this.email,
required this.passwordController,
required this.errorMessage,
required this.nextStep,
required this.showPassword,
required this.onToggleShowPassword,
required this.isLoading,
required this.onAccept,
required this.onCancel,
});
@override
Widget build(BuildContext context) {
return Container(
height: 210,
width: 500,
color: Colors.white,
padding: SizeUtils.getByScreen(
small: EdgeInsets.symmetric(horizontal: 22, vertical: 11),
big: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
final theme = Theme.of(context);
return AlertDialog(
title: Text(context.translate(I18n.verifyAccount)),
content: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Text(
context.translate(I18n.verifyAccount),
style: TextStyle(fontWeight: FontWeight.w500),
context.translate(I18n.deleteAccountVerifyPrompt),
style: theme.textTheme.bodyMedium,
),
SizedBox(height: SizeUtils.getByScreen(small: 18, big: 16)),
Text('${context.translate(I18n.email)}: $email'),
SizedBox(height: SizeUtils.getByScreen(small: 8, big: 6)),
Row(
children: [
Text('${context.translate(I18n.password)}: '),
SizedBox(width: SizeUtils.getByScreen(small: 12, big: 10)),
Expanded(
child: TextField(
controller: passwordController,
style: TextStyle(fontSize: 12),
decoration: InputDecoration(
hintText: context.translate(I18n.password),
),
obscureText: true,
enableSuggestions: false,
autocorrect: true,
),
),
],
),
if (errorMessage.isNotEmpty)
Text(
errorMessage,
textAlign: TextAlign.center,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
fontSize: 13,
),
const SizedBox(height: 16),
Text(
context.translate(I18n.email),
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
SizedBox(height: SizeUtils.getByScreen(small: 12, big: 10)),
Row(
children: [
Expanded(
child: SecondaryButton(
onPressed: () {
Navigator.pop(context);
},
text: context.translate(I18n.cancel),
color: context.sfColors.legacyPrimary,
height: 40,
radius: 20,
),
),
SizedBox(width: SizeUtils.getByScreen(small: 12, big: 10)),
Expanded(
child: PrimaryButton(
onPressed: nextStep,
text: context.translate(I18n.accept),
color: context.sfColors.legacyPrimary,
height: 40,
radius: 20,
),
),
],
),
const SizedBox(height: 4),
Text(email, style: theme.textTheme.bodyLarge),
const SizedBox(height: 16),
CustomTextField(
controller: passwordController,
label: context.translate(I18n.password),
showPassword: showPassword,
onVisibilityChanged: onToggleShowPassword,
),
],
),
actions: [
TextButton(
onPressed: isLoading ? null : onCancel,
child: Text(context.translate(I18n.cancel)),
),
FilledButton(
onPressed: isLoading ? null : onAccept,
style: FilledButton.styleFrom(
backgroundColor: context.sfColors.legacyPrimary,
),
child: Text(context.translate(I18n.accept)),
),
],
);
}
}
class _ConfirmRequestStep extends StatelessWidget {
final Function toggleDeleteDevice;
final List<String> deviceNames;
final bool isLoading;
final VoidCallback onConfirm;
final VoidCallback onCancel;
final VoidCallback onSubmit;
const _ConfirmRequestStep({
required this.toggleDeleteDevice,
required this.deviceNames,
required this.isLoading,
required this.onConfirm,
required this.onCancel,
required this.onSubmit,
});
@override
Widget build(BuildContext context) {
return Container(
height: 300,
width: 500,
color: Colors.white,
padding: SizeUtils.getByScreen(
small: EdgeInsets.symmetric(horizontal: 22, vertical: 11),
big: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
final theme = Theme.of(context);
return AlertDialog(
icon: Icon(
Icons.warning_amber_rounded,
color: theme.colorScheme.error,
size: 40,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(height: SizeUtils.getByScreen(small: 14, big: 12)),
Text(
context.translate(I18n.requestCancelTitle),
style: TextStyle(fontWeight: FontWeight.w500),
),
SizedBox(height: SizeUtils.getByScreen(small: 14, big: 12)),
Expanded(
child: SingleChildScrollView(
child: Column(
children: [
Text(
context.translate(I18n.requestCancelBody),
style: TextStyle(height: 1.5),
),
SizedBox(height: SizeUtils.getByScreen(small: 12, big: 10)),
...List<Widget>.generate(
deviceNames.length,
(int index) => CheckboxListTile(
contentPadding: EdgeInsets.zero,
title: Text(
context.translate(
I18n.deleteDeviceData,
args: {'name': deviceNames[index]},
),
style: TextStyle(height: 0),
),
controlAffinity: ListTileControlAffinity.leading,
value: false,
onChanged: (_) {
toggleDeleteDevice(index);
},
),
),
],
),
),
),
SizedBox(height: SizeUtils.getByScreen(small: 12, big: 10)),
Row(
children: [
Expanded(
child: SecondaryButton(
onPressed: onCancel,
text: context.translate(I18n.cancel),
color: context.sfColors.legacyPrimary,
height: 50,
radius: 25,
),
),
SizedBox(width: SizeUtils.getByScreen(small: 12, big: 10)),
Expanded(
child: PrimaryButton(
onPressed: onSubmit,
text: context.translate(I18n.confirm),
color: context.sfColors.legacyPrimary,
height: 50,
radius: 25,
),
),
],
),
],
title: Text(context.translate(I18n.requestCancelTitle)),
content: Text(
context.translate(I18n.deleteAccountConfirmBody),
style: theme.textTheme.bodyMedium,
),
actions: [
TextButton(
onPressed: isLoading ? null : onCancel,
child: Text(context.translate(I18n.cancel)),
),
FilledButton(
onPressed: isLoading ? null : onConfirm,
style: FilledButton.styleFrom(
backgroundColor: theme.colorScheme.error,
),
child: Text(context.translate(I18n.confirm)),
),
],
);
}
}

View File

@@ -42,7 +42,7 @@ final class LinkedDevicesEditModeProvider
}
String _$linkedDevicesEditModeHash() =>
r'aea2da0d62667e721fa059fe5b48201689bbf9c2';
r'e9feb203af2144c68897e4edc3629b067e8d679e';
abstract class _$LinkedDevicesEditMode extends $Notifier<bool> {
bool build();

View File

@@ -0,0 +1,148 @@
import 'package:account/src/core/domain/repositories/users_repository.dart';
import 'package:account/src/core/providers/users_repository_provider.dart';
import 'package:account/src/features/delete_account/presentation/providers/delete_account_controller.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:legacy_auth/legacy_auth.dart';
import 'package:legacy_auth/src/core/domain/repositories/login_repository.dart';
import 'package:legacy_auth/src/features/login/domain/entities/login_response_entity.dart';
import 'package:mocktail/mocktail.dart';
import 'package:sf_infrastructure/sf_infrastructure.dart';
import 'package:sf_shared/sf_shared.dart';
import 'package:sf_shared/testing.dart';
import 'package:sf_tracking/sf_tracking.dart';
class MockUsersRepository extends Mock implements UsersRepository {}
class MockLegacyLoginRepository extends Mock
implements LegacyLoginRepository {}
class _FakeUserInfoNotifier extends UserInfoNotifier {
_FakeUserInfoNotifier(this._user);
final UserEntity _user;
@override
Future<UserEntity> build() async => _user;
}
const _user = UserEntity(
id: 'user-1',
email: 'user1@test.com',
createdAt: 0,
status: 'active',
role: 'parent',
lastLogin: 0,
currentLogin: 0,
language: 'es',
firstName: 'Ada',
lastName: 'Lovelace',
hasApiKey: false,
phone: '+34600000000',
);
void main() {
ProviderContainer buildContainer({
required UsersRepository usersRepo,
required LegacyLoginRepository loginRepo,
}) {
return makeContainer(
overrides: [
userInfoProvider.overrideWith(() => _FakeUserInfoNotifier(_user)),
usersRepositoryProvider.overrideWithValue(usersRepo),
legacyLoginRepositoryProvider.overrideWithValue(loginRepo),
sfTrackingProvider.overrideWithValue(
SfTrackingRepository(clients: const []),
),
],
);
}
group('DeleteAccountController.verifyPassword', () {
test('transitions to AsyncData when login succeeds', () async {
final users = MockUsersRepository();
final login = MockLegacyLoginRepository();
when(
() => login.login(
email: any(named: 'email'),
password: any(named: 'password'),
),
).thenAnswer(
(_) async => const LegacyLoginResponseEntity(token: 'jwt'),
);
final container = buildContainer(usersRepo: users, loginRepo: login);
addTearDown(container.dispose);
await container
.read(deleteAccountControllerProvider.notifier)
.verifyPassword(password: 'correct');
final state = container.read(deleteAccountControllerProvider);
expect(state, isA<AsyncData<void>>());
expect(state.error, isNull);
verify(
() => login.login(email: _user.email, password: 'correct'),
).called(1);
});
test('exposes AsyncError when login fails with 401', () async {
final users = MockUsersRepository();
final login = MockLegacyLoginRepository();
when(
() => login.login(
email: any(named: 'email'),
password: any(named: 'password'),
),
).thenThrow(
const ApiException(message: 'Invalid credentials', statusCode: 401),
);
final container = buildContainer(usersRepo: users, loginRepo: login);
addTearDown(container.dispose);
await container
.read(deleteAccountControllerProvider.notifier)
.verifyPassword(password: 'wrong');
final state = container.read(deleteAccountControllerProvider);
expect(state, isA<AsyncError<void>>());
expect(state.error, isA<ApiException>());
});
});
group('DeleteAccountController.submit', () {
test('deletes user and transitions to AsyncData', () async {
final users = MockUsersRepository();
final login = MockLegacyLoginRepository();
when(() => users.deleteUser(userId: any(named: 'userId')))
.thenAnswer((_) async {});
final container = buildContainer(usersRepo: users, loginRepo: login);
addTearDown(container.dispose);
await container.read(deleteAccountControllerProvider.notifier).submit();
final state = container.read(deleteAccountControllerProvider);
expect(state, isA<AsyncData<void>>());
verify(() => users.deleteUser(userId: _user.id)).called(1);
});
test('exposes AsyncError when deleteUser fails', () async {
final users = MockUsersRepository();
final login = MockLegacyLoginRepository();
when(() => users.deleteUser(userId: any(named: 'userId')))
.thenThrow(const ApiException(message: 'boom', isNetworkError: true));
final container = buildContainer(usersRepo: users, loginRepo: login);
addTearDown(container.dispose);
await container.read(deleteAccountControllerProvider.notifier).submit();
final state = container.read(deleteAccountControllerProvider);
expect(state, isA<AsyncError<void>>());
expect(state.error, isA<ApiException>());
});
});
}

View File

@@ -8,4 +8,5 @@ export 'src/features/device_setup/presentation/device_setup_screen.dart';
export 'src/features/sign_up/sign_up_builder.dart';
export 'src/core/data/datasource/session_local_datasource.dart';
export 'src/core/providers/auth_repository_provider.dart';
export 'src/core/providers/login_repository_provider.dart';
export 'src/core/data/datasource/session_local_datasource_impl.dart';

View File

@@ -60,6 +60,10 @@
"deviceUpdatedSuccess": "Gerät aktualisiert",
"deviceDeletedSuccess": "Gerät entfernt",
"errorNotAuthorized": "Sie haben keine Berechtigung für diese Aktion.",
"accountDeletedSuccess": "Konto erfolgreich gelöscht",
"accountDeletionHasDevices": "Sie haben verbundene Geräte. Trennen Sie sie zuerst, um Ihr Konto zu kündigen.",
"deleteAccountConfirmBody": "Möchten Sie Ihr Konto wirklich kündigen? Diese Aktion ist unumkehrbar.",
"deleteAccountVerifyPrompt": "Geben Sie Ihr Passwort ein, um die Kündigung zu bestätigen.",
"accept": "Akzeptieren",
"errorMessageUnequalPasswords": "Passwörter stimmen nicht überein. versuchen Sie es erneut",
"errorMessagePasswordTooShort": "Das Passwort muss mindestens 8 Zeichen lang sein",

View File

@@ -60,6 +60,10 @@
"deviceUpdatedSuccess": "Device updated successfully",
"deviceDeletedSuccess": "Device removed successfully",
"errorNotAuthorized": "You don't have permission to perform this action.",
"accountDeletedSuccess": "Account deleted successfully",
"accountDeletionHasDevices": "You have linked devices. Unlink them first to cancel your account.",
"deleteAccountConfirmBody": "Are you sure you want to cancel your account? This action is irreversible.",
"deleteAccountVerifyPrompt": "Enter your password to confirm cancellation.",
"accept": "Accept",
"errorMessageUnequalPasswords": "Passwords don't match. Try again",
"errorMessagePasswordTooShort": "Password must include at least 8 characters",

View File

@@ -60,6 +60,10 @@
"deviceUpdatedSuccess": "Dispositivo actualizado correctamente",
"deviceDeletedSuccess": "Dispositivo eliminado correctamente",
"errorNotAuthorized": "No tienes permiso para realizar esta acción.",
"accountDeletedSuccess": "Cuenta eliminada correctamente",
"accountDeletionHasDevices": "Tienes dispositivos vinculados. Desvincúlalos primero para poder cancelar tu cuenta.",
"deleteAccountConfirmBody": "¿Seguro que quieres cancelar tu cuenta? Esta acción es irreversible.",
"deleteAccountVerifyPrompt": "Introduce tu contraseña para confirmar la cancelación.",
"accept": "Aceptar",
"errorMessageUnequalPasswords": "Las contraseñas no coinciden. Inténtalo de nuevo",
"errorMessagePasswordTooShort": "La contraseña debe tener al menos 8 caracteres",

View File

@@ -60,6 +60,10 @@
"deviceUpdatedSuccess": "Appareil mis à jour",
"deviceDeletedSuccess": "Appareil supprimé",
"errorNotAuthorized": "Vous n'avez pas l'autorisation d'effectuer cette action.",
"accountDeletedSuccess": "Compte supprimé",
"accountDeletionHasDevices": "Vous avez des appareils liés. Dissociez-les d'abord pour annuler votre compte.",
"deleteAccountConfirmBody": "Êtes-vous sûr d'annuler votre compte ? Cette action est irréversible.",
"deleteAccountVerifyPrompt": "Saisissez votre mot de passe pour confirmer l'annulation.",
"accept": "Accepter",
"errorMessageUnequalPasswords": "Les mots de passe ne correspondent pas. essayer à nouveau",
"errorMessagePasswordTooShort": "Le mot de passe doit contenir au moins 8 caractères",

View File

@@ -60,6 +60,10 @@
"deviceUpdatedSuccess": "Dispositivo aggiornato",
"deviceDeletedSuccess": "Dispositivo rimosso",
"errorNotAuthorized": "Non hai i permessi per eseguire questa azione.",
"accountDeletedSuccess": "Account eliminato correttamente",
"accountDeletionHasDevices": "Hai dispositivi collegati. Scollegali prima per cancellare il tuo account.",
"deleteAccountConfirmBody": "Sei sicuro di voler cancellare il tuo account? Questa azione è irreversibile.",
"deleteAccountVerifyPrompt": "Inserisci la tua password per confermare la cancellazione.",
"accept": "Accettare",
"errorMessageUnequalPasswords": "Le password non corrispondono. riprova",
"errorMessagePasswordTooShort": "La password deve contenere almeno 8 caratteri",

View File

@@ -60,6 +60,10 @@
"deviceUpdatedSuccess": "Dispositivo atualizado",
"deviceDeletedSuccess": "Dispositivo removido",
"errorNotAuthorized": "Não tens permissão para realizar esta ação.",
"accountDeletedSuccess": "Conta eliminada com sucesso",
"accountDeletionHasDevices": "Tens dispositivos associados. Desvincula-os primeiro para cancelar a conta.",
"deleteAccountConfirmBody": "Tens a certeza que queres cancelar a tua conta? Esta ação é irreversível.",
"deleteAccountVerifyPrompt": "Introduz a tua palavra-passe para confirmar o cancelamento.",
"accept": "Aceitar",
"errorMessageUnequalPasswords": "Las contraseñas não é coincidência.",
"errorMessagePasswordTooShort": "A senha deve ter pelo menos 8 caracteres",

View File

@@ -9,6 +9,8 @@ class I18n {
static const String accountCreatedEmailVerificationSentLabel = 'accountCreatedEmailVerificationSentLabel';
static const String accountCreatedForLabel = 'accountCreatedForLabel';
static const String accountCreatedTitle = 'accountCreatedTitle';
static const String accountDeletedSuccess = 'accountDeletedSuccess';
static const String accountDeletionHasDevices = 'accountDeletionHasDevices';
static const String accountDetails = 'accountDetails';
static const String accountDocumentError = 'accountDocumentError';
static const String accountSettings = 'accountSettings';
@@ -224,6 +226,8 @@ class I18n {
static const String deleteAccount = 'deleteAccount';
static const String deleteAccountBody1 = 'deleteAccountBody1';
static const String deleteAccountBody2 = 'deleteAccountBody2';
static const String deleteAccountConfirmBody = 'deleteAccountConfirmBody';
static const String deleteAccountVerifyPrompt = 'deleteAccountVerifyPrompt';
static const String deleteAlarm = 'deleteAlarm';
static const String deleteAlarmConfirm = 'deleteAlarmConfirm';
static const String deleteContactMessage = 'deleteContactMessage';

View File

@@ -38,7 +38,7 @@ Future<void> showInfoDialog(
BuildContext context,
String messageKey, {
Map<String, dynamic>? args,
Duration autoDismiss = const Duration(seconds: 2),
Duration? autoDismiss = const Duration(seconds: 2),
}) {
return _showFeedbackDialog(
context,