games_app/prediqo_mobile/lib/features/wallet/presentation/transfer_screen.dart
2026-10-25 18:21:07 +02:00

533 lines
22 KiB
Dart

/// Wallet presentation: in-app transfer to another user by email.
library;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../../core/di/injection.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/utils/amount_utils.dart';
import '../../../core/utils/coin_display.dart';
import '../../../data/repositories/wallet_repository_impl.dart';
import '../../../domain/repositories/health_repository.dart';
import '../../../domain/repositories/repositories.dart';
import '../../../l10n/app_strings.dart';
import '../../../shared/widgets/app_snackbar.dart';
import '../../../shared/widgets/pred_card.dart';
import '../../../shared/widgets/pred_skeleton.dart';
import '../../../shared/widgets/section_error.dart';
import '../../../shared/widgets/tloto_gradient_app_bar.dart';
import '../bloc/wallet_bloc.dart';
import '../utils/money_confirm_preflight.dart';
/// Form to transfer balance to another registered user; requires TOTP and confirmation.
class TransferScreen extends StatefulWidget {
const TransferScreen({super.key});
@override
State<TransferScreen> createState() => _TransferScreenState();
}
/// Validates inputs, shows a confirmation dialog, and dispatches [WalletTransferRequested].
class _TransferScreenState extends State<TransferScreen> {
final _emailController = TextEditingController();
final _amountController = TextEditingController();
final _totpController = TextEditingController();
String? _selectedWalletType;
bool? _totpEnabled;
bool _requireWithdrawal2fa = true;
bool _submitting = false;
bool _confirming = false;
bool _securityFailed = false;
String? _localError;
bool get _needs2faSetup => _requireWithdrawal2fa && _totpEnabled == false;
@override
void initState() {
super.initState();
context.read<WalletBloc>().add(const WalletLoadRequested(ifStale: true));
_loadSecurityContext();
}
Future<void> _loadSecurityContext({bool forceProfile = false}) async {
try {
final profile =
await sl<AuthRepository>().getProfile(force: forceProfile);
final health = await sl<HealthRepository>().getHealth();
if (!mounted) return;
setState(() {
_totpEnabled = profile.totpEnabled;
_requireWithdrawal2fa = health.requireWithdrawal2fa;
_securityFailed = false;
});
} catch (_) {
if (!mounted) return;
setState(() {
_totpEnabled ??= false;
_securityFailed = true;
});
}
}
Future<void> _refreshAll() async {
context.read<WalletBloc>().add(const WalletLoadRequested());
await _loadSecurityContext(forceProfile: true);
}
@override
void dispose() {
_emailController.dispose();
_amountController.dispose();
_totpController.dispose();
super.dispose();
}
Future<void> _submitTransfer() async {
if (_confirming || _submitting) return;
final s = context.strings;
setState(() => _localError = null);
if (_needs2faSetup) {
setState(() => _localError = s.transferTwoFaRequiredBody);
showErrorSnackBar(context, s.transferTwoFaRequiredBody);
return;
}
if (_selectedWalletType == null ||
_emailController.text.trim().isEmpty ||
_amountController.text.isEmpty) {
setState(() => _localError = s.transferFillFields);
showErrorSnackBar(context, s.transferFillFields);
return;
}
if (_requireWithdrawal2fa && _totpController.text.trim().length != 6) {
setState(() => _localError = s.transferFillFields);
showErrorSnackBar(context, s.transferFillFields);
return;
}
final state = context.read<WalletBloc>().state;
final selectedType = state.walletTypes.firstWhere(
(t) => t.code == _selectedWalletType,
orElse: () => state.walletTypes.first,
);
final amountHuman = _amountController.text.trim();
final amountRaw = humanAmountToRaw(amountHuman, selectedType.decimals);
if (amountRaw == '0') {
setState(() => _localError = s.enterValidAmount);
showErrorSnackBar(context, s.enterValidAmount);
return;
}
setState(() => _confirming = true);
try {
final preflight = await fetchMoneyConfirmPreflight(
walletRepo: sl<WalletRepository>(),
healthRepo: sl<HealthRepository>(),
);
final profile = await sl<AuthRepository>().getProfile(force: true);
if (!mounted) return;
setState(() {
_totpEnabled = profile.totpEnabled;
_requireWithdrawal2fa = preflight.health.requireWithdrawal2fa;
_securityFailed = false;
});
context.read<WalletBloc>().add(const WalletLoadRequested());
if (_requireWithdrawal2fa && _totpEnabled == false) {
setState(() => _localError = s.transferTwoFaRequiredBody);
showErrorSnackBar(context, s.transferTwoFaRequiredBody);
return;
}
final match = preflight.balances
.where((b) => b.walletType.code == _selectedWalletType)
.toList();
if (match.isEmpty) {
showErrorSnackBar(context, s.walletBalanceNotLoaded);
return;
}
final available = BigInt.tryParse(match.first.available) ?? BigInt.zero;
final need = BigInt.tryParse(amountRaw) ?? BigInt.zero;
if (need > available) {
showErrorSnackBar(context, s.insufficientBalance);
return;
}
final email = _emailController.text.trim().toLowerCase();
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(s.confirmTransfer),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('${s.amountLabel}: $amountHuman ${selectedType.name}'),
const SizedBox(height: 8),
SelectableText('${s.recipientEmail}: $email'),
const SizedBox(height: 16),
Text(
s.transferImmediateHint,
style: Theme.of(ctx).textTheme.bodySmall,
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(false),
child: Text(s.cancel),
),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(true),
child: Text(s.confirmAction),
),
],
),
);
if (confirmed == true && mounted) {
setState(() => _submitting = true);
final totp = _totpController.text.trim();
context.read<WalletBloc>().add(
WalletTransferRequested(
toEmail: email,
walletType: _selectedWalletType!,
amount: amountRaw,
totpCode: totp.isEmpty ? null : totp,
),
);
}
} catch (_) {
if (!mounted) return;
showErrorSnackBar(context, s.couldNotRefreshBalance);
} finally {
if (mounted) setState(() => _confirming = false);
}
}
@override
Widget build(BuildContext context) {
final s = context.strings;
final bottomInset = MediaQuery.paddingOf(context).bottom;
return AnnotatedRegion<SystemUiOverlayStyle>(
value: TlotoGradientAppBar.overlayStyle,
child: Scaffold(
key: const Key('transfer_screen'),
body: Column(
children: [
TlotoGradientAppBar(title: s.transfer, showBack: true),
Expanded(
child: BlocConsumer<WalletBloc, WalletState>(
listenWhen: (prev, curr) =>
prev.errorMessage != curr.errorMessage ||
prev.transferTxId != curr.transferTxId,
listener: (context, state) {
if (state.errorMessage != null &&
state.errorMessage!.isNotEmpty) {
setState(() {
_submitting = false;
_localError = state.errorMessage;
});
showErrorSnackBar(context, state.errorMessage!);
context.read<WalletBloc>().add(const WalletClearFeedback());
}
if (state.transferTxId != null) {
setState(() => _submitting = false);
showSuccessSnackBar(context, s.transferCompleted);
context.read<WalletBloc>().add(const WalletClearFeedback());
context.pop();
}
},
builder: (context, state) {
if (!state.isLoaded && state.balances.isEmpty) {
return ListView(
padding: EdgeInsets.fromLTRB(
20,
16,
20,
24 + bottomInset,
),
children: const [
PredSkeletonCard(height: 56),
SizedBox(height: 12),
PredSkeletonCard(height: 56),
SizedBox(height: 12),
PredSkeletonCard(height: 56),
SizedBox(height: 12),
PredSkeletonCard(height: 48),
],
);
}
final types = state.walletTypes;
final balances = state.balances;
if (types.isEmpty) {
return ListView(
padding: EdgeInsets.fromLTRB(
20,
16,
20,
24 + bottomInset,
),
children: [
SectionError(
message: state.errorMessage ?? s.walletBalanceNotLoaded,
onRetry: _refreshAll,
),
],
);
}
_selectedWalletType ??= types.first.code;
if (!types.any((t) => t.code == _selectedWalletType)) {
_selectedWalletType = types.first.code;
}
final selectedType = types.firstWhere(
(t) => t.code == _selectedWalletType,
);
final networkLabel =
CoinDisplay.networkLabel(selectedType.code);
final busy = _submitting || _confirming;
return RefreshIndicator(
onRefresh: _refreshAll,
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
),
padding: EdgeInsets.fromLTRB(
20,
16,
20,
24 + bottomInset,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (_securityFailed) ...[
SectionError(
compact: true,
message: s.couldNotVerify2fa,
onRetry: () =>
_loadSecurityContext(forceProfile: true),
),
const SizedBox(height: 12),
],
if (_needs2faSetup) ...[
PredCard(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
s.transferTwoFaRequiredTitle,
style: const TextStyle(
fontWeight: FontWeight.w800,
),
),
const SizedBox(height: 6),
Text(
s.transferTwoFaRequiredBody,
style:
Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 10),
OutlinedButton(
onPressed: () =>
context.push('/totp-setup'),
child: Text(s.enableTwoFa),
),
],
),
),
const SizedBox(height: 12),
],
if (_localError != null) ...[
PredCard(
padding: const EdgeInsets.all(14),
child: Text(
_localError!,
style: const TextStyle(
color: AppColors.danger,
fontWeight: FontWeight.w600,
),
),
),
const SizedBox(height: 12),
],
PredCard(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
s.recipientEmail,
style: const TextStyle(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
TextField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
autocorrect: false,
enabled: !_needs2faSetup && !busy,
decoration: InputDecoration(
labelText: s.emailAddressLabel,
prefixIcon:
const Icon(Icons.email_outlined),
),
),
const SizedBox(height: 14),
Text(
s.assetLabel,
style: const TextStyle(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
DropdownButtonFormField<String>(
key: ValueKey(
'transfer_asset_$_selectedWalletType',
),
isExpanded: true,
initialValue: _selectedWalletType,
items: types
.map(
(t) => DropdownMenuItem(
value: t.code,
child: Text(
t.name,
overflow: TextOverflow.ellipsis,
),
),
)
.toList(),
onChanged: (_needs2faSetup || busy)
? null
: (v) => setState(
() => _selectedWalletType = v,
),
),
const SizedBox(height: 10),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(
Icons.info_outline,
size: 20,
color: AppColors.primary,
),
const SizedBox(width: 8),
Expanded(
child: Text(
s.depositNetworkLabel(networkLabel),
style: Theme.of(context)
.textTheme
.bodySmall,
),
),
],
),
const SizedBox(height: 14),
TextField(
controller: _amountController,
enabled: !_needs2faSetup && !busy,
keyboardType:
const TextInputType.numberWithOptions(
decimal: true,
),
decoration: InputDecoration(
labelText: s.amountLabel,
prefixIcon:
const Icon(Icons.attach_money),
),
),
if (balances.any(
(b) =>
b.walletType.code == _selectedWalletType,
)) ...[
const SizedBox(height: 8),
Text(
s.availableAsset(
rawAmountToHuman(
balances
.firstWhere(
(b) =>
b.walletType.code ==
_selectedWalletType,
)
.available,
selectedType.decimals,
),
selectedType.name,
),
key: const Key('transfer_available'),
style:
Theme.of(context).textTheme.bodySmall,
),
],
],
),
),
if (!_needs2faSetup) ...[
const SizedBox(height: 12),
PredCard(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
s.transferTotpHint,
style: const TextStyle(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
TextField(
controller: _totpController,
enabled: !busy,
keyboardType: TextInputType.number,
maxLength: 6,
decoration: InputDecoration(
labelText: s.totpCode,
prefixIcon:
const Icon(Icons.security),
),
),
],
),
),
],
const SizedBox(height: 20),
FilledButton(
key: const Key('transfer_submit'),
onPressed: busy ? null : _submitTransfer,
child: busy
? const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
)
: Text(s.transfer),
),
],
),
),
);
},
),
),
],
),
),
);
}
}