Starting to resolve the issue on prediction
This commit is contained in:
parent
e5f52cf3cc
commit
633d6683e3
@ -1623,6 +1623,20 @@ async function finalizeIntervalCandleAtMaturity(
|
||||
|
||||
const nowMs = Date.now();
|
||||
const closeMs = openMs + interval.intervalMinutes * 60 * 1000;
|
||||
// Publish real time-to-next-betting so clients do not stick at 0s until refresh.
|
||||
const timingNext = getActiveRoundTiming(
|
||||
nowMs,
|
||||
interval.intervalMinutes,
|
||||
interval.predictionWindowSeconds
|
||||
);
|
||||
const secondsToBettingEnd =
|
||||
timingNext.phase === 'betting'
|
||||
? Math.max(0, Math.ceil((timingNext.openMs - nowMs) / 1000))
|
||||
: 0;
|
||||
const secondsToBettingStart =
|
||||
timingNext.phase === 'betting'
|
||||
? 0
|
||||
: Math.max(0, Math.ceil((timingNext.nextBettingStartMs - nowMs) / 1000));
|
||||
const settledDto = {
|
||||
id: round.id,
|
||||
candleOpenMs: openMs,
|
||||
@ -1636,9 +1650,9 @@ async function finalizeIntervalCandleAtMaturity(
|
||||
closePrice: candle.close,
|
||||
settledAt: new Date().toISOString(),
|
||||
serverNowMs: nowMs,
|
||||
secondsToBettingEnd: 0,
|
||||
secondsToBettingStart: 0,
|
||||
secondsToClose: 0,
|
||||
secondsToBettingEnd,
|
||||
secondsToBettingStart,
|
||||
secondsToClose: Math.max(0, Math.ceil((closeMs - nowMs) / 1000)),
|
||||
};
|
||||
|
||||
// Fire-and-forget Redis publish — must never block or kill the engine loop.
|
||||
|
||||
@ -60,16 +60,237 @@ class AdminUserListResult {
|
||||
final int total;
|
||||
}
|
||||
|
||||
/// TTL store for a single [SystemSettings] payload.
|
||||
class AdminSettingsStore {
|
||||
static const ttl = Duration(seconds: 45);
|
||||
|
||||
SystemSettings? _cached;
|
||||
DateTime? _cachedAt;
|
||||
Future<SystemSettings>? _inFlight;
|
||||
|
||||
SystemSettings? peekLast() => _cached;
|
||||
|
||||
SystemSettings? peekFresh() {
|
||||
if (_cached == null || _cachedAt == null) return null;
|
||||
if (DateTime.now().difference(_cachedAt!) >= ttl) return null;
|
||||
return _cached;
|
||||
}
|
||||
|
||||
void invalidate() {
|
||||
_cached = null;
|
||||
_cachedAt = null;
|
||||
}
|
||||
|
||||
void put(SystemSettings value) {
|
||||
_cached = value;
|
||||
_cachedAt = DateTime.now();
|
||||
}
|
||||
|
||||
Future<SystemSettings> get(
|
||||
Future<SystemSettings> Function() fetch, {
|
||||
bool force = false,
|
||||
}) async {
|
||||
if (!force) {
|
||||
final hit = peekFresh();
|
||||
if (hit != null) return hit;
|
||||
if (_inFlight != null) return _inFlight!;
|
||||
}
|
||||
final future = fetch().then((value) {
|
||||
put(value);
|
||||
return value;
|
||||
});
|
||||
_inFlight = future;
|
||||
try {
|
||||
return await future;
|
||||
} finally {
|
||||
if (identical(_inFlight, future)) _inFlight = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Caches the last admin user-list page (keyed by search/limit/offset).
|
||||
class AdminUsersListStore {
|
||||
static const ttl = Duration(seconds: 45);
|
||||
|
||||
String? _key;
|
||||
AdminUserListResult? _cached;
|
||||
DateTime? _cachedAt;
|
||||
Future<AdminUserListResult>? _inFlight;
|
||||
String? _inFlightKey;
|
||||
|
||||
static String keyFor({String? search, required int limit, required int offset}) {
|
||||
final q = (search ?? '').trim().toLowerCase();
|
||||
return '$q|$limit|$offset';
|
||||
}
|
||||
|
||||
AdminUserListResult? peekLast({
|
||||
String? search,
|
||||
required int limit,
|
||||
required int offset,
|
||||
}) {
|
||||
final key = keyFor(search: search, limit: limit, offset: offset);
|
||||
if (_key != key) return null;
|
||||
return _cached;
|
||||
}
|
||||
|
||||
AdminUserListResult? peekFresh({
|
||||
String? search,
|
||||
required int limit,
|
||||
required int offset,
|
||||
}) {
|
||||
final hit = peekLast(search: search, limit: limit, offset: offset);
|
||||
if (hit == null || _cachedAt == null) return null;
|
||||
if (DateTime.now().difference(_cachedAt!) >= ttl) return null;
|
||||
return hit;
|
||||
}
|
||||
|
||||
void invalidate() {
|
||||
_cached = null;
|
||||
_cachedAt = null;
|
||||
_key = null;
|
||||
}
|
||||
|
||||
Future<AdminUserListResult> get(
|
||||
String key,
|
||||
Future<AdminUserListResult> Function() fetch, {
|
||||
bool force = false,
|
||||
}) async {
|
||||
if (!force) {
|
||||
if (_key == key &&
|
||||
_cached != null &&
|
||||
_cachedAt != null &&
|
||||
DateTime.now().difference(_cachedAt!) < ttl) {
|
||||
return _cached!;
|
||||
}
|
||||
if (_inFlight != null && _inFlightKey == key) return _inFlight!;
|
||||
}
|
||||
final future = fetch().then((value) {
|
||||
_key = key;
|
||||
_cached = value;
|
||||
_cachedAt = DateTime.now();
|
||||
return value;
|
||||
});
|
||||
_inFlight = future;
|
||||
_inFlightKey = key;
|
||||
try {
|
||||
return await future;
|
||||
} finally {
|
||||
if (identical(_inFlight, future)) {
|
||||
_inFlight = null;
|
||||
_inFlightKey = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-user detail cache for admin inspection.
|
||||
class AdminUserDetailStore {
|
||||
static const ttl = Duration(seconds: 45);
|
||||
|
||||
final Map<String, AdminUserDetails> _cached = {};
|
||||
final Map<String, DateTime> _cachedAt = {};
|
||||
final Map<String, Future<AdminUserDetails?>> _inFlight = {};
|
||||
|
||||
AdminUserDetails? peekLast(String userId) => _cached[userId];
|
||||
|
||||
AdminUserDetails? peekFresh(String userId) {
|
||||
final hit = _cached[userId];
|
||||
final at = _cachedAt[userId];
|
||||
if (hit == null || at == null) return null;
|
||||
if (DateTime.now().difference(at) >= ttl) return null;
|
||||
return hit;
|
||||
}
|
||||
|
||||
void invalidate([String? userId]) {
|
||||
if (userId == null) {
|
||||
_cached.clear();
|
||||
_cachedAt.clear();
|
||||
return;
|
||||
}
|
||||
_cached.remove(userId);
|
||||
_cachedAt.remove(userId);
|
||||
}
|
||||
|
||||
Future<AdminUserDetails?> get(
|
||||
String userId,
|
||||
Future<AdminUserDetails?> Function() fetch, {
|
||||
bool force = false,
|
||||
}) async {
|
||||
if (!force) {
|
||||
final hit = peekFresh(userId);
|
||||
if (hit != null) return hit;
|
||||
final pending = _inFlight[userId];
|
||||
if (pending != null) return pending;
|
||||
}
|
||||
final future = fetch().then((value) {
|
||||
if (value != null) {
|
||||
_cached[userId] = value;
|
||||
_cachedAt[userId] = DateTime.now();
|
||||
}
|
||||
return value;
|
||||
});
|
||||
_inFlight[userId] = future;
|
||||
try {
|
||||
return await future;
|
||||
} finally {
|
||||
if (identical(_inFlight[userId], future)) {
|
||||
_inFlight.remove(userId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Repository for admin-only user and settings operations.
|
||||
class AdminRepositoryImpl {
|
||||
AdminRepositoryImpl(this._api);
|
||||
final ApiClient _api;
|
||||
|
||||
final AdminSettingsStore settingsStore = AdminSettingsStore();
|
||||
final AdminUsersListStore usersStore = AdminUsersListStore();
|
||||
final AdminUserDetailStore userDetailStore = AdminUserDetailStore();
|
||||
|
||||
SystemSettings? peekLastSettings() => settingsStore.peekLast();
|
||||
|
||||
AdminUserListResult? peekLastUsers({
|
||||
String? search,
|
||||
int limit = 50,
|
||||
int offset = 0,
|
||||
}) =>
|
||||
usersStore.peekLast(search: search, limit: limit, offset: offset);
|
||||
|
||||
AdminUserDetails? peekLastUserDetails(String userId) =>
|
||||
userDetailStore.peekLast(userId);
|
||||
|
||||
void invalidateSettings() => settingsStore.invalidate();
|
||||
|
||||
void invalidateUsers() => usersStore.invalidate();
|
||||
|
||||
void invalidateUserDetails([String? userId]) =>
|
||||
userDetailStore.invalidate(userId);
|
||||
|
||||
/// Searches and paginates users for the admin management screen.
|
||||
Future<AdminUserListResult> listUsers({
|
||||
String? search,
|
||||
int limit = 50,
|
||||
int offset = 0,
|
||||
bool force = false,
|
||||
}) {
|
||||
final key = AdminUsersListStore.keyFor(
|
||||
search: search,
|
||||
limit: limit,
|
||||
offset: offset,
|
||||
);
|
||||
return usersStore.get(
|
||||
key,
|
||||
() => _fetchUsers(search: search, limit: limit, offset: offset),
|
||||
force: force,
|
||||
);
|
||||
}
|
||||
|
||||
Future<AdminUserListResult> _fetchUsers({
|
||||
String? search,
|
||||
required int limit,
|
||||
required int offset,
|
||||
}) async {
|
||||
final res = await _api.dio.get<Map<String, dynamic>>(
|
||||
'/api/v1/admin/users',
|
||||
@ -112,10 +333,16 @@ class AdminRepositoryImpl {
|
||||
'/api/v1/admin/users/$userId/flags',
|
||||
data: body,
|
||||
);
|
||||
usersStore.invalidate();
|
||||
userDetailStore.invalidate(userId);
|
||||
}
|
||||
|
||||
/// Fetches system settings (password policy, token expiry). Admin only.
|
||||
Future<SystemSettings> getSettings() async {
|
||||
Future<SystemSettings> getSettings({bool force = false}) {
|
||||
return settingsStore.get(_fetchSettings, force: force);
|
||||
}
|
||||
|
||||
Future<SystemSettings> _fetchSettings() async {
|
||||
final res = await _api.dio.get<Map<String, dynamic>>(
|
||||
'/api/v1/admin/settings',
|
||||
);
|
||||
@ -145,11 +372,24 @@ class AdminRepositoryImpl {
|
||||
'refresh_token_expiry': settings.refreshTokenExpiry,
|
||||
},
|
||||
);
|
||||
return getSettings();
|
||||
final fresh = await getSettings(force: true);
|
||||
settingsStore.put(fresh);
|
||||
return fresh;
|
||||
}
|
||||
|
||||
/// Fetches full user details and balances for admin. Returns null if not found.
|
||||
Future<AdminUserDetails?> getUserDetails(String userId) async {
|
||||
Future<AdminUserDetails?> getUserDetails(
|
||||
String userId, {
|
||||
bool force = false,
|
||||
}) {
|
||||
return userDetailStore.get(
|
||||
userId,
|
||||
() => _fetchUserDetails(userId),
|
||||
force: force,
|
||||
);
|
||||
}
|
||||
|
||||
Future<AdminUserDetails?> _fetchUserDetails(String userId) async {
|
||||
final res = await _api.dio.get<Map<String, dynamic>>(
|
||||
'/api/v1/admin/users/$userId',
|
||||
);
|
||||
|
||||
@ -3,13 +3,68 @@ import '../../core/errors/app_exception.dart';
|
||||
import '../../core/network/api_client.dart';
|
||||
import '../../domain/repositories/health_repository.dart';
|
||||
|
||||
/// Short TTL + in-flight coalesce for GET /health.
|
||||
class HealthStore {
|
||||
static const ttl = Duration(seconds: 45);
|
||||
|
||||
HealthStatus? _cached;
|
||||
DateTime? _cachedAt;
|
||||
Future<HealthStatus>? _inFlight;
|
||||
|
||||
HealthStatus? peekLast() => _cached;
|
||||
|
||||
HealthStatus? peekFresh() {
|
||||
if (_cached == null || _cachedAt == null) return null;
|
||||
if (DateTime.now().difference(_cachedAt!) >= ttl) return null;
|
||||
return _cached;
|
||||
}
|
||||
|
||||
void invalidate() {
|
||||
_cached = null;
|
||||
_cachedAt = null;
|
||||
}
|
||||
|
||||
Future<HealthStatus> get(
|
||||
Future<HealthStatus> Function() fetch, {
|
||||
bool force = false,
|
||||
}) async {
|
||||
if (!force) {
|
||||
final hit = peekFresh();
|
||||
if (hit != null) return hit;
|
||||
if (_inFlight != null) return _inFlight!;
|
||||
}
|
||||
final future = fetch().then((value) {
|
||||
_cached = value;
|
||||
_cachedAt = DateTime.now();
|
||||
return value;
|
||||
});
|
||||
_inFlight = future;
|
||||
try {
|
||||
return await future;
|
||||
} finally {
|
||||
if (identical(_inFlight, future)) _inFlight = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class HealthRepositoryImpl implements HealthRepository {
|
||||
HealthRepositoryImpl(this._api);
|
||||
|
||||
final ApiClient _api;
|
||||
final HealthStore store = HealthStore();
|
||||
|
||||
@override
|
||||
Future<HealthStatus> getHealth() async {
|
||||
HealthStatus? peekLast() => store.peekLast();
|
||||
|
||||
@override
|
||||
void invalidate() => store.invalidate();
|
||||
|
||||
@override
|
||||
Future<HealthStatus> getHealth({bool force = false}) {
|
||||
return store.get(_fetch, force: force);
|
||||
}
|
||||
|
||||
Future<HealthStatus> _fetch() async {
|
||||
try {
|
||||
final res = await _api.dio.get<dynamic>('/health');
|
||||
final data = res.data;
|
||||
|
||||
@ -54,9 +54,24 @@ class PredictionRepositoryImpl implements PredictionRepository {
|
||||
_stateCache[key] = _StateCacheEntry(etag: nextEtag, data: cached.data);
|
||||
}
|
||||
|
||||
/// Drop ETag so the next `/state` cannot 304 on a stale settled snapshot.
|
||||
static void invalidateStateCache([int? intervalMinutes]) {
|
||||
if (intervalMinutes == null) {
|
||||
_stateCache.clear();
|
||||
return;
|
||||
}
|
||||
_stateCache.remove(_stateCacheKey(intervalMinutes));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<GameStateModel> getState({int? intervalMinutes}) async {
|
||||
Future<GameStateModel> getState({
|
||||
int? intervalMinutes,
|
||||
bool force = false,
|
||||
}) async {
|
||||
final cacheKey = _stateCacheKey(intervalMinutes);
|
||||
if (force) {
|
||||
_stateCache.remove(cacheKey);
|
||||
}
|
||||
final cached = _stateCache[cacheKey];
|
||||
try {
|
||||
final res = await _api.dio.get<Map<String, dynamic>>(
|
||||
@ -65,7 +80,9 @@ class PredictionRepositoryImpl implements PredictionRepository {
|
||||
? {'intervalMinutes': intervalMinutes}
|
||||
: null,
|
||||
options: Options(
|
||||
headers: cached != null ? {'If-None-Match': cached.etag} : null,
|
||||
headers: !force && cached != null
|
||||
? {'If-None-Match': cached.etag}
|
||||
: null,
|
||||
validateStatus: (status) =>
|
||||
status != null &&
|
||||
((status >= 200 && status < 300) || status == 304),
|
||||
|
||||
@ -1,7 +1,12 @@
|
||||
|
||||
/// Health/network status from GET /health.
|
||||
abstract class HealthRepository {
|
||||
Future<HealthStatus> getHealth();
|
||||
Future<HealthStatus> getHealth({bool force = false});
|
||||
|
||||
/// Last successful payload (may be stale); used to hydrate UI instantly.
|
||||
HealthStatus? peekLast();
|
||||
|
||||
void invalidate();
|
||||
}
|
||||
|
||||
class HealthStatus {
|
||||
@ -24,7 +29,8 @@ class HealthStatus {
|
||||
withdrawalsEnabled: json['withdrawalsEnabled'] == true,
|
||||
env: (json['env'] ?? '').toString(),
|
||||
requireWithdrawal2fa: json['requireWithdrawal2fa'] != false,
|
||||
withdrawalNetworkFeeRaw: (json['withdrawalNetworkFeeRaw'] ?? '0').toString(),
|
||||
withdrawalNetworkFeeRaw:
|
||||
(json['withdrawalNetworkFeeRaw'] ?? '0').toString(),
|
||||
);
|
||||
|
||||
bool get isTestnetSafe => network == 'shasta' && !withdrawalsEnabled;
|
||||
|
||||
@ -1,7 +1,10 @@
|
||||
import '../../data/models/prediction_models.dart';
|
||||
|
||||
abstract class PredictionRepository {
|
||||
Future<GameStateModel> getState({int? intervalMinutes});
|
||||
Future<GameStateModel> getState({
|
||||
int? intervalMinutes,
|
||||
bool force = false,
|
||||
});
|
||||
Future<CandlesPageModel> getCandlesPage({
|
||||
int? intervalMinutes,
|
||||
int limit,
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
import '../../../domain/repositories/health_repository.dart';
|
||||
@ -6,6 +7,7 @@ import '../../../l10n/app_strings.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';
|
||||
|
||||
class NetworkScreen extends StatefulWidget {
|
||||
const NetworkScreen({super.key});
|
||||
@ -23,6 +25,11 @@ class _NetworkScreenState extends State<NetworkScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final cached = context.read<HealthRepository>().peekLast();
|
||||
if (cached != null) {
|
||||
_health = cached;
|
||||
_loading = false;
|
||||
}
|
||||
_load();
|
||||
}
|
||||
|
||||
@ -34,7 +41,9 @@ class _NetworkScreenState extends State<NetworkScreen> {
|
||||
if (!force) _error = null;
|
||||
});
|
||||
try {
|
||||
final health = await context.read<HealthRepository>().getHealth();
|
||||
final health = await context.read<HealthRepository>().getHealth(
|
||||
force: force || !keep,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_health = health;
|
||||
@ -57,90 +66,131 @@ class _NetworkScreenState extends State<NetworkScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
return Scaffold(
|
||||
key: const Key('admin_network_screen'),
|
||||
appBar: AppBar(
|
||||
title: Text(s.networkStatus),
|
||||
actions: [
|
||||
IconButton(
|
||||
onPressed: _loading ? null : () => _load(),
|
||||
icon: const Icon(Icons.refresh_rounded),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: _error != null && _health == null
|
||||
? ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(force: true),
|
||||
),
|
||||
],
|
||||
)
|
||||
: _loading && _health == null
|
||||
? ListView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 140),
|
||||
SizedBox(height: 16),
|
||||
PredSkeletonCard(height: 72),
|
||||
],
|
||||
)
|
||||
: ListView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: [
|
||||
PredCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
key: const Key('admin_network_screen'),
|
||||
body: Column(
|
||||
children: [
|
||||
TlotoGradientAppBar(
|
||||
title: s.networkStatus,
|
||||
showBack: true,
|
||||
),
|
||||
Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () => _load(force: true),
|
||||
child: _error != null && _health == null
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: EdgeInsets.fromLTRB(20, 12, 20, 24 + bottomInset),
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
_health!.isTestnetSafe
|
||||
? Icons.verified_rounded
|
||||
: Icons.warning_amber_rounded,
|
||||
color: _health!.isTestnetSafe
|
||||
? AppColors.success
|
||||
: AppColors.warning,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'TRON ${_health!.network.toUpperCase()}',
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_InfoRow(label: s.environment, value: _health!.env),
|
||||
_InfoRow(
|
||||
label: s.withdrawalsBroadcast,
|
||||
value: _health!.withdrawalsEnabled ? s.enabled : s.disabled,
|
||||
),
|
||||
_InfoRow(
|
||||
label: s.withdrawalFee,
|
||||
value: _health!.withdrawalNetworkFeeRaw,
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(force: true),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (!_health!.isTestnetSafe) ...[
|
||||
const SizedBox(height: 16),
|
||||
PredCard(
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.info_outline, color: AppColors.warning),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: Text(s.networkWarning)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
)
|
||||
: _loading && _health == null
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
20,
|
||||
12,
|
||||
20,
|
||||
24 + bottomInset,
|
||||
),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 140),
|
||||
SizedBox(height: 16),
|
||||
PredSkeletonCard(height: 72),
|
||||
],
|
||||
)
|
||||
: ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
20,
|
||||
12,
|
||||
20,
|
||||
24 + bottomInset,
|
||||
),
|
||||
children: [
|
||||
PredCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
_health!.isTestnetSafe
|
||||
? Icons.verified_rounded
|
||||
: Icons.warning_amber_rounded,
|
||||
color: _health!.isTestnetSafe
|
||||
? AppColors.success
|
||||
: AppColors.warning,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'TRON ${_health!.network.toUpperCase()}',
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleLarge
|
||||
?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_InfoRow(
|
||||
label: s.environment,
|
||||
value: _health!.env,
|
||||
),
|
||||
_InfoRow(
|
||||
label: s.withdrawalsBroadcast,
|
||||
value: _health!.withdrawalsEnabled
|
||||
? s.enabled
|
||||
: s.disabled,
|
||||
),
|
||||
_InfoRow(
|
||||
label: s.withdrawalFee,
|
||||
value: _health!.withdrawalNetworkFeeRaw,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (!_health!.isTestnetSafe) ...[
|
||||
const SizedBox(height: 12),
|
||||
PredCard(
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.info_outline,
|
||||
color: AppColors.warning,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: Text(s.networkWarning)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,8 +1,11 @@
|
||||
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/theme/app_theme.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/pred_card.dart';
|
||||
import '../../../shared/widgets/tloto_gradient_app_bar.dart';
|
||||
import '../../auth/bloc/auth_bloc.dart';
|
||||
|
||||
class OptionsScreen extends StatelessWidget {
|
||||
@ -12,59 +15,74 @@ class OptionsScreen extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
final isAdmin = context.read<AuthBloc>().state.isAdmin;
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(s.settings),
|
||||
flexibleSpace: Container(
|
||||
decoration: const BoxDecoration(gradient: AppTheme.goldGradient),
|
||||
),
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: [
|
||||
if (isAdmin) ...[
|
||||
Text(s.adminOnly, style: Theme.of(context).textTheme.titleMedium),
|
||||
const SizedBox(height: 12),
|
||||
_OptionTile(
|
||||
icon: Icons.hub_rounded,
|
||||
title: s.networkStatus,
|
||||
subtitle: s.networkWarning,
|
||||
onTap: () => context.push('/admin/network'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_OptionTile(
|
||||
icon: Icons.people_rounded,
|
||||
title: s.users,
|
||||
subtitle: 'View and manage registered users',
|
||||
onTap: () => context.push('/admin/users'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_OptionTile(
|
||||
icon: Icons.settings_applications_rounded,
|
||||
title: s.settings,
|
||||
subtitle: 'Password policy, tokens, system configuration',
|
||||
onTap: () => context.push('/options/settings'),
|
||||
),
|
||||
] else
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 48),
|
||||
child: Column(
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
final muted = isDark ? AppColors.textMuted : const Color(0xFF94A3B8);
|
||||
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
key: const Key('options_screen'),
|
||||
body: Column(
|
||||
children: [
|
||||
TlotoGradientAppBar(title: s.settings),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
physics: const BouncingScrollPhysics(),
|
||||
padding: EdgeInsets.fromLTRB(20, 16, 20, 24 + bottomInset),
|
||||
children: [
|
||||
Icon(
|
||||
Icons.admin_panel_settings_outlined,
|
||||
size: 48,
|
||||
color: AppColors.textMuted,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'No administrative options available.',
|
||||
style: TextStyle(color: AppColors.textMuted),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
if (isAdmin) ...[
|
||||
Text(
|
||||
s.adminOnly,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_OptionTile(
|
||||
icon: Icons.hub_rounded,
|
||||
title: s.networkStatus,
|
||||
subtitle: s.networkWarning,
|
||||
onTap: () => context.push('/admin/network'),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_OptionTile(
|
||||
icon: Icons.people_rounded,
|
||||
title: s.users,
|
||||
subtitle: s.usersManageSubtitle,
|
||||
onTap: () => context.push('/admin/users'),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
_OptionTile(
|
||||
icon: Icons.settings_applications_rounded,
|
||||
title: s.settings,
|
||||
subtitle: s.systemSettingsSubtitle,
|
||||
onTap: () => context.push('/options/settings'),
|
||||
),
|
||||
] else
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 48),
|
||||
child: Column(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.admin_panel_settings_outlined,
|
||||
size: 48,
|
||||
color: muted,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
s.noAdminOptions,
|
||||
style: TextStyle(color: muted),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@ -85,20 +103,47 @@ class _OptionTile extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
child: ListTile(
|
||||
leading: Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primary.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final color = Theme.of(context).colorScheme.primary;
|
||||
final secondary = isDark ? AppColors.textSecondary : const Color(0xFF475569);
|
||||
final chevron = isDark ? AppColors.textMuted : const Color(0xFF94A3B8);
|
||||
|
||||
return PredCard(
|
||||
onTap: onTap,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: isDark ? 0.15 : 0.12),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Icon(icon, color: color, size: 24),
|
||||
),
|
||||
child: Icon(icon, color: AppColors.primary),
|
||||
),
|
||||
title: Text(title, style: const TextStyle(fontWeight: FontWeight.w600)),
|
||||
subtitle: Text(subtitle, style: Theme.of(context).textTheme.bodySmall),
|
||||
trailing: const Icon(Icons.chevron_right_rounded),
|
||||
onTap: onTap,
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
subtitle,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: secondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Icon(Icons.chevron_right_rounded, color: chevron),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@ -2,12 +2,15 @@
|
||||
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/theme/app_theme.dart';
|
||||
import '../../../data/repositories/admin_repository_impl.dart';
|
||||
import '../../../l10n/app_strings.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 '../../auth/bloc/auth_bloc.dart';
|
||||
|
||||
/// Admin-only screen to view and update password policy and JWT expiry settings.
|
||||
@ -35,6 +38,14 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final cached = widget.adminRepo.peekLastSettings();
|
||||
if (cached != null) {
|
||||
_settings = cached;
|
||||
_minLengthController.text = cached.passwordMinLength.toString();
|
||||
_accessExpiryController.text = cached.accessTokenExpiry;
|
||||
_refreshExpiryController.text = cached.refreshTokenExpiry;
|
||||
_loading = false;
|
||||
}
|
||||
_load();
|
||||
}
|
||||
|
||||
@ -46,6 +57,13 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _applySettings(SystemSettings s) {
|
||||
_settings = s;
|
||||
_minLengthController.text = s.passwordMinLength.toString();
|
||||
_accessExpiryController.text = s.accessTokenExpiry;
|
||||
_refreshExpiryController.text = s.refreshTokenExpiry;
|
||||
}
|
||||
|
||||
/// Fetches current system settings and populates form controllers.
|
||||
Future<void> _load({bool force = false}) async {
|
||||
final keepForm = _settings != null;
|
||||
@ -55,13 +73,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
if (!force) _error = null;
|
||||
});
|
||||
try {
|
||||
final s = await widget.adminRepo.getSettings();
|
||||
final s = await widget.adminRepo.getSettings(force: force || !keepForm);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_settings = s;
|
||||
_minLengthController.text = s.passwordMinLength.toString();
|
||||
_accessExpiryController.text = s.accessTokenExpiry;
|
||||
_refreshExpiryController.text = s.refreshTokenExpiry;
|
||||
_applySettings(s);
|
||||
_loading = false;
|
||||
_retrying = false;
|
||||
_error = null;
|
||||
@ -82,10 +97,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
|
||||
/// Validates form values and submits updated settings to the API.
|
||||
Future<void> _save() async {
|
||||
final s = context.strings;
|
||||
final minLen = int.tryParse(_minLengthController.text.trim());
|
||||
if (minLen == null || minLen < 1 || minLen > 128) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Password minimum length must be between 1 and 128')),
|
||||
SnackBar(content: Text(s.passwordMinLengthInvalid)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
@ -93,7 +109,7 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
final refreshExpiry = _refreshExpiryController.text.trim();
|
||||
if (accessExpiry.isEmpty || refreshExpiry.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Token expiry values are required (e.g. 15m, 7d)')),
|
||||
SnackBar(content: Text(s.tokenExpiryRequired)),
|
||||
);
|
||||
return;
|
||||
}
|
||||
@ -108,14 +124,14 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
accessTokenExpiry: accessExpiry,
|
||||
refreshTokenExpiry: refreshExpiry,
|
||||
);
|
||||
final s = await widget.adminRepo.updateSettings(updated);
|
||||
final result = await widget.adminRepo.updateSettings(updated);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_settings = s;
|
||||
_settings = result;
|
||||
_saving = false;
|
||||
});
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Settings saved')),
|
||||
SnackBar(content: Text(s.settingsSaved)),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
@ -129,9 +145,16 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
}
|
||||
|
||||
Widget _settingsBody(BuildContext context) {
|
||||
final s = context.strings;
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
|
||||
|
||||
if (_error != null && _settings == null) {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: EdgeInsets.fromLTRB(20, 12, 20, 24 + bottomInset),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
@ -143,7 +166,10 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
}
|
||||
if (_loading && _settings == null) {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: EdgeInsets.fromLTRB(20, 12, 20, 24 + bottomInset),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 120),
|
||||
SizedBox(height: 16),
|
||||
@ -153,190 +179,293 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
],
|
||||
);
|
||||
}
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
ExpansionTile(
|
||||
initiallyExpanded: false,
|
||||
leading: Icon(Icons.password_rounded, color: AppColors.goldPrimary),
|
||||
title: Text(
|
||||
'Password policy',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: AppColors.goldPrimary,
|
||||
),
|
||||
),
|
||||
subtitle: const Text('Minimum length and character requirements'),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
TextField(
|
||||
controller: _minLengthController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Minimum length',
|
||||
border: OutlineInputBorder(),
|
||||
helperText: 'Minimum password length (e.g. 8)',
|
||||
),
|
||||
keyboardType: TextInputType.number,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
CheckboxListTile(
|
||||
title: const Text('Require uppercase letter'),
|
||||
value: _settings!.passwordRequireUppercase,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase: v ?? true,
|
||||
passwordRequireLowercase: _settings!.passwordRequireLowercase,
|
||||
passwordRequireNumber: _settings!.passwordRequireNumber,
|
||||
passwordRequireSpecial: _settings!.passwordRequireSpecial,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
CheckboxListTile(
|
||||
title: const Text('Require lowercase letter'),
|
||||
value: _settings!.passwordRequireLowercase,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase: _settings!.passwordRequireUppercase,
|
||||
passwordRequireLowercase: v ?? true,
|
||||
passwordRequireNumber: _settings!.passwordRequireNumber,
|
||||
passwordRequireSpecial: _settings!.passwordRequireSpecial,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
CheckboxListTile(
|
||||
title: const Text('Require number'),
|
||||
value: _settings!.passwordRequireNumber,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase: _settings!.passwordRequireUppercase,
|
||||
passwordRequireLowercase: _settings!.passwordRequireLowercase,
|
||||
passwordRequireNumber: v ?? true,
|
||||
passwordRequireSpecial: _settings!.passwordRequireSpecial,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
CheckboxListTile(
|
||||
title: const Text('Require special character'),
|
||||
value: _settings!.passwordRequireSpecial,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase: _settings!.passwordRequireUppercase,
|
||||
passwordRequireLowercase: _settings!.passwordRequireLowercase,
|
||||
passwordRequireNumber: _settings!.passwordRequireNumber,
|
||||
passwordRequireSpecial: v ?? true,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
ExpansionTile(
|
||||
initiallyExpanded: false,
|
||||
leading: Icon(Icons.timer_outlined, color: AppColors.goldPrimary),
|
||||
title: Text(
|
||||
'Token expiration',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: AppColors.goldPrimary,
|
||||
),
|
||||
),
|
||||
subtitle: const Text('Access and refresh token validity'),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
'Use values like 15m, 1h, 7d (minutes, hours, days). New tokens will use these values.',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _accessExpiryController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Access token expiry',
|
||||
border: OutlineInputBorder(),
|
||||
helperText: 'e.g. 15m, 1h',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _refreshExpiryController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Refresh token expiry',
|
||||
border: OutlineInputBorder(),
|
||||
helperText: 'e.g. 7d, 30d',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: _saving
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Text('Save settings'),
|
||||
),
|
||||
],
|
||||
|
||||
final primary = Theme.of(context).colorScheme.primary;
|
||||
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
20,
|
||||
12,
|
||||
20,
|
||||
24 + bottomInset + keyboardInset,
|
||||
),
|
||||
children: [
|
||||
PredCard(
|
||||
padding: EdgeInsets.zero,
|
||||
child: Theme(
|
||||
data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
|
||||
child: ExpansionTile(
|
||||
initiallyExpanded: false,
|
||||
tilePadding: const EdgeInsets.symmetric(
|
||||
horizontal: 14,
|
||||
vertical: 2,
|
||||
),
|
||||
childrenPadding: const EdgeInsets.fromLTRB(14, 8, 14, 16),
|
||||
leading: Icon(Icons.password_rounded, color: primary),
|
||||
title: Text(
|
||||
s.passwordPolicy,
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
subtitle: Text(
|
||||
s.passwordPolicySubtitle,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
children: [
|
||||
_LabeledField(
|
||||
label: s.passwordMinLength,
|
||||
helperText: s.passwordMinLengthHelper,
|
||||
child: TextField(
|
||||
controller: _minLengthController,
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
decoration: const InputDecoration(),
|
||||
keyboardType: TextInputType.number,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
CheckboxListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text(s.requireUppercase),
|
||||
value: _settings!.passwordRequireUppercase,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase: v ?? true,
|
||||
passwordRequireLowercase:
|
||||
_settings!.passwordRequireLowercase,
|
||||
passwordRequireNumber: _settings!.passwordRequireNumber,
|
||||
passwordRequireSpecial: _settings!.passwordRequireSpecial,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
CheckboxListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text(s.requireLowercase),
|
||||
value: _settings!.passwordRequireLowercase,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase:
|
||||
_settings!.passwordRequireUppercase,
|
||||
passwordRequireLowercase: v ?? true,
|
||||
passwordRequireNumber: _settings!.passwordRequireNumber,
|
||||
passwordRequireSpecial: _settings!.passwordRequireSpecial,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
CheckboxListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text(s.requireNumber),
|
||||
value: _settings!.passwordRequireNumber,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase:
|
||||
_settings!.passwordRequireUppercase,
|
||||
passwordRequireLowercase:
|
||||
_settings!.passwordRequireLowercase,
|
||||
passwordRequireNumber: v ?? true,
|
||||
passwordRequireSpecial: _settings!.passwordRequireSpecial,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
CheckboxListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text(s.requireSpecial),
|
||||
value: _settings!.passwordRequireSpecial,
|
||||
onChanged: (v) => setState(() {
|
||||
_settings = SystemSettings(
|
||||
passwordMinLength: _settings!.passwordMinLength,
|
||||
passwordRequireUppercase:
|
||||
_settings!.passwordRequireUppercase,
|
||||
passwordRequireLowercase:
|
||||
_settings!.passwordRequireLowercase,
|
||||
passwordRequireNumber: _settings!.passwordRequireNumber,
|
||||
passwordRequireSpecial: v ?? true,
|
||||
accessTokenExpiry: _settings!.accessTokenExpiry,
|
||||
refreshTokenExpiry: _settings!.refreshTokenExpiry,
|
||||
);
|
||||
}),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
PredCard(
|
||||
padding: EdgeInsets.zero,
|
||||
child: Theme(
|
||||
data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
|
||||
child: ExpansionTile(
|
||||
initiallyExpanded: false,
|
||||
tilePadding: const EdgeInsets.symmetric(
|
||||
horizontal: 14,
|
||||
vertical: 2,
|
||||
),
|
||||
childrenPadding: const EdgeInsets.fromLTRB(14, 8, 14, 16),
|
||||
leading: Icon(Icons.timer_outlined, color: primary),
|
||||
title: Text(
|
||||
s.tokenExpiration,
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
subtitle: Text(
|
||||
s.tokenExpirationSubtitle,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
children: [
|
||||
Text(
|
||||
s.tokenExpiryHint,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_LabeledField(
|
||||
label: s.accessTokenExpiry,
|
||||
helperText: s.tokenExpiryExampleShort,
|
||||
child: TextField(
|
||||
controller: _accessExpiryController,
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
decoration: const InputDecoration(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_LabeledField(
|
||||
label: s.refreshTokenExpiry,
|
||||
helperText: s.tokenExpiryExampleLong,
|
||||
child: TextField(
|
||||
controller: _refreshExpiryController,
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
decoration: const InputDecoration(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: _saving
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: Text(s.saveSettings),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
|
||||
return BlocBuilder<AuthBloc, AuthState>(
|
||||
buildWhen: (prev, next) => prev.isAdmin != next.isAdmin,
|
||||
builder: (context, authState) {
|
||||
if (!authState.isAdmin) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Settings')),
|
||||
body: const Center(child: Text('Access denied. Admin only.')),
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
body: Column(
|
||||
children: [
|
||||
TlotoGradientAppBar(
|
||||
title: s.settings,
|
||||
showBack: true,
|
||||
),
|
||||
Expanded(
|
||||
child: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text(
|
||||
s.accessDeniedAdmin,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: AppColors.textMuted),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return Scaffold(
|
||||
key: const Key('admin_settings_screen'),
|
||||
appBar: AppBar(
|
||||
title: const Text('Settings'),
|
||||
flexibleSpace: Container(
|
||||
decoration: const BoxDecoration(gradient: AppTheme.goldGradient),
|
||||
),
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back_rounded),
|
||||
onPressed: () => context.pop(),
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
key: const Key('admin_settings_screen'),
|
||||
body: Column(
|
||||
children: [
|
||||
TlotoGradientAppBar(
|
||||
title: s.settings,
|
||||
showBack: true,
|
||||
),
|
||||
Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () => _load(force: true),
|
||||
child: _settingsBody(context),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: _settingsBody(context),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Label + field outside [InputDecoration] so ExpansionTile does not clip it.
|
||||
class _LabeledField extends StatelessWidget {
|
||||
const _LabeledField({
|
||||
required this.label,
|
||||
required this.child,
|
||||
this.helperText,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final Widget child;
|
||||
final String? helperText;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final primary = Theme.of(context).colorScheme.primary;
|
||||
final muted = Theme.of(context).brightness == Brightness.dark
|
||||
? AppColors.textMuted
|
||||
: const Color(0xFF64748B);
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
label,
|
||||
style: Theme.of(context).textTheme.labelLarge?.copyWith(
|
||||
color: primary,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
child,
|
||||
if (helperText != null) ...[
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
helperText!,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(color: muted),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,12 +2,15 @@
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../../../core/theme/app_theme.dart';
|
||||
import '../../../data/repositories/admin_repository_impl.dart';
|
||||
import '../../../l10n/app_strings.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';
|
||||
|
||||
/// Full user detail view for admins: profile, account flags, and balances.
|
||||
class UserDetailScreen extends StatefulWidget {
|
||||
@ -34,6 +37,11 @@ class _UserDetailScreenState extends State<UserDetailScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final cached = widget.adminRepo.peekLastUserDetails(widget.userId);
|
||||
if (cached != null) {
|
||||
_data = cached;
|
||||
_loading = false;
|
||||
}
|
||||
_load();
|
||||
}
|
||||
|
||||
@ -46,7 +54,10 @@ class _UserDetailScreenState extends State<UserDetailScreen> {
|
||||
if (!force) _error = null;
|
||||
});
|
||||
try {
|
||||
final data = await widget.adminRepo.getUserDetails(widget.userId);
|
||||
final data = await widget.adminRepo.getUserDetails(
|
||||
widget.userId,
|
||||
force: force || !keepData,
|
||||
);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_data = data;
|
||||
@ -70,31 +81,47 @@ class _UserDetailScreenState extends State<UserDetailScreen> {
|
||||
|
||||
/// Confirms and persists an account flag change, then reloads details.
|
||||
Future<void> _updateFlag(String flagName, bool newValue) async {
|
||||
final s = context.strings;
|
||||
final userLabel = _data?.user.email ?? widget.userId;
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('Confirm change'),
|
||||
title: Text(s.confirmChange),
|
||||
content: Text(
|
||||
'Set "$flagName" to ${newValue ? "enabled" : "disabled"}?',
|
||||
s.confirmFlagChange(
|
||||
flagName: flagName,
|
||||
enabled: newValue,
|
||||
userLabel: userLabel,
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: const Text('Cancel')),
|
||||
FilledButton(onPressed: () => Navigator.of(ctx).pop(true), child: const Text('Confirm')),
|
||||
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 || _data == null) return;
|
||||
try {
|
||||
if (flagName == 'isEnabled') {
|
||||
await widget.adminRepo.updateUserFlags(widget.userId, isEnabled: newValue);
|
||||
await widget.adminRepo
|
||||
.updateUserFlags(widget.userId, isEnabled: newValue);
|
||||
} else if (flagName == 'isAccountNonExpired') {
|
||||
await widget.adminRepo.updateUserFlags(widget.userId, isAccountNonExpired: newValue);
|
||||
await widget.adminRepo
|
||||
.updateUserFlags(widget.userId, isAccountNonExpired: newValue);
|
||||
} else if (flagName == 'isAccountNonLocked') {
|
||||
await widget.adminRepo.updateUserFlags(widget.userId, isAccountNonLocked: newValue);
|
||||
await widget.adminRepo
|
||||
.updateUserFlags(widget.userId, isAccountNonLocked: newValue);
|
||||
} else if (flagName == 'isCredentialsNonExpired') {
|
||||
await widget.adminRepo.updateUserFlags(widget.userId, isCredentialsNonExpired: newValue);
|
||||
await widget.adminRepo
|
||||
.updateUserFlags(widget.userId, isCredentialsNonExpired: newValue);
|
||||
}
|
||||
if (mounted) _load();
|
||||
if (mounted) _load(force: true);
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
@ -104,87 +131,221 @@ class _UserDetailScreenState extends State<UserDetailScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
Widget _skeletonBody() {
|
||||
String _formatCreated(String createdAt) {
|
||||
if (createdAt.isEmpty) return '—';
|
||||
final dt = DateTime.tryParse(createdAt);
|
||||
return dt != null ? DateFormat.yMd().add_Hm().format(dt.toLocal()) : createdAt;
|
||||
}
|
||||
|
||||
Widget _body(BuildContext context) {
|
||||
final s = context.strings;
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
final padding = EdgeInsets.fromLTRB(20, 12, 20, 24 + bottomInset);
|
||||
|
||||
if (_error != null && _data == null) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: padding,
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(force: true),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
if (_loading && _data == null) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: padding,
|
||||
children: const [
|
||||
PredSkeletonCard(height: 160),
|
||||
SizedBox(height: 12),
|
||||
PredSkeletonCard(height: 140),
|
||||
SizedBox(height: 12),
|
||||
PredSkeletonCard(height: 100),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
if (_data == null) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: padding,
|
||||
children: [
|
||||
PredCard(
|
||||
child: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 24),
|
||||
child: Text(
|
||||
s.userNotFound,
|
||||
style: TextStyle(color: AppColors.textMuted),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
final user = _data!.user;
|
||||
final email = user.email?.isNotEmpty == true ? user.email! : '—';
|
||||
final initial = email != '—'
|
||||
? email.substring(0, 1).toUpperCase()
|
||||
: user.id.substring(0, 1).toUpperCase();
|
||||
final primary = Theme.of(context).colorScheme.primary;
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 160),
|
||||
SizedBox(height: 16),
|
||||
PredSkeletonCard(height: 140),
|
||||
SizedBox(height: 16),
|
||||
PredSkeletonCard(height: 100),
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: padding,
|
||||
children: [
|
||||
PredCard(
|
||||
child: Row(
|
||||
children: [
|
||||
CircleAvatar(
|
||||
radius: 28,
|
||||
backgroundColor:
|
||||
primary.withValues(alpha: isDark ? 0.25 : 0.15),
|
||||
child: Text(
|
||||
initial,
|
||||
style: TextStyle(
|
||||
color: primary,
|
||||
fontWeight: FontWeight.w800,
|
||||
fontSize: 22,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
email,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
user.roleName,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: isDark
|
||||
? AppColors.textSecondary
|
||||
: const Color(0xFF475569),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_Section(
|
||||
title: s.profileSectionPersonal,
|
||||
children: [
|
||||
_InfoRow(label: s.email, value: email),
|
||||
_InfoRow(label: s.userIdLabel, value: user.id),
|
||||
_InfoRow(label: s.roleLabel, value: user.roleName),
|
||||
_InfoRow(
|
||||
label: s.createdAtLabel,
|
||||
value: _formatCreated(user.createdAt),
|
||||
),
|
||||
_InfoRow(
|
||||
label: s.emailVerifiedLabel,
|
||||
value: user.emailVerified ? s.yes : s.no,
|
||||
),
|
||||
_InfoRow(
|
||||
label: s.totpEnabledLabel,
|
||||
value: user.totpEnabled ? s.yes : s.no,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_Section(
|
||||
title: s.accountStatus,
|
||||
children: [
|
||||
_SwitchRow(
|
||||
label: s.enabled,
|
||||
value: user.isEnabled,
|
||||
onChanged: (v) => _updateFlag('isEnabled', v),
|
||||
),
|
||||
_SwitchRow(
|
||||
label: s.accountNonExpired,
|
||||
value: user.isAccountNonExpired,
|
||||
onChanged: (v) => _updateFlag('isAccountNonExpired', v),
|
||||
),
|
||||
_SwitchRow(
|
||||
label: s.accountNonLocked,
|
||||
value: user.isAccountNonLocked,
|
||||
onChanged: (v) => _updateFlag('isAccountNonLocked', v),
|
||||
),
|
||||
_SwitchRow(
|
||||
label: s.credentialsNonExpired,
|
||||
value: user.isCredentialsNonExpired,
|
||||
onChanged: (v) => _updateFlag('isCredentialsNonExpired', v),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_Section(
|
||||
title: s.balances,
|
||||
children: _data!.balances.isEmpty
|
||||
? [
|
||||
Text(
|
||||
s.noBalances,
|
||||
style: TextStyle(color: AppColors.textMuted),
|
||||
),
|
||||
]
|
||||
: _data!.balances
|
||||
.map(
|
||||
(b) => _BalanceRow(
|
||||
walletName: b.walletName,
|
||||
available: b.available,
|
||||
locked: b.locked,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
key: const Key('admin_user_detail_screen'),
|
||||
appBar: AppBar(
|
||||
title: const Text('User details'),
|
||||
flexibleSpace: Container(
|
||||
decoration: const BoxDecoration(gradient: AppTheme.goldGradient),
|
||||
),
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back_rounded),
|
||||
onPressed: () => context.pop(),
|
||||
final s = context.strings;
|
||||
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
key: const Key('admin_user_detail_screen'),
|
||||
body: Column(
|
||||
children: [
|
||||
TlotoGradientAppBar(
|
||||
title: s.userDetails,
|
||||
showBack: true,
|
||||
),
|
||||
Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () => _load(force: true),
|
||||
child: _body(context),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: _error != null && _data == null
|
||||
? ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(force: true),
|
||||
),
|
||||
],
|
||||
)
|
||||
: _loading && _data == null
|
||||
? _skeletonBody()
|
||||
: _data == null
|
||||
? const Center(child: Text('User not found'))
|
||||
: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_Section(title: 'Profile', children: [
|
||||
_Row(label: 'Email', value: _data!.user.email ?? '—'),
|
||||
_Row(label: 'User ID', value: _data!.user.id),
|
||||
_Row(label: 'Role', value: _data!.user.roleName),
|
||||
_Row(
|
||||
label: 'Created',
|
||||
value: _data!.user.createdAt.isNotEmpty
|
||||
? (DateTime.tryParse(_data!.user.createdAt) != null
|
||||
? DateFormat.yMd().add_Hm().format(DateTime.parse(_data!.user.createdAt))
|
||||
: _data!.user.createdAt)
|
||||
: '—',
|
||||
),
|
||||
_Row(label: 'Email verified', value: _data!.user.emailVerified ? 'Yes' : 'No'),
|
||||
_Row(label: 'TOTP enabled', value: _data!.user.totpEnabled ? 'Yes' : 'No'),
|
||||
]),
|
||||
const SizedBox(height: 24),
|
||||
_Section(title: 'Account status', children: [
|
||||
_SwitchRow(label: 'Enabled', value: _data!.user.isEnabled, onChanged: (v) => _updateFlag('isEnabled', v)),
|
||||
_SwitchRow(label: 'Account non expired', value: _data!.user.isAccountNonExpired, onChanged: (v) => _updateFlag('isAccountNonExpired', v)),
|
||||
_SwitchRow(label: 'Account non locked', value: _data!.user.isAccountNonLocked, onChanged: (v) => _updateFlag('isAccountNonLocked', v)),
|
||||
_SwitchRow(label: 'Credentials non expired', value: _data!.user.isCredentialsNonExpired, onChanged: (v) => _updateFlag('isCredentialsNonExpired', v)),
|
||||
]),
|
||||
const SizedBox(height: 24),
|
||||
_Section(
|
||||
title: 'Balances',
|
||||
children: _data!.balances.isEmpty
|
||||
? [const Padding(padding: EdgeInsets.all(8), child: Text('No balances'))]
|
||||
: _data!.balances
|
||||
.map((b) => _BalanceRow(walletName: b.walletName, available: b.available, locked: b.locked))
|
||||
.toList(),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -197,43 +358,58 @@ class _Section extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
...children,
|
||||
],
|
||||
),
|
||||
return PredCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
...children,
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Read-only label/value row for profile fields.
|
||||
class _Row extends StatelessWidget {
|
||||
const _Row({required this.label, required this.value});
|
||||
class _InfoRow extends StatelessWidget {
|
||||
const _InfoRow({required this.label, required this.value});
|
||||
final String label;
|
||||
final String value;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final labelColor =
|
||||
isDark ? AppColors.textSecondary : const Color(0xFF64748B);
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
padding: const EdgeInsets.only(bottom: 10),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 140,
|
||||
child: Text(label, style: Theme.of(context).textTheme.bodyMedium?.copyWith(color: Colors.grey.shade700)),
|
||||
width: 130,
|
||||
child: Text(
|
||||
label,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: labelColor,
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: SelectableText(
|
||||
value,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(child: SelectableText(value, style: Theme.of(context).textTheme.bodyMedium)),
|
||||
],
|
||||
),
|
||||
);
|
||||
@ -242,7 +418,11 @@ class _Row extends StatelessWidget {
|
||||
|
||||
/// Editable account flag with a switch control.
|
||||
class _SwitchRow extends StatelessWidget {
|
||||
const _SwitchRow({required this.label, required this.value, required this.onChanged});
|
||||
const _SwitchRow({
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.onChanged,
|
||||
});
|
||||
final String label;
|
||||
final bool value;
|
||||
final ValueChanged<bool> onChanged;
|
||||
@ -250,11 +430,13 @@ class _SwitchRow extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
padding: const EdgeInsets.only(bottom: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(child: Text(label, style: Theme.of(context).textTheme.bodyMedium)),
|
||||
Switch(value: value, onChanged: (v) => onChanged(v)),
|
||||
Expanded(
|
||||
child: Text(label, style: Theme.of(context).textTheme.bodyMedium),
|
||||
),
|
||||
Switch(value: value, onChanged: onChanged),
|
||||
],
|
||||
),
|
||||
);
|
||||
@ -263,22 +445,44 @@ class _SwitchRow extends StatelessWidget {
|
||||
|
||||
/// Displays available and locked balance for one wallet type.
|
||||
class _BalanceRow extends StatelessWidget {
|
||||
const _BalanceRow({required this.walletName, required this.available, required this.locked});
|
||||
const _BalanceRow({
|
||||
required this.walletName,
|
||||
required this.available,
|
||||
required this.locked,
|
||||
});
|
||||
final String walletName;
|
||||
final String available;
|
||||
final String locked;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final muted =
|
||||
isDark ? AppColors.textSecondary : const Color(0xFF64748B);
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
padding: const EdgeInsets.only(bottom: 14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(walletName, style: Theme.of(context).textTheme.titleSmall?.copyWith(fontWeight: FontWeight.w600)),
|
||||
const SizedBox(height: 4),
|
||||
Text('Available: $available', style: Theme.of(context).textTheme.bodyMedium),
|
||||
Text('Locked: $locked', style: Theme.of(context).textTheme.bodyMedium),
|
||||
Text(
|
||||
walletName,
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
'${s.availableBalance}: $available',
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
Text(
|
||||
'${s.lockedBalance}: $locked',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: muted,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@ -1,13 +1,19 @@
|
||||
/// Admin presentation: searchable paginated user list with account flag toggles.
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../../../core/theme/app_theme.dart';
|
||||
import '../../../data/repositories/admin_repository_impl.dart';
|
||||
import '../../../l10n/app_strings.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';
|
||||
|
||||
/// Lists registered users with search, pagination, and inline flag management.
|
||||
class UserManagementScreen extends StatefulWidget {
|
||||
@ -25,9 +31,14 @@ class UserManagementScreen extends StatefulWidget {
|
||||
/// Handles search, pagination, and flag updates for the user list.
|
||||
class _UserManagementScreenState extends State<UserManagementScreen> {
|
||||
final _searchController = TextEditingController();
|
||||
final _searchFocus = FocusNode();
|
||||
Timer? _debounce;
|
||||
int _loadToken = 0;
|
||||
|
||||
List<AdminUserListItem> _users = [];
|
||||
int _total = 0;
|
||||
bool _loading = true;
|
||||
bool _searching = false;
|
||||
bool _retrying = false;
|
||||
String? _error;
|
||||
int _offset = 0;
|
||||
@ -36,69 +47,112 @@ class _UserManagementScreenState extends State<UserManagementScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final cached = widget.adminRepo.peekLastUsers(
|
||||
limit: _pageSize,
|
||||
offset: 0,
|
||||
);
|
||||
if (cached != null) {
|
||||
_users = cached.users;
|
||||
_total = cached.total;
|
||||
_loading = false;
|
||||
}
|
||||
_searchController.addListener(_onSearchChanged);
|
||||
_load();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_debounce?.cancel();
|
||||
_searchController.removeListener(_onSearchChanged);
|
||||
_searchController.dispose();
|
||||
_searchFocus.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onSearchChanged() {
|
||||
setState(() {}); // refresh clear icon
|
||||
_debounce?.cancel();
|
||||
_debounce = Timer(const Duration(milliseconds: 300), () {
|
||||
if (!mounted) return;
|
||||
_load();
|
||||
});
|
||||
}
|
||||
|
||||
void _clearSearch() {
|
||||
_debounce?.cancel();
|
||||
if (_searchController.text.isEmpty) return;
|
||||
_searchController.clear();
|
||||
_load();
|
||||
}
|
||||
|
||||
/// Loads a page of users from the API, optionally resetting pagination.
|
||||
Future<void> _load({bool resetOffset = true, bool force = false}) async {
|
||||
if (resetOffset) _offset = 0;
|
||||
final token = ++_loadToken;
|
||||
final query = _searchController.text.trim();
|
||||
final keepList = _users.isNotEmpty;
|
||||
final isSearchReload = keepList && (resetOffset || force);
|
||||
setState(() {
|
||||
_loading = !keepList;
|
||||
_searching = isSearchReload;
|
||||
_retrying = force && !keepList;
|
||||
if (!force) _error = null;
|
||||
});
|
||||
try {
|
||||
final result = await widget.adminRepo.listUsers(
|
||||
search: _searchController.text.trim().isEmpty ? null : _searchController.text.trim(),
|
||||
search: query.isEmpty ? null : query,
|
||||
limit: _pageSize,
|
||||
offset: _offset,
|
||||
force: force || !keepList,
|
||||
);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_users = result.users;
|
||||
_total = result.total;
|
||||
_loading = false;
|
||||
_retrying = false;
|
||||
_error = null;
|
||||
});
|
||||
}
|
||||
if (!mounted || token != _loadToken) return;
|
||||
setState(() {
|
||||
_users = result.users;
|
||||
_total = result.total;
|
||||
_loading = false;
|
||||
_searching = false;
|
||||
_retrying = false;
|
||||
_error = null;
|
||||
});
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_loading = false;
|
||||
_retrying = false;
|
||||
if (_users.isEmpty) {
|
||||
_error = e.toString().replaceFirst('Exception: ', '');
|
||||
}
|
||||
});
|
||||
}
|
||||
if (!mounted || token != _loadToken) return;
|
||||
setState(() {
|
||||
_loading = false;
|
||||
_searching = false;
|
||||
_retrying = false;
|
||||
if (_users.isEmpty) {
|
||||
_error = e.toString().replaceFirst('Exception: ', '');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Confirms and persists a Spring Security-style account flag change.
|
||||
Future<void> _updateFlag(AdminUserListItem user, String flagName, bool newValue) async {
|
||||
Future<void> _updateFlag(
|
||||
AdminUserListItem user,
|
||||
String flagName,
|
||||
bool newValue,
|
||||
) async {
|
||||
final s = context.strings;
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('Confirm change'),
|
||||
title: Text(s.confirmChange),
|
||||
content: Text(
|
||||
'Set "$flagName" to ${newValue ? "enabled" : "disabled"} for user ${user.email ?? user.id}?',
|
||||
s.confirmFlagChange(
|
||||
flagName: flagName,
|
||||
enabled: newValue,
|
||||
userLabel: user.email ?? user.id,
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(ctx).pop(false),
|
||||
child: const Text('Cancel'),
|
||||
child: Text(s.cancel),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(ctx).pop(true),
|
||||
child: const Text('Confirm'),
|
||||
child: Text(s.confirmAction),
|
||||
),
|
||||
],
|
||||
),
|
||||
@ -108,11 +162,14 @@ class _UserManagementScreenState extends State<UserManagementScreen> {
|
||||
if (flagName == 'isEnabled') {
|
||||
await widget.adminRepo.updateUserFlags(user.id, isEnabled: newValue);
|
||||
} else if (flagName == 'isAccountNonExpired') {
|
||||
await widget.adminRepo.updateUserFlags(user.id, isAccountNonExpired: newValue);
|
||||
await widget.adminRepo
|
||||
.updateUserFlags(user.id, isAccountNonExpired: newValue);
|
||||
} else if (flagName == 'isAccountNonLocked') {
|
||||
await widget.adminRepo.updateUserFlags(user.id, isAccountNonLocked: newValue);
|
||||
await widget.adminRepo
|
||||
.updateUserFlags(user.id, isAccountNonLocked: newValue);
|
||||
} else if (flagName == 'isCredentialsNonExpired') {
|
||||
await widget.adminRepo.updateUserFlags(user.id, isCredentialsNonExpired: newValue);
|
||||
await widget.adminRepo
|
||||
.updateUserFlags(user.id, isCredentialsNonExpired: newValue);
|
||||
}
|
||||
if (mounted) _load(resetOffset: false);
|
||||
} catch (e) {
|
||||
@ -133,112 +190,191 @@ class _UserManagementScreenState extends State<UserManagementScreen> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
key: const Key('admin_users_screen'),
|
||||
appBar: AppBar(
|
||||
title: const Text('User Management'),
|
||||
flexibleSpace: Container(
|
||||
decoration: const BoxDecoration(gradient: AppTheme.goldGradient),
|
||||
),
|
||||
),
|
||||
body: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _searchController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Search by ID or email',
|
||||
prefixIcon: Icon(Icons.search_rounded),
|
||||
border: OutlineInputBorder(),
|
||||
isDense: true,
|
||||
),
|
||||
onSubmitted: (_) => _load(),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
FilledButton.icon(
|
||||
onPressed: _loading ? null : () => _load(),
|
||||
icon: const Icon(Icons.search_rounded, size: 20),
|
||||
label: const Text('Search'),
|
||||
),
|
||||
],
|
||||
final s = context.strings;
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
final primary = Theme.of(context).colorScheme.primary;
|
||||
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
key: const Key('admin_users_screen'),
|
||||
body: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
TlotoGradientAppBar(
|
||||
title: s.userManagement,
|
||||
showBack: true,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: _error != null && _users.isEmpty
|
||||
? ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(force: true),
|
||||
),
|
||||
],
|
||||
)
|
||||
: _loading && _users.isEmpty
|
||||
? ListView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
],
|
||||
)
|
||||
: _users.isEmpty
|
||||
? const Center(child: Text('No users found'))
|
||||
: ListView.builder(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
itemCount: _users.length,
|
||||
itemBuilder: (context, index) {
|
||||
final u = _users[index];
|
||||
return _UserExpansionTile(
|
||||
user: u,
|
||||
formatCreated: _formatCreated,
|
||||
onUpdateFlag: _updateFlag,
|
||||
onViewDetails: () => context.push('/admin/users/${u.id}'),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
if (_total > 0 && !(_loading && _users.isEmpty))
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
IconButton(
|
||||
onPressed: _offset <= 0 || _loading
|
||||
? null
|
||||
: () {
|
||||
setState(() => _offset = (_offset - _pageSize).clamp(0, _total));
|
||||
_load(resetOffset: false);
|
||||
},
|
||||
icon: const Icon(Icons.chevron_left_rounded),
|
||||
padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),
|
||||
child: PredCard(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
|
||||
child: TextField(
|
||||
key: const Key('admin_users_search'),
|
||||
controller: _searchController,
|
||||
focusNode: _searchFocus,
|
||||
textInputAction: TextInputAction.search,
|
||||
decoration: InputDecoration(
|
||||
hintText: s.usersSearchHint,
|
||||
helperText: s.usersSearchHelper,
|
||||
helperMaxLines: 2,
|
||||
border: InputBorder.none,
|
||||
enabledBorder: InputBorder.none,
|
||||
focusedBorder: InputBorder.none,
|
||||
filled: false,
|
||||
prefixIcon: const Icon(Icons.search_rounded),
|
||||
suffixIcon: _searchController.text.isNotEmpty
|
||||
? IconButton(
|
||||
tooltip: s.cancel,
|
||||
icon: const Icon(Icons.clear_rounded),
|
||||
onPressed: _clearSearch,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
Text('${_offset + 1}-${(_offset + _users.length).clamp(0, _total)} of $_total'),
|
||||
IconButton(
|
||||
onPressed: _offset + _users.length >= _total || _loading
|
||||
? null
|
||||
: () {
|
||||
setState(() => _offset += _pageSize);
|
||||
_load(resetOffset: false);
|
||||
},
|
||||
icon: const Icon(Icons.chevron_right_rounded),
|
||||
),
|
||||
],
|
||||
onSubmitted: (_) {
|
||||
_debounce?.cancel();
|
||||
_load();
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
if (_searching)
|
||||
LinearProgressIndicator(
|
||||
minHeight: 2,
|
||||
color: primary,
|
||||
),
|
||||
Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () => _load(force: true),
|
||||
child: _error != null && _users.isEmpty
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
20,
|
||||
12,
|
||||
20,
|
||||
24 + bottomInset,
|
||||
),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(force: true),
|
||||
),
|
||||
],
|
||||
)
|
||||
: _loading && _users.isEmpty
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
20,
|
||||
12,
|
||||
20,
|
||||
24 + bottomInset,
|
||||
),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
],
|
||||
)
|
||||
: _users.isEmpty
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
20,
|
||||
48,
|
||||
20,
|
||||
24 + bottomInset,
|
||||
),
|
||||
children: [
|
||||
Icon(
|
||||
Icons.people_outline_rounded,
|
||||
size: 48,
|
||||
color: AppColors.textMuted,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
s.noUsersFound,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: AppColors.textMuted),
|
||||
),
|
||||
],
|
||||
)
|
||||
: ListView.builder(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
20,
|
||||
12,
|
||||
20,
|
||||
8 + bottomInset,
|
||||
),
|
||||
itemCount: _users.length,
|
||||
itemBuilder: (context, index) {
|
||||
final u = _users[index];
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 10),
|
||||
child: _UserExpansionTile(
|
||||
user: u,
|
||||
formatCreated: _formatCreated,
|
||||
onUpdateFlag: _updateFlag,
|
||||
onViewDetails: () =>
|
||||
context.push('/admin/users/${u.id}'),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_total > 0 && !(_loading && _users.isEmpty))
|
||||
Padding(
|
||||
padding: EdgeInsets.fromLTRB(8, 0, 8, 8 + bottomInset),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
IconButton(
|
||||
onPressed: _offset <= 0 || _loading || _searching
|
||||
? null
|
||||
: () {
|
||||
setState(
|
||||
() => _offset =
|
||||
(_offset - _pageSize).clamp(0, _total),
|
||||
);
|
||||
_load(resetOffset: false);
|
||||
},
|
||||
icon: const Icon(Icons.chevron_left_rounded),
|
||||
),
|
||||
Text(
|
||||
'${_offset + 1}-${(_offset + _users.length).clamp(0, _total)} of $_total',
|
||||
),
|
||||
IconButton(
|
||||
onPressed: _offset + _users.length >= _total ||
|
||||
_loading ||
|
||||
_searching
|
||||
? null
|
||||
: () {
|
||||
setState(() => _offset += _pageSize);
|
||||
_load(resetOffset: false);
|
||||
},
|
||||
icon: const Icon(Icons.chevron_right_rounded),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@ -260,48 +396,76 @@ class _UserExpansionTile extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final primary = Theme.of(context).colorScheme.primary;
|
||||
final email = user.email?.isNotEmpty == true ? user.email! : '—';
|
||||
final initial = email != '—' ? email.substring(0, 1).toUpperCase() : user.id.substring(0, 1).toUpperCase();
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
child: ExpansionTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: AppColors.goldPrimary.withValues(alpha: 0.3),
|
||||
child: Text(
|
||||
initial,
|
||||
style: const TextStyle(color: Colors.black87, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
email,
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(fontWeight: FontWeight.w600),
|
||||
),
|
||||
subtitle: Text(
|
||||
'${user.id} · ${user.roleName}',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text('Created: ${formatCreated(user.createdAt)}', style: Theme.of(context).textTheme.bodySmall),
|
||||
const SizedBox(height: 12),
|
||||
_FlagRow(label: 'Enabled', value: user.isEnabled, onChanged: (v) => onUpdateFlag(user, 'isEnabled', v)),
|
||||
_FlagRow(label: 'Account non expired', value: user.isAccountNonExpired, onChanged: (v) => onUpdateFlag(user, 'isAccountNonExpired', v)),
|
||||
_FlagRow(label: 'Account non locked', value: user.isAccountNonLocked, onChanged: (v) => onUpdateFlag(user, 'isAccountNonLocked', v)),
|
||||
_FlagRow(label: 'Credentials non expired', value: user.isCredentialsNonExpired, onChanged: (v) => onUpdateFlag(user, 'isCredentialsNonExpired', v)),
|
||||
const SizedBox(height: 12),
|
||||
FilledButton.icon(
|
||||
onPressed: onViewDetails,
|
||||
icon: const Icon(Icons.person_outline_rounded, size: 20),
|
||||
label: const Text('View full details & balance'),
|
||||
),
|
||||
],
|
||||
final initial = email != '—'
|
||||
? email.substring(0, 1).toUpperCase()
|
||||
: user.id.substring(0, 1).toUpperCase();
|
||||
|
||||
return PredCard(
|
||||
padding: EdgeInsets.zero,
|
||||
child: Theme(
|
||||
data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
|
||||
child: ExpansionTile(
|
||||
tilePadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 2),
|
||||
childrenPadding: const EdgeInsets.fromLTRB(14, 0, 14, 16),
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: primary.withValues(alpha: isDark ? 0.25 : 0.15),
|
||||
child: Text(
|
||||
initial,
|
||||
style: TextStyle(
|
||||
color: primary,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
title: Text(
|
||||
email,
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
subtitle: Text(
|
||||
'${user.id} · ${user.roleName}',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
children: [
|
||||
Text(
|
||||
'${s.createdAtLabel}: ${formatCreated(user.createdAt)}',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_FlagRow(
|
||||
label: s.enabled,
|
||||
value: user.isEnabled,
|
||||
onChanged: (v) => onUpdateFlag(user, 'isEnabled', v),
|
||||
),
|
||||
_FlagRow(
|
||||
label: s.accountNonExpired,
|
||||
value: user.isAccountNonExpired,
|
||||
onChanged: (v) => onUpdateFlag(user, 'isAccountNonExpired', v),
|
||||
),
|
||||
_FlagRow(
|
||||
label: s.accountNonLocked,
|
||||
value: user.isAccountNonLocked,
|
||||
onChanged: (v) => onUpdateFlag(user, 'isAccountNonLocked', v),
|
||||
),
|
||||
_FlagRow(
|
||||
label: s.credentialsNonExpired,
|
||||
value: user.isCredentialsNonExpired,
|
||||
onChanged: (v) =>
|
||||
onUpdateFlag(user, 'isCredentialsNonExpired', v),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
FilledButton.icon(
|
||||
onPressed: onViewDetails,
|
||||
icon: const Icon(Icons.person_outline_rounded, size: 20),
|
||||
label: Text(s.viewUserDetails),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@ -309,7 +473,11 @@ class _UserExpansionTile extends StatelessWidget {
|
||||
|
||||
/// Label and switch row for a single account status flag.
|
||||
class _FlagRow extends StatelessWidget {
|
||||
const _FlagRow({required this.label, required this.value, required this.onChanged});
|
||||
const _FlagRow({
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.onChanged,
|
||||
});
|
||||
final String label;
|
||||
final bool value;
|
||||
final ValueChanged<bool> onChanged;
|
||||
@ -320,8 +488,10 @@ class _FlagRow extends StatelessWidget {
|
||||
padding: const EdgeInsets.only(bottom: 6),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(child: Text(label, style: Theme.of(context).textTheme.bodyMedium)),
|
||||
Switch(value: value, onChanged: (v) => onChanged(v)),
|
||||
Expanded(
|
||||
child: Text(label, style: Theme.of(context).textTheme.bodyMedium),
|
||||
),
|
||||
Switch(value: value, onChanged: onChanged),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
@ -1,13 +1,16 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../core/di/injection.dart';
|
||||
import '../../../domain/repositories/repositories.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/app_snackbar.dart';
|
||||
import '../../../shared/widgets/pred_button.dart';
|
||||
import '../../../shared/widgets/pred_card.dart';
|
||||
import '../../../shared/widgets/pred_text_field.dart';
|
||||
import '../../../shared/widgets/tloto_gradient_app_bar.dart';
|
||||
import '../../welcome/utils/welcome_navigation.dart';
|
||||
|
||||
class ForgotPasswordScreen extends StatefulWidget {
|
||||
@ -75,62 +78,94 @@ class _ForgotPasswordScreenState extends State<ForgotPasswordScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
return Scaffold(
|
||||
key: const Key('forgot_password_screen'),
|
||||
appBar: AppBar(
|
||||
leading: welcomeBackButton(context),
|
||||
title: Text(s.forgotPassword),
|
||||
),
|
||||
body: SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: _sent
|
||||
? Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Icon(Icons.mark_email_read_outlined, size: 64),
|
||||
const SizedBox(height: 16),
|
||||
Text(s.resetEmailSent, textAlign: TextAlign.center),
|
||||
const SizedBox(height: 24),
|
||||
PredPrimaryButton(
|
||||
key: const Key('forgot_password_back_to_login'),
|
||||
label: s.signIn,
|
||||
onPressed: () => context.go('/login'),
|
||||
),
|
||||
],
|
||||
)
|
||||
: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(s.forgotPasswordHint),
|
||||
const SizedBox(height: 20),
|
||||
PredTextField(
|
||||
key: const Key('forgot_password_email'),
|
||||
controller: _emailController,
|
||||
label: s.email,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
enabled: !_loading,
|
||||
textInputAction: TextInputAction.done,
|
||||
autofillHints: const [AutofillHints.email],
|
||||
onSubmitted: _loading ? null : (_) => _submit(),
|
||||
),
|
||||
if (_error != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
_error!,
|
||||
key: const Key('forgot_password_error'),
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 24),
|
||||
PredPrimaryButton(
|
||||
key: const Key('forgot_password_submit'),
|
||||
label: s.sendResetLink,
|
||||
loading: _loading,
|
||||
onPressed: _submit,
|
||||
),
|
||||
],
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
|
||||
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
key: const Key('forgot_password_screen'),
|
||||
body: Column(
|
||||
children: [
|
||||
TlotoGradientAppBar(
|
||||
title: s.forgotPassword,
|
||||
showBack: true,
|
||||
onBack: () => popToWelcomeOrPrevious(context),
|
||||
),
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
20,
|
||||
16,
|
||||
20,
|
||||
24 + bottomInset + keyboardInset,
|
||||
),
|
||||
child: PredCard(
|
||||
child: _sent
|
||||
? Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.mark_email_read_outlined,
|
||||
size: 64,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
s.resetEmailSent,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyLarge,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
PredPrimaryButton(
|
||||
key: const Key('forgot_password_back_to_login'),
|
||||
label: s.signIn,
|
||||
onPressed: () => context.go('/login'),
|
||||
),
|
||||
],
|
||||
)
|
||||
: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
s.forgotPasswordHint,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
PredTextField(
|
||||
key: const Key('forgot_password_email'),
|
||||
controller: _emailController,
|
||||
label: s.email,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
enabled: !_loading,
|
||||
textInputAction: TextInputAction.done,
|
||||
autofillHints: const [AutofillHints.email],
|
||||
onSubmitted:
|
||||
_loading ? null : (_) => _submit(),
|
||||
),
|
||||
if (_error != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
_error!,
|
||||
key: const Key('forgot_password_error'),
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 24),
|
||||
PredPrimaryButton(
|
||||
key: const Key('forgot_password_submit'),
|
||||
label: s.sendResetLink,
|
||||
loading: _loading,
|
||||
onPressed: _submit,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_animate/flutter_animate.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
@ -8,8 +9,10 @@ import '../../../core/theme/app_colors.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/app_snackbar.dart';
|
||||
import '../../../shared/widgets/pred_button.dart';
|
||||
import '../../../shared/widgets/pred_card.dart';
|
||||
import '../../../shared/widgets/pred_text_field.dart';
|
||||
import '../../../shared/widgets/prediqo_logo.dart';
|
||||
import '../../../shared/widgets/tloto_gradient_app_bar.dart';
|
||||
import '../../welcome/utils/welcome_navigation.dart';
|
||||
import '../bloc/auth_bloc.dart';
|
||||
|
||||
@ -108,238 +111,313 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
|
||||
|
||||
return Scaffold(
|
||||
key: const Key('login_screen'),
|
||||
appBar: AppBar(
|
||||
leading: welcomeBackButton(context, key: const Key('login_back')),
|
||||
backgroundColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
),
|
||||
body: SafeArea(
|
||||
top: false,
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
|
||||
child: BlocConsumer<AuthBloc, AuthState>(
|
||||
listenWhen: (prev, curr) =>
|
||||
prev.status != curr.status ||
|
||||
prev.errorMessage != curr.errorMessage ||
|
||||
prev.registerMessage != curr.registerMessage ||
|
||||
prev.captcha != curr.captcha,
|
||||
listener: (context, state) {
|
||||
if (!isCurrentRoute(context)) return;
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
key: const Key('login_screen'),
|
||||
body: Column(
|
||||
children: [
|
||||
TlotoGradientAppBar(
|
||||
title: s.signIn,
|
||||
showBack: true,
|
||||
backButtonKey: const Key('login_back'),
|
||||
onBack: () => popToWelcomeOrPrevious(context),
|
||||
),
|
||||
Expanded(
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
20,
|
||||
16,
|
||||
20,
|
||||
24 + bottomInset + keyboardInset,
|
||||
),
|
||||
child: BlocConsumer<AuthBloc, AuthState>(
|
||||
listenWhen: (prev, curr) =>
|
||||
prev.status != curr.status ||
|
||||
prev.errorMessage != curr.errorMessage ||
|
||||
prev.registerMessage != curr.registerMessage ||
|
||||
prev.captcha != curr.captcha,
|
||||
listener: (context, state) {
|
||||
if (!isCurrentRoute(context)) return;
|
||||
|
||||
if (state.status == AuthStatus.authenticated) {
|
||||
setState(() {
|
||||
_verifyBanner = null;
|
||||
_captchaRequired = false;
|
||||
_mathPrompt = null;
|
||||
_mathChallengeToken = null;
|
||||
_mathAnswerController.clear();
|
||||
});
|
||||
_consumeFeedback();
|
||||
context.go('/home');
|
||||
return;
|
||||
}
|
||||
if (state.status == AuthStatus.authenticated) {
|
||||
setState(() {
|
||||
_verifyBanner = null;
|
||||
_captchaRequired = false;
|
||||
_mathPrompt = null;
|
||||
_mathChallengeToken = null;
|
||||
_mathAnswerController.clear();
|
||||
});
|
||||
_consumeFeedback();
|
||||
context.go('/home');
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.status == AuthStatus.verificationResent) {
|
||||
final msg = state.registerMessage ?? s.verificationEmailSent;
|
||||
setState(() {
|
||||
_verifyBanner = null;
|
||||
_showVerifyHint = true;
|
||||
});
|
||||
_bannerTimer = scheduleMessageClear(
|
||||
setState,
|
||||
() => _showVerifyHint = false,
|
||||
duration: const Duration(seconds: 6),
|
||||
previous: _bannerTimer,
|
||||
);
|
||||
showSuccessSnackBar(context, msg);
|
||||
_consumeFeedback();
|
||||
return;
|
||||
}
|
||||
if (state.status == AuthStatus.verificationResent) {
|
||||
final msg =
|
||||
state.registerMessage ?? s.verificationEmailSent;
|
||||
setState(() {
|
||||
_verifyBanner = null;
|
||||
_showVerifyHint = true;
|
||||
});
|
||||
_bannerTimer = scheduleMessageClear(
|
||||
setState,
|
||||
() => _showVerifyHint = false,
|
||||
duration: const Duration(seconds: 6),
|
||||
previous: _bannerTimer,
|
||||
);
|
||||
showSuccessSnackBar(context, msg);
|
||||
_consumeFeedback();
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.status == AuthStatus.error && state.errorMessage != null) {
|
||||
final msg = state.errorMessage!.replaceFirst('Exception: ', '');
|
||||
if (state.isCaptchaChallenge) {
|
||||
_applyCaptchaChallenge(state.captcha);
|
||||
} else if (_captchaRequired) {
|
||||
// Keep / refresh challenge after other login failures once captcha is active.
|
||||
_applyCaptchaChallenge(state.captcha);
|
||||
}
|
||||
if (state.isEmailNotVerified) {
|
||||
setState(() => _verifyBanner = msg);
|
||||
_bannerTimer = scheduleMessageClear(
|
||||
setState,
|
||||
() => _verifyBanner = null,
|
||||
duration: const Duration(seconds: 8),
|
||||
previous: _bannerTimer,
|
||||
);
|
||||
} else {
|
||||
setState(() => _verifyBanner = null);
|
||||
showErrorSnackBar(context, msg);
|
||||
}
|
||||
_consumeFeedback();
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final loading = state.isSubmitting;
|
||||
return AutofillGroup(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const SizedBox(height: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(18),
|
||||
decoration: BoxDecoration(
|
||||
gradient: AppColors.heroGradient(isDark),
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
),
|
||||
if (state.status == AuthStatus.error &&
|
||||
state.errorMessage != null) {
|
||||
final msg = state.errorMessage!
|
||||
.replaceFirst('Exception: ', '');
|
||||
if (state.isCaptchaChallenge) {
|
||||
_applyCaptchaChallenge(state.captcha);
|
||||
} else if (_captchaRequired) {
|
||||
_applyCaptchaChallenge(state.captcha);
|
||||
}
|
||||
if (state.isEmailNotVerified) {
|
||||
setState(() => _verifyBanner = msg);
|
||||
_bannerTimer = scheduleMessageClear(
|
||||
setState,
|
||||
() => _verifyBanner = null,
|
||||
duration: const Duration(seconds: 8),
|
||||
previous: _bannerTimer,
|
||||
);
|
||||
} else {
|
||||
setState(() => _verifyBanner = null);
|
||||
showErrorSnackBar(context, msg);
|
||||
}
|
||||
_consumeFeedback();
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final loading = state.isSubmitting;
|
||||
return AutofillGroup(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const PrediqoLogo(size: 64, showWordmark: false),
|
||||
const SizedBox(height: 12),
|
||||
Text(s.appName, style: Theme.of(context).textTheme.headlineMedium),
|
||||
const SizedBox(height: 6),
|
||||
Text(s.tagline, textAlign: TextAlign.center, style: Theme.of(context).textTheme.bodySmall),
|
||||
],
|
||||
),
|
||||
).animate().fadeIn(duration: 400.ms).slideY(begin: 0.05, end: 0),
|
||||
const SizedBox(height: 24),
|
||||
if (_showVerifyHint) ...[
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primary.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.primary.withValues(alpha: 0.35)),
|
||||
),
|
||||
child: Text(s.registerSuccessVerify),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
if (_verifyBanner != null) ...[
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.danger.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.danger.withValues(alpha: 0.4)),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Icon(Icons.error_outline, color: AppColors.danger, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_verifyBanner!,
|
||||
style: const TextStyle(color: AppColors.danger, fontWeight: FontWeight.w600),
|
||||
PredCard(
|
||||
gradient: AppColors.heroGradient(isDark),
|
||||
child: Column(
|
||||
children: [
|
||||
const PrediqoLogo(
|
||||
size: 56,
|
||||
showWordmark: false,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
s.appName,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.headlineMedium
|
||||
?.copyWith(fontWeight: FontWeight.w800),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
s.tagline,
|
||||
textAlign: TextAlign.center,
|
||||
style:
|
||||
Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
.animate()
|
||||
.fadeIn(duration: 400.ms)
|
||||
.slideY(begin: 0.05, end: 0),
|
||||
const SizedBox(height: 16),
|
||||
if (_showVerifyHint) ...[
|
||||
PredCard(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Text(s.registerSuccessVerify),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
if (_verifyBanner != null) ...[
|
||||
PredCard(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment:
|
||||
CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.error_outline,
|
||||
color: AppColors.danger,
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_verifyBanner!,
|
||||
style: const TextStyle(
|
||||
color: AppColors.danger,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
s.emailNotVerifiedHint,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.bodySmall,
|
||||
),
|
||||
TextButton(
|
||||
onPressed: loading
|
||||
? null
|
||||
: () {
|
||||
final email =
|
||||
_emailController.text.trim();
|
||||
if (email.isEmpty) {
|
||||
showErrorSnackBar(
|
||||
context,
|
||||
s.emailCannotBeEmpty,
|
||||
);
|
||||
return;
|
||||
}
|
||||
context.read<AuthBloc>().add(
|
||||
AuthResendVerificationRequested(
|
||||
email,
|
||||
),
|
||||
);
|
||||
},
|
||||
child: Text(s.resendVerification),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
],
|
||||
),
|
||||
PredCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
PredTextField(
|
||||
key: const Key('login_email'),
|
||||
controller: _emailController,
|
||||
label: s.email,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
prefixIcon: Icons.email_outlined,
|
||||
enabled: !loading,
|
||||
textInputAction: TextInputAction.next,
|
||||
autofillHints: const [AutofillHints.email],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
PredTextField(
|
||||
key: const Key('login_password'),
|
||||
controller: _passwordController,
|
||||
label: s.password,
|
||||
obscure: _obscurePassword,
|
||||
prefixIcon: Icons.lock_outline,
|
||||
enabled: !loading,
|
||||
textInputAction: TextInputAction.next,
|
||||
autofillHints: const [
|
||||
AutofillHints.password
|
||||
],
|
||||
suffix: IconButton(
|
||||
icon: Icon(
|
||||
_obscurePassword
|
||||
? Icons.visibility_outlined
|
||||
: Icons.visibility_off_outlined,
|
||||
),
|
||||
onPressed: loading
|
||||
? null
|
||||
: () => setState(
|
||||
() => _obscurePassword =
|
||||
!_obscurePassword,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
PredTextField(
|
||||
controller: _totpController,
|
||||
label: s.totpCode,
|
||||
keyboardType: TextInputType.number,
|
||||
prefixIcon: Icons.security_outlined,
|
||||
maxLength: 6,
|
||||
enabled: !loading,
|
||||
textInputAction: _captchaRequired
|
||||
? TextInputAction.next
|
||||
: TextInputAction.done,
|
||||
onSubmitted:
|
||||
loading ? null : (_) => _submitLogin(),
|
||||
),
|
||||
if (_captchaRequired &&
|
||||
_mathPrompt != null) ...[
|
||||
const SizedBox(height: 14),
|
||||
PredTextField(
|
||||
key: const Key('login_captcha_math'),
|
||||
controller: _mathAnswerController,
|
||||
label: s.captchaMathLabel(_mathPrompt!),
|
||||
keyboardType: TextInputType.number,
|
||||
prefixIcon:
|
||||
Icons.verified_user_outlined,
|
||||
enabled: !loading,
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: loading
|
||||
? null
|
||||
: (_) => _submitLogin(),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
s.captchaMathHelper,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.bodySmall,
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 4),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: TextButton(
|
||||
key: const Key('forgot_password_link'),
|
||||
onPressed: loading
|
||||
? null
|
||||
: () => context
|
||||
.push('/forgot-password'),
|
||||
child: Text(s.forgotPassword),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
PredPrimaryButton(
|
||||
key: const Key('login_submit'),
|
||||
label: s.signIn,
|
||||
loading: loading,
|
||||
onPressed: _submitLogin,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextButton(
|
||||
onPressed: loading
|
||||
? null
|
||||
: () => context.go('/register'),
|
||||
child: Text(s.signUp),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(s.emailNotVerifiedHint, style: Theme.of(context).textTheme.bodySmall),
|
||||
TextButton(
|
||||
onPressed: loading
|
||||
? null
|
||||
: () {
|
||||
final email = _emailController.text.trim();
|
||||
if (email.isEmpty) {
|
||||
showErrorSnackBar(context, s.emailCannotBeEmpty);
|
||||
return;
|
||||
}
|
||||
context.read<AuthBloc>().add(AuthResendVerificationRequested(email));
|
||||
},
|
||||
child: Text(s.resendVerification),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
PredTextField(
|
||||
key: const Key('login_email'),
|
||||
controller: _emailController,
|
||||
label: s.email,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
prefixIcon: Icons.email_outlined,
|
||||
enabled: !loading,
|
||||
textInputAction: TextInputAction.next,
|
||||
autofillHints: const [AutofillHints.email],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
PredTextField(
|
||||
key: const Key('login_password'),
|
||||
controller: _passwordController,
|
||||
label: s.password,
|
||||
obscure: _obscurePassword,
|
||||
prefixIcon: Icons.lock_outline,
|
||||
enabled: !loading,
|
||||
textInputAction: TextInputAction.next,
|
||||
autofillHints: const [AutofillHints.password],
|
||||
suffix: IconButton(
|
||||
icon: Icon(_obscurePassword ? Icons.visibility_outlined : Icons.visibility_off_outlined),
|
||||
onPressed: loading
|
||||
? null
|
||||
: () => setState(() => _obscurePassword = !_obscurePassword),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
PredTextField(
|
||||
controller: _totpController,
|
||||
label: s.totpCode,
|
||||
keyboardType: TextInputType.number,
|
||||
prefixIcon: Icons.security_outlined,
|
||||
maxLength: 6,
|
||||
enabled: !loading,
|
||||
textInputAction: _captchaRequired
|
||||
? TextInputAction.next
|
||||
: TextInputAction.done,
|
||||
onSubmitted: loading ? null : (_) => _submitLogin(),
|
||||
),
|
||||
if (_captchaRequired && _mathPrompt != null) ...[
|
||||
const SizedBox(height: 14),
|
||||
PredTextField(
|
||||
key: const Key('login_captcha_math'),
|
||||
controller: _mathAnswerController,
|
||||
label: s.captchaMathLabel(_mathPrompt!),
|
||||
keyboardType: TextInputType.number,
|
||||
prefixIcon: Icons.verified_user_outlined,
|
||||
enabled: !loading,
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: loading ? null : (_) => _submitLogin(),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(s.captchaMathHelper, style: Theme.of(context).textTheme.bodySmall),
|
||||
],
|
||||
const SizedBox(height: 8),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: TextButton(
|
||||
key: const Key('forgot_password_link'),
|
||||
onPressed: loading ? null : () => context.push('/forgot-password'),
|
||||
child: Text(s.forgotPassword),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
PredPrimaryButton(
|
||||
key: const Key('login_submit'),
|
||||
label: s.signIn,
|
||||
loading: loading,
|
||||
onPressed: _submitLogin,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextButton(
|
||||
onPressed: loading ? null : () => context.go('/register'),
|
||||
child: Text(s.signUp),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@ -10,9 +10,10 @@ import '../../../domain/repositories/repositories.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/app_snackbar.dart';
|
||||
import '../../../shared/widgets/pred_button.dart';
|
||||
import '../../../shared/widgets/pred_card.dart';
|
||||
import '../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../shared/widgets/pred_text_field.dart';
|
||||
import '../../../shared/widgets/prediqo_logo.dart';
|
||||
import '../../../shared/widgets/tloto_gradient_app_bar.dart';
|
||||
import '../../welcome/utils/welcome_navigation.dart';
|
||||
import '../bloc/auth_bloc.dart';
|
||||
|
||||
@ -285,50 +286,64 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
final invited = widget.initialReferralCode?.trim();
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: welcomeBackButton(context),
|
||||
title: Row(
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
key: const Key('register_screen'),
|
||||
body: Column(
|
||||
children: [
|
||||
const PrediqoLogo(size: 28, showWordmark: false),
|
||||
const SizedBox(width: 10),
|
||||
Text(s.signUp),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: SafeArea(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: BlocConsumer<AuthBloc, AuthState>(
|
||||
listenWhen: (prev, curr) =>
|
||||
prev.status != curr.status || prev.errorMessage != curr.errorMessage,
|
||||
listener: (context, state) {
|
||||
if (!isCurrentRoute(context)) return;
|
||||
TlotoGradientAppBar(
|
||||
title: s.signUp,
|
||||
showBack: true,
|
||||
onBack: () => popToWelcomeOrPrevious(context),
|
||||
),
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
20,
|
||||
16,
|
||||
20,
|
||||
24 + bottomInset + keyboardInset,
|
||||
),
|
||||
child: BlocConsumer<AuthBloc, AuthState>(
|
||||
listenWhen: (prev, curr) =>
|
||||
prev.status != curr.status ||
|
||||
prev.errorMessage != curr.errorMessage,
|
||||
listener: (context, state) {
|
||||
if (!isCurrentRoute(context)) return;
|
||||
|
||||
if (state.status == AuthStatus.registered) {
|
||||
final msg = state.registerMessage?.trim().isNotEmpty == true
|
||||
? state.registerMessage!
|
||||
: s.registerSuccessVerify;
|
||||
showSuccessSnackBar(context, msg);
|
||||
context.read<AuthBloc>().add(const AuthClearFeedback());
|
||||
context.go('/login', extra: {'verifyEmail': true});
|
||||
return;
|
||||
}
|
||||
if (state.status == AuthStatus.error && state.errorMessage != null) {
|
||||
showErrorSnackBar(
|
||||
context,
|
||||
state.errorMessage!.replaceFirst('Exception: ', ''),
|
||||
);
|
||||
context.read<AuthBloc>().add(const AuthClearFeedback());
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final loading = state.isSubmitting;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(s.registerSubtitle, style: Theme.of(context).textTheme.bodyMedium),
|
||||
if (state.status == AuthStatus.registered) {
|
||||
final msg =
|
||||
state.registerMessage?.trim().isNotEmpty == true
|
||||
? state.registerMessage!
|
||||
: s.registerSuccessVerify;
|
||||
showSuccessSnackBar(context, msg);
|
||||
context.read<AuthBloc>().add(const AuthClearFeedback());
|
||||
context.go('/login', extra: {'verifyEmail': true});
|
||||
return;
|
||||
}
|
||||
if (state.status == AuthStatus.error &&
|
||||
state.errorMessage != null) {
|
||||
showErrorSnackBar(
|
||||
context,
|
||||
state.errorMessage!.replaceFirst('Exception: ', ''),
|
||||
);
|
||||
context.read<AuthBloc>().add(const AuthClearFeedback());
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final loading = state.isSubmitting;
|
||||
return PredCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
s.registerSubtitle,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
if (invited != null && invited.isNotEmpty && !_usingDefaultReferrer) ...[
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
@ -511,14 +526,19 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
onPressed: () => _submit(s),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextButton(
|
||||
onPressed: loading ? null : () => context.go('/login'),
|
||||
child: Text(s.signIn),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
TextButton(
|
||||
onPressed:
|
||||
loading ? null : () => context.go('/login'),
|
||||
child: Text(s.signIn),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@ -14,6 +14,7 @@ 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/auth_bloc.dart';
|
||||
|
||||
/// Guides the user through 2FA setup, or manages disable when already enabled.
|
||||
@ -121,7 +122,7 @@ class _TotpSetupScreenState extends State<TotpSetupScreen> {
|
||||
final s = context.strings;
|
||||
final code = _regenCodeController.text.trim();
|
||||
if (code.length != 6) {
|
||||
showErrorSnackBar(context, s.totpCode);
|
||||
showErrorSnackBar(context, s.enterSixDigitTotp);
|
||||
return;
|
||||
}
|
||||
setState(() => _regenerating = true);
|
||||
@ -142,117 +143,167 @@ class _TotpSetupScreenState extends State<TotpSetupScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
EdgeInsets _scrollPadding(BuildContext context) {
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
|
||||
return EdgeInsets.fromLTRB(20, 16, 20, 24 + bottomInset + keyboardInset);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
return Scaffold(
|
||||
key: const Key('totp_setup_screen'),
|
||||
appBar: AppBar(title: Text(s.twoFactor)),
|
||||
body: BlocConsumer<AuthBloc, AuthState>(
|
||||
listenWhen: (prev, curr) =>
|
||||
prev.status != curr.status ||
|
||||
prev.errorMessage != curr.errorMessage ||
|
||||
prev.recoveryCodes != curr.recoveryCodes,
|
||||
listener: (context, state) {
|
||||
if (state.status == AuthStatus.authenticated && _awaitingEnable) {
|
||||
_awaitingEnable = false;
|
||||
showSuccessSnackBar(context, s.twoFactorEnabledSuccess);
|
||||
setState(() {
|
||||
_totpEnabled = true;
|
||||
_recoveryCodes = List<String>.from(state.recoveryCodes);
|
||||
_codeController.clear();
|
||||
});
|
||||
sl<AuthRepository>().invalidateProfile();
|
||||
// Keep recovery codes visible — do not pop away.
|
||||
context.read<AuthBloc>().add(const AuthClearFeedback());
|
||||
return;
|
||||
}
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
key: const Key('totp_setup_screen'),
|
||||
body: Column(
|
||||
children: [
|
||||
TlotoGradientAppBar(
|
||||
title: s.twoFactor,
|
||||
showBack: true,
|
||||
),
|
||||
Expanded(
|
||||
child: BlocConsumer<AuthBloc, AuthState>(
|
||||
listenWhen: (prev, curr) =>
|
||||
prev.status != curr.status ||
|
||||
prev.errorMessage != curr.errorMessage ||
|
||||
prev.recoveryCodes != curr.recoveryCodes,
|
||||
listener: (context, state) {
|
||||
if (state.status == AuthStatus.authenticated &&
|
||||
_awaitingEnable) {
|
||||
_awaitingEnable = false;
|
||||
showSuccessSnackBar(context, s.twoFactorEnabledSuccess);
|
||||
setState(() {
|
||||
_totpEnabled = true;
|
||||
_recoveryCodes = List<String>.from(state.recoveryCodes);
|
||||
_codeController.clear();
|
||||
});
|
||||
sl<AuthRepository>().invalidateProfile();
|
||||
context.read<AuthBloc>().add(const AuthClearFeedback());
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.status == AuthStatus.authenticated && _awaitingDisable) {
|
||||
_awaitingDisable = false;
|
||||
showSuccessSnackBar(context, s.twoFactorDisabled);
|
||||
setState(() {
|
||||
_totpEnabled = false;
|
||||
_recoveryCodes = const [];
|
||||
_passwordController.clear();
|
||||
_disableCodeController.clear();
|
||||
_regenCodeController.clear();
|
||||
});
|
||||
sl<AuthRepository>().invalidateProfile();
|
||||
context.read<AuthBloc>().add(const AuthClearFeedback());
|
||||
return;
|
||||
}
|
||||
if (state.status == AuthStatus.authenticated &&
|
||||
_awaitingDisable) {
|
||||
_awaitingDisable = false;
|
||||
showSuccessSnackBar(context, s.twoFactorDisabled);
|
||||
setState(() {
|
||||
_totpEnabled = false;
|
||||
_recoveryCodes = const [];
|
||||
_passwordController.clear();
|
||||
_disableCodeController.clear();
|
||||
_regenCodeController.clear();
|
||||
});
|
||||
sl<AuthRepository>().invalidateProfile();
|
||||
context.read<AuthBloc>().add(const AuthClearFeedback());
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.status == AuthStatus.error) {
|
||||
_awaitingEnable = false;
|
||||
_awaitingDisable = false;
|
||||
setState(() => _startingSetup = false);
|
||||
showErrorSnackBar(context, _cleanError(state.errorMessage));
|
||||
context.read<AuthBloc>().add(const AuthClearFeedback());
|
||||
return;
|
||||
}
|
||||
if (state.status == AuthStatus.error) {
|
||||
_awaitingEnable = false;
|
||||
_awaitingDisable = false;
|
||||
setState(() => _startingSetup = false);
|
||||
showErrorSnackBar(context, _cleanError(state.errorMessage));
|
||||
context.read<AuthBloc>().add(const AuthClearFeedback());
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.status == AuthStatus.totpSetup) {
|
||||
setState(() => _startingSetup = false);
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
if (_profileError != null && !_profileKnown) {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _profileError!,
|
||||
retrying: _profileRetrying,
|
||||
onRetry: () => _loadProfile(force: true),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (_loadingProfile && !_profileKnown) {
|
||||
return ListView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 16),
|
||||
PredSkeletonCard(height: 48),
|
||||
SizedBox(height: 12),
|
||||
PredSkeletonCard(height: 48),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (_totpEnabled && state.totpData == null) {
|
||||
return _buildEnabledView(context, s);
|
||||
}
|
||||
return _buildSetupView(context, s, state);
|
||||
},
|
||||
if (state.status == AuthStatus.totpSetup) {
|
||||
setState(() => _startingSetup = false);
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
return RefreshIndicator(
|
||||
onRefresh: () => _loadProfile(force: true),
|
||||
child: _buildBody(context, s, state),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildEnabledView(BuildContext context, AppStrings s) {
|
||||
Widget _buildBody(BuildContext context, AppStrings s, AuthState state) {
|
||||
const physics = AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
);
|
||||
final padding = _scrollPadding(context);
|
||||
|
||||
if (_profileError != null && !_profileKnown) {
|
||||
return ListView(
|
||||
physics: physics,
|
||||
padding: padding,
|
||||
children: [
|
||||
SectionError(
|
||||
message: _profileError!,
|
||||
retrying: _profileRetrying,
|
||||
onRetry: () => _loadProfile(force: true),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (_loadingProfile && !_profileKnown) {
|
||||
return ListView(
|
||||
physics: physics,
|
||||
padding: padding,
|
||||
children: const [
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 16),
|
||||
PredSkeletonCard(height: 48),
|
||||
SizedBox(height: 12),
|
||||
PredSkeletonCard(height: 48),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (_totpEnabled && state.totpData == null) {
|
||||
return _buildEnabledView(context, s, physics, padding);
|
||||
}
|
||||
return _buildSetupView(context, s, state, physics, padding);
|
||||
}
|
||||
|
||||
Widget _buildEnabledView(
|
||||
BuildContext context,
|
||||
AppStrings s,
|
||||
ScrollPhysics physics,
|
||||
EdgeInsets padding,
|
||||
) {
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
physics: physics,
|
||||
padding: padding,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.goldPrimary.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.goldPrimary.withValues(alpha: 0.35)),
|
||||
),
|
||||
PredCard(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.verified_user_rounded, color: AppColors.goldPrimary),
|
||||
Container(
|
||||
width: 40,
|
||||
height: 40,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: AppColors.success.withValues(alpha: 0.15),
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.verified_user_rounded,
|
||||
color: AppColors.success,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: Text(s.twoFactorEnabled)),
|
||||
Expanded(
|
||||
child: Text(
|
||||
s.twoFactorEnabled,
|
||||
style: const TextStyle(fontWeight: FontWeight.w700),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (_recoveryCodes.isNotEmpty) ...[
|
||||
const SizedBox(height: 20),
|
||||
const SizedBox(height: 12),
|
||||
_RecoveryCodesCard(
|
||||
codes: _recoveryCodes,
|
||||
onCopyAll: _copyAllCodes,
|
||||
@ -260,136 +311,198 @@ class _TotpSetupScreenState extends State<TotpSetupScreen> {
|
||||
onDismiss: () => setState(() => _recoveryCodes = const []),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 28),
|
||||
Text(
|
||||
s.enterTotpToRegenerate,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
const SizedBox(height: 12),
|
||||
PredCard(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
s.twoFactorRegenSection,
|
||||
style: const TextStyle(fontWeight: FontWeight.w800),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _regenCodeController,
|
||||
keyboardType: TextInputType.number,
|
||||
maxLength: 6,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.totpCode,
|
||||
prefixIcon: const Icon(Icons.pin),
|
||||
counterText: '',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _regenerating ? null : _regenerateCodes,
|
||||
icon: _regenerating
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.refresh_rounded),
|
||||
label: Text(
|
||||
_regenerating ? s.regeneratingRecoveryCodes : s.regenerateRecoveryCodes,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
const Divider(),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: _passwordController,
|
||||
obscureText: true,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.twoFactorCurrentPassword,
|
||||
prefixIcon: const Icon(Icons.lock_outline),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
s.enterTotpToRegenerate,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _regenCodeController,
|
||||
keyboardType: TextInputType.number,
|
||||
maxLength: 6,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.totpCode,
|
||||
prefixIcon: const Icon(Icons.pin),
|
||||
counterText: '',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _regenerating ? null : _regenerateCodes,
|
||||
icon: _regenerating
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.refresh_rounded),
|
||||
label: Text(
|
||||
_regenerating
|
||||
? s.regeneratingRecoveryCodes
|
||||
: s.regenerateRecoveryCodes,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _disableCodeController,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.twoFactorCodeOrRecovery,
|
||||
prefixIcon: const Icon(Icons.pin),
|
||||
PredCard(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
s.twoFactorDisableSection,
|
||||
style: const TextStyle(fontWeight: FontWeight.w800),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _passwordController,
|
||||
obscureText: true,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.twoFactorCurrentPassword,
|
||||
prefixIcon: const Icon(Icons.lock_outline),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _disableCodeController,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.twoFactorCodeOrRecovery,
|
||||
prefixIcon: const Icon(Icons.pin),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
onPressed: () {
|
||||
final password = _passwordController.text;
|
||||
final code = _disableCodeController.text.trim();
|
||||
if (password.isEmpty || code.isEmpty) {
|
||||
showErrorSnackBar(
|
||||
context,
|
||||
'${s.twoFactorCurrentPassword} / ${s.twoFactorCodeOrRecovery}',
|
||||
);
|
||||
return;
|
||||
}
|
||||
setState(() => _awaitingDisable = true);
|
||||
context.read<AuthBloc>().add(
|
||||
Auth2FADisableRequested(
|
||||
password: password,
|
||||
code: code,
|
||||
),
|
||||
);
|
||||
},
|
||||
child: Text(s.twoFactorDisable),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
FilledButton(
|
||||
style: FilledButton.styleFrom(backgroundColor: Colors.redAccent),
|
||||
onPressed: () {
|
||||
final password = _passwordController.text;
|
||||
final code = _disableCodeController.text.trim();
|
||||
if (password.isEmpty || code.isEmpty) {
|
||||
showErrorSnackBar(
|
||||
context,
|
||||
'${s.twoFactorCurrentPassword} / ${s.twoFactorCodeOrRecovery}',
|
||||
);
|
||||
return;
|
||||
}
|
||||
setState(() => _awaitingDisable = true);
|
||||
context.read<AuthBloc>().add(
|
||||
Auth2FADisableRequested(password: password, code: code),
|
||||
);
|
||||
},
|
||||
child: Text(s.twoFactorDisable),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSetupView(BuildContext context, AppStrings s, AuthState state) {
|
||||
Widget _buildSetupView(
|
||||
BuildContext context,
|
||||
AppStrings s,
|
||||
AuthState state,
|
||||
ScrollPhysics physics,
|
||||
EdgeInsets padding,
|
||||
) {
|
||||
final qrUrl = state.totpData?['qrCodeUrl'] as String?;
|
||||
final busy = _startingSetup;
|
||||
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(s.twoFactorSetupHint),
|
||||
const SizedBox(height: 20),
|
||||
if (qrUrl == null) ...[
|
||||
FilledButton(
|
||||
onPressed: busy
|
||||
? null
|
||||
: () {
|
||||
setState(() => _startingSetup = true);
|
||||
context.read<AuthBloc>().add(const Auth2FASetupRequested());
|
||||
},
|
||||
child: busy
|
||||
? const SizedBox(
|
||||
height: 22,
|
||||
width: 22,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: Text(s.twoFactorStartSetup),
|
||||
),
|
||||
] else ...[
|
||||
Center(child: _QrImage(dataUrl: qrUrl)),
|
||||
const SizedBox(height: 24),
|
||||
TextField(
|
||||
controller: _codeController,
|
||||
keyboardType: TextInputType.number,
|
||||
maxLength: 6,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.totpCode,
|
||||
prefixIcon: const Icon(Icons.pin),
|
||||
),
|
||||
physics: physics,
|
||||
padding: padding,
|
||||
child: PredCard(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
s.twoFactorSetupHint,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
final code = _codeController.text.trim();
|
||||
if (code.length != 6) {
|
||||
showErrorSnackBar(context, s.totpCode);
|
||||
return;
|
||||
}
|
||||
setState(() => _awaitingEnable = true);
|
||||
context.read<AuthBloc>().add(Auth2FAEnableRequested(code: code));
|
||||
},
|
||||
child: Text(s.twoFactorEnable),
|
||||
),
|
||||
if (qrUrl == null) ...[
|
||||
FilledButton(
|
||||
onPressed: busy
|
||||
? null
|
||||
: () {
|
||||
setState(() => _startingSetup = true);
|
||||
context
|
||||
.read<AuthBloc>()
|
||||
.add(const Auth2FASetupRequested());
|
||||
},
|
||||
child: busy
|
||||
? const SizedBox(
|
||||
height: 22,
|
||||
width: 22,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
)
|
||||
: Text(s.twoFactorStartSetup),
|
||||
),
|
||||
] else ...[
|
||||
Center(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: _QrImage(dataUrl: qrUrl),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
TextField(
|
||||
controller: _codeController,
|
||||
keyboardType: TextInputType.number,
|
||||
maxLength: 6,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.totpCode,
|
||||
prefixIcon: const Icon(Icons.pin),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
final code = _codeController.text.trim();
|
||||
if (code.length != 6) {
|
||||
showErrorSnackBar(context, s.enterSixDigitTotp);
|
||||
return;
|
||||
}
|
||||
setState(() => _awaitingEnable = true);
|
||||
context
|
||||
.read<AuthBloc>()
|
||||
.add(Auth2FAEnableRequested(code: code));
|
||||
},
|
||||
child: Text(s.twoFactorEnable),
|
||||
),
|
||||
],
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@ -446,7 +559,10 @@ class _RecoveryCodesCard extends StatelessWidget {
|
||||
onTap: () => onCopyOne(code),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 12,
|
||||
vertical: 10,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
|
||||
@ -1,4 +1,8 @@
|
||||
/// Help presentation: searchable FAQ list with expandable answers.
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import '../../../core/di/injection.dart';
|
||||
import '../../../core/errors/app_exception.dart';
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
@ -8,6 +12,7 @@ import '../../../l10n/app_strings.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 '../../welcome/utils/welcome_navigation.dart';
|
||||
|
||||
class FaqScreen extends StatefulWidget {
|
||||
@ -36,6 +41,9 @@ class _FaqScreenState extends State<FaqScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_searchController.addListener(() {
|
||||
if (mounted) setState(() {});
|
||||
});
|
||||
final cached = _repo.peekLast(category: widget.initialCategory);
|
||||
if (cached != null && cached.isNotEmpty) {
|
||||
_entries = cached;
|
||||
@ -118,126 +126,197 @@ class _FaqScreenState extends State<FaqScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
return Scaffold(
|
||||
key: const Key('faq_screen'),
|
||||
appBar: AppBar(
|
||||
leading: welcomeBackButton(context),
|
||||
title: Text(s.faqTitle),
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),
|
||||
child: TextField(
|
||||
key: const Key('faq_search'),
|
||||
controller: _searchController,
|
||||
decoration: InputDecoration(
|
||||
hintText: s.searchFaq,
|
||||
prefixIcon: const Icon(Icons.search_rounded),
|
||||
suffixIcon: IconButton(
|
||||
icon: const Icon(Icons.clear_rounded),
|
||||
onPressed: _clearSearch,
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
|
||||
final muted = isDark ? AppColors.textMuted : const Color(0xFF94A3B8);
|
||||
final secondary =
|
||||
isDark ? AppColors.textSecondary : const Color(0xFF475569);
|
||||
const physics = AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
);
|
||||
final listPadding = EdgeInsets.fromLTRB(
|
||||
20,
|
||||
12,
|
||||
20,
|
||||
24 + bottomInset + keyboardInset,
|
||||
);
|
||||
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
key: const Key('faq_screen'),
|
||||
body: Column(
|
||||
children: [
|
||||
TlotoGradientAppBar(
|
||||
title: s.faqTitle,
|
||||
showBack: true,
|
||||
onBack: () => popToWelcomeOrPrevious(context),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),
|
||||
child: PredCard(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
|
||||
child: TextField(
|
||||
key: const Key('faq_search'),
|
||||
controller: _searchController,
|
||||
textInputAction: TextInputAction.search,
|
||||
decoration: InputDecoration(
|
||||
hintText: s.searchFaq,
|
||||
border: InputBorder.none,
|
||||
enabledBorder: InputBorder.none,
|
||||
focusedBorder: InputBorder.none,
|
||||
prefixIcon: const Icon(Icons.search_rounded),
|
||||
suffixIcon: _searchController.text.isNotEmpty
|
||||
? IconButton(
|
||||
icon: const Icon(Icons.clear_rounded),
|
||||
onPressed: _clearSearch,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
onSubmitted: (q) => _load(
|
||||
search: q.trim().isEmpty ? null : q.trim(),
|
||||
category: widget.initialCategory,
|
||||
force: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
onSubmitted: (q) => _load(
|
||||
search: q.trim().isEmpty ? null : q.trim(),
|
||||
category: widget.initialCategory,
|
||||
force: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_searching)
|
||||
const LinearProgressIndicator(
|
||||
minHeight: 2,
|
||||
color: AppColors.primary,
|
||||
),
|
||||
Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () => _load(
|
||||
search: _activeSearch,
|
||||
category: widget.initialCategory,
|
||||
force: true,
|
||||
if (_searching)
|
||||
const LinearProgressIndicator(
|
||||
minHeight: 2,
|
||||
color: AppColors.primary,
|
||||
),
|
||||
child: _error != null && _entries.isEmpty
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(
|
||||
search: _activeSearch,
|
||||
category: widget.initialCategory,
|
||||
force: true,
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: _loading && _entries.isEmpty
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 72),
|
||||
],
|
||||
)
|
||||
: _entries.isEmpty
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: [
|
||||
SizedBox(
|
||||
height: 160,
|
||||
child: Center(child: Text(s.noFaqResults)),
|
||||
),
|
||||
],
|
||||
)
|
||||
: ListView.builder(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(20),
|
||||
itemCount: _entries.length,
|
||||
itemBuilder: (context, index) {
|
||||
final entry = _entries[index];
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 10),
|
||||
child: PredCard(
|
||||
child: ExpansionTile(
|
||||
title: Text(
|
||||
entry.question,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
subtitle: entry.category.isNotEmpty
|
||||
? Text(entry.category)
|
||||
: null,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
16,
|
||||
0,
|
||||
16,
|
||||
16,
|
||||
),
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Text(entry.answer),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () => _load(
|
||||
search: _activeSearch,
|
||||
category: widget.initialCategory,
|
||||
force: true,
|
||||
),
|
||||
child: _error != null && _entries.isEmpty
|
||||
? ListView(
|
||||
physics: physics,
|
||||
padding: listPadding,
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _load(
|
||||
search: _activeSearch,
|
||||
category: widget.initialCategory,
|
||||
force: true,
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: _loading && _entries.isEmpty
|
||||
? ListView(
|
||||
physics: physics,
|
||||
padding: listPadding,
|
||||
children: const [
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 72),
|
||||
],
|
||||
)
|
||||
: _entries.isEmpty
|
||||
? ListView(
|
||||
physics: physics,
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
40,
|
||||
40,
|
||||
40,
|
||||
40 + bottomInset,
|
||||
),
|
||||
children: [
|
||||
Icon(
|
||||
Icons.help_outline_rounded,
|
||||
size: 48,
|
||||
color: muted,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
s.noFaqResults,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.bodyMedium
|
||||
?.copyWith(color: secondary),
|
||||
),
|
||||
],
|
||||
)
|
||||
: ListView.separated(
|
||||
physics: physics,
|
||||
padding: listPadding,
|
||||
itemCount: _entries.length,
|
||||
separatorBuilder: (_, __) =>
|
||||
const SizedBox(height: 8),
|
||||
itemBuilder: (context, index) {
|
||||
final entry = _entries[index];
|
||||
return PredCard(
|
||||
padding: EdgeInsets.zero,
|
||||
child: Theme(
|
||||
data: Theme.of(context).copyWith(
|
||||
dividerColor: Colors.transparent,
|
||||
),
|
||||
child: ExpansionTile(
|
||||
tilePadding: const EdgeInsets.symmetric(
|
||||
horizontal: 14,
|
||||
vertical: 2,
|
||||
),
|
||||
childrenPadding:
|
||||
const EdgeInsets.fromLTRB(
|
||||
14,
|
||||
0,
|
||||
14,
|
||||
14,
|
||||
),
|
||||
title: Text(
|
||||
entry.question,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleSmall
|
||||
?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
subtitle: entry.category.isNotEmpty
|
||||
? Text(
|
||||
entry.category,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.bodySmall
|
||||
?.copyWith(
|
||||
color: muted,
|
||||
),
|
||||
)
|
||||
: null,
|
||||
children: [
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Text(
|
||||
entry.answer,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.bodyMedium
|
||||
?.copyWith(
|
||||
color: secondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,4 +1,8 @@
|
||||
/// Notifications presentation: security / system alerts with mark-read and pagination.
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../../../core/di/injection.dart';
|
||||
import '../../../core/errors/app_exception.dart';
|
||||
@ -9,6 +13,7 @@ import '../../../l10n/app_strings.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';
|
||||
|
||||
class NotificationsScreen extends StatefulWidget {
|
||||
const NotificationsScreen({super.key});
|
||||
@ -155,47 +160,41 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
|
||||
await showModalBottomSheet<void>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: AppColors.surfaceCard,
|
||||
useRootNavigator: true,
|
||||
showDragHandle: true,
|
||||
backgroundColor: Theme.of(context).colorScheme.surface,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
builder: (ctx) {
|
||||
return Padding(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
20,
|
||||
16,
|
||||
20,
|
||||
24 + MediaQuery.paddingOf(ctx).bottom,
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Center(
|
||||
child: Container(
|
||||
width: 40,
|
||||
height: 4,
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.border,
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
final isDark = Theme.of(ctx).brightness == Brightness.dark;
|
||||
final muted =
|
||||
isDark ? AppColors.textMuted : const Color(0xFF94A3B8);
|
||||
return SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 8, 20, 24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
item.title,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.w800,
|
||||
fontSize: 18,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
item.title,
|
||||
style: const TextStyle(fontWeight: FontWeight.w800, fontSize: 18),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
_formatDate(item.createdAt),
|
||||
style: Theme.of(ctx).textTheme.bodySmall?.copyWith(
|
||||
color: AppColors.textMuted,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Text(item.body, style: Theme.of(ctx).textTheme.bodyMedium),
|
||||
],
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
_formatDate(item.createdAt),
|
||||
style: Theme.of(ctx).textTheme.bodySmall?.copyWith(
|
||||
color: muted,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Text(item.body, style: Theme.of(ctx).textTheme.bodyMedium),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
@ -211,45 +210,78 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(s.notificationsTitle),
|
||||
actions: [
|
||||
if (_unreadCount > 0)
|
||||
TextButton(
|
||||
onPressed: _markAll,
|
||||
child: Text(s.markAllRead),
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
final muted = isDark ? AppColors.textMuted : const Color(0xFF94A3B8);
|
||||
final secondary =
|
||||
isDark ? AppColors.textSecondary : const Color(0xFF475569);
|
||||
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
key: const Key('notifications_screen'),
|
||||
body: Column(
|
||||
children: [
|
||||
TlotoGradientAppBar(
|
||||
title: s.notificationsTitle,
|
||||
showBack: true,
|
||||
actions: [
|
||||
if (_unreadCount > 0)
|
||||
TextButton(
|
||||
onPressed: _markAll,
|
||||
child: Text(
|
||||
s.markAllRead,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
body: RefreshIndicator(
|
||||
onRefresh: () => _load(reset: true, force: true),
|
||||
child: _buildBody(s),
|
||||
Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () => _load(reset: true, force: true),
|
||||
child: _buildBody(s, muted, secondary, bottomInset),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBody(AppStrings s) {
|
||||
Widget _buildBody(
|
||||
AppStrings s,
|
||||
Color muted,
|
||||
Color secondary,
|
||||
double bottomInset,
|
||||
) {
|
||||
const physics = AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
);
|
||||
final listPadding = EdgeInsets.fromLTRB(20, 12, 20, 24 + bottomInset);
|
||||
|
||||
if (_loading && _items.isEmpty) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.fromLTRB(20, 12, 20, 28),
|
||||
physics: physics,
|
||||
padding: listPadding,
|
||||
children: const [
|
||||
PredSkeletonCard(height: 88),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 88),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 88),
|
||||
SizedBox(height: 10),
|
||||
PredSkeletonCard(height: 88),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
if (_error != null && _items.isEmpty) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.fromLTRB(20, 12, 20, 28),
|
||||
physics: physics,
|
||||
padding: listPadding,
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
@ -262,41 +294,44 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
|
||||
|
||||
if (_items.isEmpty) {
|
||||
return ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(40),
|
||||
physics: physics,
|
||||
padding: EdgeInsets.fromLTRB(40, 40, 40, 40 + bottomInset),
|
||||
children: [
|
||||
const Icon(
|
||||
Icons.notifications_none_rounded,
|
||||
size: 48,
|
||||
color: AppColors.textMuted,
|
||||
),
|
||||
Icon(Icons.notifications_none_rounded, size: 48, color: muted),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
s.noNotifications,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
color: secondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
final remaining = (_total - _items.length).clamp(0, _pageSize);
|
||||
|
||||
return ListView.separated(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.fromLTRB(20, 12, 20, 28),
|
||||
physics: physics,
|
||||
padding: listPadding,
|
||||
itemCount: _items.length + (_hasMore ? 1 : 0),
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 10),
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 8),
|
||||
itemBuilder: (context, index) {
|
||||
if (index >= _items.length) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Center(
|
||||
child: _loadingMore
|
||||
? const PredSkeletonLine(width: 120, height: 36)
|
||||
: OutlinedButton(
|
||||
? const SizedBox(
|
||||
width: 28,
|
||||
height: 28,
|
||||
child: CircularProgressIndicator(strokeWidth: 2.5),
|
||||
)
|
||||
: TextButton(
|
||||
key: const Key('notifications_load_more'),
|
||||
onPressed: () => _load(reset: false),
|
||||
child: Text(s.loadMore),
|
||||
child: Text(s.loadMoreRemaining(remaining)),
|
||||
),
|
||||
),
|
||||
);
|
||||
@ -304,7 +339,7 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
|
||||
final item = _items[index];
|
||||
return PredCard(
|
||||
onTap: () => _openItem(item),
|
||||
padding: const EdgeInsets.all(16),
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
@ -337,7 +372,7 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.bodySmall
|
||||
?.copyWith(color: AppColors.textSecondary),
|
||||
?.copyWith(color: secondary),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
@ -345,7 +380,7 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.labelSmall
|
||||
?.copyWith(color: AppColors.textMuted),
|
||||
?.copyWith(color: muted),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@ -1042,7 +1042,10 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
}
|
||||
_healthyPollSkips = 0;
|
||||
|
||||
final gameState = await _repo.getState(intervalMinutes: interval);
|
||||
final gameState = await _repo.getState(
|
||||
intervalMinutes: interval,
|
||||
force: event.forceGameState || phaseBoundary,
|
||||
);
|
||||
final labels = await _loadBalances(gameState.config.walletTypeCode);
|
||||
final multi = gameState.userMultiBet;
|
||||
var history = state.history;
|
||||
@ -1161,7 +1164,9 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
case 'round.updated':
|
||||
case 'round.settled':
|
||||
final roundVersions = msg['versions'];
|
||||
if (roundVersions is Map<String, dynamic>) {
|
||||
// Do not advance the ETag on settle before `/state` — that caused 304
|
||||
// loops while the UI was stuck at secondsToBettingStart: 0.
|
||||
if (type == 'round.updated' && roundVersions is Map<String, dynamic>) {
|
||||
PredictionRepositoryImpl.mergeCachedStateVersions(
|
||||
state.selectedIntervalMinutes,
|
||||
round: roundVersions['round'] is num
|
||||
@ -1200,9 +1205,10 @@ class PredictionBloc extends Bloc<PredictionEvent, PredictionState> {
|
||||
}
|
||||
if (type == 'round.settled') {
|
||||
// Candle + next window arrive via candle.append / round.updated.
|
||||
// A full Load would re-apply a stale HTTP snapshot mid-countdown,
|
||||
// but a forced `/state` tick is required when those WS events lag —
|
||||
// otherwise the UI stays at 0s until the healthy poll catches up.
|
||||
// Force `/state` without the settle ETag so clients leave 0s promptly.
|
||||
PredictionRepositoryImpl.invalidateStateCache(
|
||||
state.selectedIntervalMinutes,
|
||||
);
|
||||
add(const PredictionBalancesRefreshRequested());
|
||||
add(const PredictionHistoryPageRequested(1));
|
||||
add(const PredictionRefreshTick(forceGameState: true));
|
||||
|
||||
@ -11,8 +11,8 @@ 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/prediqo_logo.dart';
|
||||
import '../../../shared/widgets/section_error.dart';
|
||||
import '../../../shared/widgets/tloto_gradient_app_bar.dart';
|
||||
import '../../home/utils/home_navigation.dart';
|
||||
import '../bloc/prediction_bloc.dart';
|
||||
import '../utils/game_catalog_ui.dart';
|
||||
@ -107,56 +107,12 @@ class _PredictionGamesScreenState extends State<PredictionGamesScreen> {
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: const SystemUiOverlayStyle(
|
||||
statusBarColor: Colors.transparent,
|
||||
statusBarIconBrightness: Brightness.light,
|
||||
statusBarBrightness: Brightness.dark,
|
||||
),
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
key: const Key('prediction_games_screen'),
|
||||
body: Column(
|
||||
children: [
|
||||
DecoratedBox(
|
||||
decoration: const BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
colors: [
|
||||
Color(0xFF059669),
|
||||
Color(0xFF047857),
|
||||
Color(0xFF0F172A),
|
||||
],
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
bottom: false,
|
||||
child: SizedBox(
|
||||
height: kToolbarHeight,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Row(
|
||||
children: [
|
||||
const PrediqoLogo(size: 28, showWordmark: false),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Text(
|
||||
s.predictionGamesTitle,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.w900,
|
||||
letterSpacing: 0.3,
|
||||
color: Colors.white,
|
||||
fontSize: 18,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
TlotoGradientAppBar(title: s.predictionGamesTitle),
|
||||
Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () => _load(force: true),
|
||||
|
||||
@ -1,16 +1,17 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_animate/flutter_animate.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../../core/theme/app_colors.dart';
|
||||
import '../../../../data/models/prediction_models.dart';
|
||||
import '../../../../data/models/candle_predict_instrument.dart';
|
||||
import '../../../../l10n/app_strings.dart';
|
||||
import '../../../../shared/widgets/pred_card.dart';
|
||||
import '../../../../shared/widgets/pred_skeleton.dart';
|
||||
import '../../../../shared/widgets/pred_text_field.dart';
|
||||
import '../../../../shared/widgets/section_error.dart';
|
||||
import '../../../../shared/widgets/adaptive_space_between_row.dart';
|
||||
import '../../../../shared/widgets/tloto_gradient_app_bar.dart';
|
||||
import '../../auth/bloc/auth_bloc.dart';
|
||||
import '../../support/utils/support_ui_gate.dart';
|
||||
import '../bloc/prediction_bloc.dart';
|
||||
@ -173,26 +174,51 @@ class _PredictionScreenState extends State<PredictionScreen> with WidgetsBinding
|
||||
final bootError =
|
||||
state.status == PredictionStatus.error && gs == null;
|
||||
|
||||
return KeyedSubtree(
|
||||
key: const Key('prediction_screen'),
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () async {
|
||||
context.read<PredictionBloc>().add(const PredictionLoadRequested());
|
||||
},
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.fromLTRB(20, 8, 20, 100),
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: KeyedSubtree(
|
||||
key: const Key('prediction_screen'),
|
||||
child: Column(
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(s.predictTitle, style: Theme.of(context).textTheme.headlineMedium),
|
||||
TlotoGradientAppBar(
|
||||
title: s.predictTitle,
|
||||
showBack: true,
|
||||
onBack: () {
|
||||
if (context.canPop()) {
|
||||
context.pop();
|
||||
} else {
|
||||
context.go('/predict');
|
||||
}
|
||||
},
|
||||
actions: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 10),
|
||||
child: Center(
|
||||
child: _LiveBadge(status: state.realtimeStatus),
|
||||
),
|
||||
),
|
||||
_LiveBadge(status: state.realtimeStatus),
|
||||
],
|
||||
).animate().fadeIn(duration: 300.ms),
|
||||
const SizedBox(height: 4),
|
||||
Text(s.tagline, style: Theme.of(context).textTheme.bodySmall),
|
||||
const SizedBox(height: 20),
|
||||
),
|
||||
Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () async {
|
||||
context
|
||||
.read<PredictionBloc>()
|
||||
.add(const PredictionLoadRequested());
|
||||
},
|
||||
child: ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
20,
|
||||
12,
|
||||
20,
|
||||
24 + bottomInset + 72,
|
||||
),
|
||||
children: [
|
||||
if (bootError) ...[
|
||||
SectionError(
|
||||
message: state.errorMessage ?? s.error,
|
||||
@ -440,6 +466,10 @@ class _PredictionScreenState extends State<PredictionScreen> with WidgetsBinding
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@ -978,5 +1008,9 @@ String _formatPredictionError(AppStrings s, String raw) {
|
||||
};
|
||||
return s.insufficientBalanceOn(wallet);
|
||||
}
|
||||
final lower = raw.toLowerCase();
|
||||
if (lower.contains('readonly') || lower.contains('read only replica')) {
|
||||
return s.predictionDbReadonly;
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
@ -2,10 +2,14 @@
|
||||
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/theme/app_theme.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/tloto_gradient_app_bar.dart';
|
||||
import '../../auth/bloc/auth_bloc.dart';
|
||||
|
||||
/// Form to update the user's password; requires current password and confirmation.
|
||||
@ -33,21 +37,24 @@ class _ChangePasswordScreenState extends State<ChangePasswordScreen> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// Validates inputs and submits the password change to the API.
|
||||
Future<void> _submit() async {
|
||||
final s = context.strings;
|
||||
final current = _currentPasswordController.text;
|
||||
final newPass = _newPasswordController.text;
|
||||
final confirm = _confirmPasswordController.text;
|
||||
if (current.isEmpty) {
|
||||
setState(() => _error = 'Enter your current password');
|
||||
setState(() => _error = s.enterCurrentPassword);
|
||||
showErrorSnackBar(context, s.enterCurrentPassword);
|
||||
return;
|
||||
}
|
||||
if (newPass.isEmpty) {
|
||||
setState(() => _error = 'Enter a new password');
|
||||
setState(() => _error = s.enterNewPassword);
|
||||
showErrorSnackBar(context, s.enterNewPassword);
|
||||
return;
|
||||
}
|
||||
if (newPass != confirm) {
|
||||
setState(() => _error = 'New password and confirmation do not match');
|
||||
setState(() => _error = s.passwordsMustMatch);
|
||||
showErrorSnackBar(context, s.passwordsMustMatch);
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
@ -56,103 +63,140 @@ class _ChangePasswordScreenState extends State<ChangePasswordScreen> {
|
||||
});
|
||||
try {
|
||||
final authRepo = context.read<AuthRepository>();
|
||||
await authRepo.changePassword(currentPassword: current, newPassword: newPass);
|
||||
await authRepo.changePassword(
|
||||
currentPassword: current,
|
||||
newPassword: newPass,
|
||||
);
|
||||
if (mounted) {
|
||||
setState(() => _saving = false);
|
||||
context.read<AuthBloc>().add(const AuthLogoutRequested());
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Password updated. Please sign in again.'),
|
||||
),
|
||||
);
|
||||
showSuccessSnackBar(context, s.passwordUpdatedSignInAgain);
|
||||
context.go('/login');
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) {
|
||||
final msg = e.toString().replaceFirst('Exception: ', '');
|
||||
setState(() {
|
||||
_saving = false;
|
||||
_error = e.toString().replaceFirst('Exception: ', '');
|
||||
_error = msg;
|
||||
});
|
||||
showErrorSnackBar(context, msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Change password'),
|
||||
flexibleSpace: Container(
|
||||
decoration: const BoxDecoration(gradient: AppTheme.goldGradient),
|
||||
),
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back_rounded),
|
||||
onPressed: () => context.pop(),
|
||||
),
|
||||
),
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
final s = context.strings;
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
|
||||
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
key: const Key('change_password_screen'),
|
||||
body: Column(
|
||||
children: [
|
||||
Text(
|
||||
'Enter your current password and choose a new one. New password must meet the system security policy.',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
TlotoGradientAppBar(
|
||||
title: s.changePassword,
|
||||
showBack: true,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
TextField(
|
||||
controller: _currentPasswordController,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Current password',
|
||||
border: const OutlineInputBorder(),
|
||||
prefixIcon: const Icon(Icons.lock_outline),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(_passwordVisible ? Icons.visibility_off : Icons.visibility),
|
||||
onPressed: () => setState(() => _passwordVisible = !_passwordVisible),
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
20,
|
||||
16,
|
||||
20,
|
||||
24 + bottomInset + keyboardInset,
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
s.changePasswordHint,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context)
|
||||
.colorScheme
|
||||
.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
PredCard(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
TextField(
|
||||
controller: _currentPasswordController,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.currentPassword,
|
||||
prefixIcon: const Icon(Icons.lock_outline),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
_passwordVisible
|
||||
? Icons.visibility_off
|
||||
: Icons.visibility,
|
||||
),
|
||||
onPressed: () => setState(
|
||||
() => _passwordVisible = !_passwordVisible,
|
||||
),
|
||||
),
|
||||
),
|
||||
obscureText: !_passwordVisible,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _newPasswordController,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.newPassword,
|
||||
prefixIcon: const Icon(Icons.lock_outline),
|
||||
),
|
||||
obscureText: !_passwordVisible,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _confirmPasswordController,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.confirmNewPassword,
|
||||
prefixIcon: const Icon(Icons.lock_outline),
|
||||
),
|
||||
obscureText: !_passwordVisible,
|
||||
),
|
||||
if (_error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 12),
|
||||
child: Text(
|
||||
_error!,
|
||||
style: TextStyle(
|
||||
color:
|
||||
Theme.of(context).colorScheme.error,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _submit,
|
||||
child: _saving
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
)
|
||||
: Text(s.updatePassword),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
obscureText: !_passwordVisible,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _newPasswordController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'New password',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.lock_outline),
|
||||
),
|
||||
obscureText: !_passwordVisible,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _confirmPasswordController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Confirm new password',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.lock_outline),
|
||||
),
|
||||
obscureText: !_passwordVisible,
|
||||
),
|
||||
if (_error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 12),
|
||||
child: Text(
|
||||
_error!,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _submit,
|
||||
child: _saving
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Text('Update password'),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@ -2,16 +2,19 @@
|
||||
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/errors/app_exception.dart';
|
||||
import '../../../core/theme/app_theme.dart';
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
import '../../../data/repositories/auth_repository_impl.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';
|
||||
|
||||
/// Form to view and update the authenticated user's profile via the API.
|
||||
class ProfileEditScreen extends StatefulWidget {
|
||||
@ -181,6 +184,12 @@ class _ProfileEditScreenState extends State<ProfileEditScreen> {
|
||||
final selected = await showModalBottomSheet<String>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
useRootNavigator: true,
|
||||
showDragHandle: true,
|
||||
backgroundColor: Theme.of(context).colorScheme.surface,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
builder: (ctx) {
|
||||
var query = '';
|
||||
return StatefulBuilder(
|
||||
@ -197,12 +206,13 @@ class _ProfileEditScreenState extends State<ProfileEditScreen> {
|
||||
child: Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
|
||||
padding: const EdgeInsets.fromLTRB(20, 8, 20, 8),
|
||||
child: TextField(
|
||||
controller: _countrySearchController,
|
||||
decoration: InputDecoration(
|
||||
hintText:
|
||||
nationality ? s.nationalityOptional : s.countryOfResidence,
|
||||
hintText: nationality
|
||||
? s.nationalityOptional
|
||||
: s.countryOfResidence,
|
||||
prefixIcon: const Icon(Icons.search),
|
||||
),
|
||||
onChanged: (v) => setModal(() => query = v.trim()),
|
||||
@ -249,7 +259,8 @@ class _ProfileEditScreenState extends State<ProfileEditScreen> {
|
||||
: null;
|
||||
final picked = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: initial ?? DateTime.now().subtract(const Duration(days: 365 * 18)),
|
||||
initialDate:
|
||||
initial ?? DateTime.now().subtract(const Duration(days: 365 * 18)),
|
||||
firstDate: DateTime(1900),
|
||||
lastDate: DateTime.now(),
|
||||
);
|
||||
@ -268,7 +279,10 @@ class _ProfileEditScreenState extends State<ProfileEditScreen> {
|
||||
}
|
||||
final country = _countryCode;
|
||||
final gender = _gender;
|
||||
if (country == null || country.length != 2 || gender == null || gender.isEmpty) {
|
||||
if (country == null ||
|
||||
country.length != 2 ||
|
||||
gender == null ||
|
||||
gender.isEmpty) {
|
||||
showErrorSnackBar(context, s.profileCountryRequired);
|
||||
return;
|
||||
}
|
||||
@ -311,193 +325,269 @@ class _ProfileEditScreenState extends State<ProfileEditScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
return Scaffold(
|
||||
key: const Key('profile_edit_screen'),
|
||||
appBar: AppBar(
|
||||
title: Text(s.updateProfile),
|
||||
flexibleSpace: Container(
|
||||
decoration: const BoxDecoration(gradient: AppTheme.goldGradient),
|
||||
),
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back_rounded),
|
||||
onPressed: () => context.pop(),
|
||||
),
|
||||
),
|
||||
body: RefreshIndicator(
|
||||
onRefresh: () async {
|
||||
await Future.wait([
|
||||
_loadProfile(force: true),
|
||||
_loadCountries(force: true),
|
||||
]);
|
||||
},
|
||||
child: SingleChildScrollView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
s.profileEditHint,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
if (_profileError != null && !_profileReady)
|
||||
SectionError(
|
||||
message: _profileError!,
|
||||
retrying: _profileRetrying,
|
||||
onRetry: () => _loadProfile(force: true),
|
||||
)
|
||||
else if (_profileLoading && !_profileReady) ...[
|
||||
const PredSkeletonCard(height: 56),
|
||||
const SizedBox(height: 12),
|
||||
const PredSkeletonCard(height: 56),
|
||||
const SizedBox(height: 12),
|
||||
const PredSkeletonCard(height: 56),
|
||||
const SizedBox(height: 12),
|
||||
const PredSkeletonCard(height: 56),
|
||||
] else ...[
|
||||
TextField(
|
||||
controller: _firstNameController,
|
||||
enabled: !_saving,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.firstName,
|
||||
border: const OutlineInputBorder(),
|
||||
prefixIcon: const Icon(Icons.person_outline_rounded),
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
|
||||
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
key: const Key('profile_edit_screen'),
|
||||
body: Column(
|
||||
children: [
|
||||
TlotoGradientAppBar(
|
||||
title: s.updateProfile,
|
||||
showBack: true,
|
||||
),
|
||||
Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () async {
|
||||
await Future.wait([
|
||||
_loadProfile(force: true),
|
||||
_loadCountries(force: true),
|
||||
]);
|
||||
},
|
||||
child: SingleChildScrollView(
|
||||
physics: const AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
),
|
||||
textCapitalization: TextCapitalization.words,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _middleNameController,
|
||||
enabled: !_saving,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.middleName,
|
||||
border: const OutlineInputBorder(),
|
||||
prefixIcon: const Icon(Icons.person_outline_rounded),
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
20,
|
||||
16,
|
||||
20,
|
||||
24 + bottomInset + keyboardInset,
|
||||
),
|
||||
textCapitalization: TextCapitalization.words,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _lastNameController,
|
||||
enabled: !_saving,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.lastName,
|
||||
border: const OutlineInputBorder(),
|
||||
prefixIcon: const Icon(Icons.person_outline_rounded),
|
||||
),
|
||||
textCapitalization: TextCapitalization.words,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _dateOfBirthController,
|
||||
enabled: !_saving,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.dateOfBirth,
|
||||
border: const OutlineInputBorder(),
|
||||
prefixIcon: const Icon(Icons.calendar_today_rounded),
|
||||
suffixIcon: IconButton(
|
||||
icon: const Icon(Icons.event_rounded),
|
||||
onPressed: _saving ? null : _pickDate,
|
||||
),
|
||||
hintText: 'YYYY-MM-DD',
|
||||
),
|
||||
readOnly: true,
|
||||
onTap: _saving ? null : _pickDate,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(s.genderRequired, style: Theme.of(context).textTheme.labelLarge),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
for (final entry in [
|
||||
('male', s.genderMale),
|
||||
('female', s.genderFemale),
|
||||
('other', s.genderOther),
|
||||
])
|
||||
ChoiceChip(
|
||||
label: Text(entry.$2),
|
||||
selected: _gender == entry.$1,
|
||||
onSelected: _saving
|
||||
? null
|
||||
: (_) => setState(() => _gender = entry.$1),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
s.profileEditHint,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Theme.of(context)
|
||||
.colorScheme
|
||||
.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _emailController,
|
||||
enabled: !_saving,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.emailRequired,
|
||||
border: const OutlineInputBorder(),
|
||||
prefixIcon: const Icon(Icons.email_outlined),
|
||||
),
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
autocorrect: false,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _phoneController,
|
||||
enabled: !_saving,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.phoneOptional,
|
||||
border: const OutlineInputBorder(),
|
||||
prefixIcon: const Icon(Icons.phone_outlined),
|
||||
),
|
||||
keyboardType: TextInputType.phone,
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
if (_countriesError != null && _countries.isEmpty)
|
||||
SectionError(
|
||||
compact: true,
|
||||
message: _countriesError!,
|
||||
retrying: _countriesRetrying,
|
||||
onRetry: () => _loadCountries(force: true),
|
||||
)
|
||||
else if (_countriesLoading && _countries.isEmpty) ...[
|
||||
const PredSkeletonCard(height: 56),
|
||||
const SizedBox(height: 12),
|
||||
const PredSkeletonCard(height: 56),
|
||||
] else ...[
|
||||
_SelectField(
|
||||
label: s.countryOfResidence,
|
||||
value: _countryLabel(_countryCode),
|
||||
enabled: !_saving && _countries.isNotEmpty,
|
||||
onTap: () => _pickCountry(nationality: false),
|
||||
helper: s.countryHelper,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_SelectField(
|
||||
label: s.nationalityOptional,
|
||||
value: _countryLabel(_nationalityCode),
|
||||
enabled: !_saving && _countries.isNotEmpty,
|
||||
onTap: () => _pickCountry(nationality: true),
|
||||
clearable: _nationalityCode != null,
|
||||
onClear:
|
||||
_saving ? null : () => setState(() => _nationalityCode = null),
|
||||
),
|
||||
],
|
||||
if (_profileReady) ...[
|
||||
const SizedBox(height: 24),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: _saving
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
const SizedBox(height: 16),
|
||||
if (_profileError != null && !_profileReady)
|
||||
SectionError(
|
||||
message: _profileError!,
|
||||
retrying: _profileRetrying,
|
||||
onRetry: () => _loadProfile(force: true),
|
||||
)
|
||||
: Text(s.saveProfile),
|
||||
else if (_profileLoading && !_profileReady) ...[
|
||||
const PredSkeletonCard(height: 56),
|
||||
const SizedBox(height: 12),
|
||||
const PredSkeletonCard(height: 56),
|
||||
const SizedBox(height: 12),
|
||||
const PredSkeletonCard(height: 56),
|
||||
const SizedBox(height: 12),
|
||||
const PredSkeletonCard(height: 56),
|
||||
] else ...[
|
||||
PredCard(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
s.profileSectionPersonal,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _firstNameController,
|
||||
enabled: !_saving,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.firstName,
|
||||
prefixIcon: const Icon(
|
||||
Icons.person_outline_rounded,
|
||||
),
|
||||
),
|
||||
textCapitalization: TextCapitalization.words,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _middleNameController,
|
||||
enabled: !_saving,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.middleName,
|
||||
prefixIcon: const Icon(
|
||||
Icons.person_outline_rounded,
|
||||
),
|
||||
),
|
||||
textCapitalization: TextCapitalization.words,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _lastNameController,
|
||||
enabled: !_saving,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.lastName,
|
||||
prefixIcon: const Icon(
|
||||
Icons.person_outline_rounded,
|
||||
),
|
||||
),
|
||||
textCapitalization: TextCapitalization.words,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _dateOfBirthController,
|
||||
enabled: !_saving,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.dateOfBirth,
|
||||
prefixIcon: const Icon(
|
||||
Icons.calendar_today_rounded,
|
||||
),
|
||||
suffixIcon: IconButton(
|
||||
icon: const Icon(Icons.event_rounded),
|
||||
onPressed: _saving ? null : _pickDate,
|
||||
),
|
||||
hintText: s.dateOfBirthHint,
|
||||
),
|
||||
readOnly: true,
|
||||
onTap: _saving ? null : _pickDate,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
s.genderRequired,
|
||||
style: Theme.of(context).textTheme.labelLarge,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
for (final entry in [
|
||||
('male', s.genderMale),
|
||||
('female', s.genderFemale),
|
||||
('other', s.genderOther),
|
||||
])
|
||||
ChoiceChip(
|
||||
label: Text(entry.$2),
|
||||
selected: _gender == entry.$1,
|
||||
onSelected: _saving
|
||||
? null
|
||||
: (_) => setState(
|
||||
() => _gender = entry.$1,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
PredCard(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
s.profileSectionContact,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _emailController,
|
||||
enabled: !_saving,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.emailRequired,
|
||||
prefixIcon:
|
||||
const Icon(Icons.email_outlined),
|
||||
),
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
autocorrect: false,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _phoneController,
|
||||
enabled: !_saving,
|
||||
decoration: InputDecoration(
|
||||
labelText: s.phoneOptional,
|
||||
prefixIcon:
|
||||
const Icon(Icons.phone_outlined),
|
||||
),
|
||||
keyboardType: TextInputType.phone,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
if (_countriesError != null && _countries.isEmpty)
|
||||
SectionError(
|
||||
compact: true,
|
||||
message: _countriesError!,
|
||||
retrying: _countriesRetrying,
|
||||
onRetry: () => _loadCountries(force: true),
|
||||
)
|
||||
else if (_countriesLoading && _countries.isEmpty) ...[
|
||||
const PredSkeletonCard(height: 56),
|
||||
const SizedBox(height: 12),
|
||||
const PredSkeletonCard(height: 56),
|
||||
] else
|
||||
PredCard(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
s.profileSectionLocation,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_SelectField(
|
||||
label: s.countryOfResidence,
|
||||
value: _countryLabel(_countryCode),
|
||||
enabled: !_saving && _countries.isNotEmpty,
|
||||
onTap: () =>
|
||||
_pickCountry(nationality: false),
|
||||
helper: s.countryHelper,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_SelectField(
|
||||
label: s.nationalityOptional,
|
||||
value: _countryLabel(_nationalityCode),
|
||||
enabled: !_saving && _countries.isNotEmpty,
|
||||
onTap: () =>
|
||||
_pickCountry(nationality: true),
|
||||
clearable: _nationalityCode != null,
|
||||
onClear: _saving
|
||||
? null
|
||||
: () => setState(
|
||||
() => _nationalityCode = null,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (_profileReady) ...[
|
||||
const SizedBox(height: 20),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: _saving
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
)
|
||||
: Text(s.saveProfile),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
@ -532,14 +622,15 @@ class _SelectField extends StatelessWidget {
|
||||
decoration: InputDecoration(
|
||||
labelText: label,
|
||||
helperText: helper,
|
||||
border: const OutlineInputBorder(),
|
||||
suffixIcon: clearable
|
||||
? IconButton(icon: const Icon(Icons.clear), onPressed: onClear)
|
||||
: const Icon(Icons.arrow_drop_down),
|
||||
),
|
||||
child: Text(
|
||||
value ?? '—',
|
||||
style: TextStyle(color: value == null ? AppColors.textMuted : null),
|
||||
style: TextStyle(
|
||||
color: value == null ? AppColors.textMuted : null,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@ -2,18 +2,22 @@
|
||||
library;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../../../core/di/injection.dart';
|
||||
import '../../../core/errors/app_exception.dart';
|
||||
import '../../../core/theme/app_theme.dart';
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
import '../../../core/utils/amount_utils.dart';
|
||||
import '../../../core/utils/coin_display.dart';
|
||||
import '../../../data/models/transaction_model.dart';
|
||||
import '../../../data/models/wallet_type_model.dart';
|
||||
import '../../../core/di/injection.dart';
|
||||
import '../../../data/repositories/wallet_repository_impl.dart';
|
||||
import '../../../features/share_cards/presentation/share_result_widgets.dart';
|
||||
import '../../../l10n/app_strings.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/transaction_display.dart';
|
||||
|
||||
@ -22,7 +26,8 @@ class TransactionHistoryScreen extends StatefulWidget {
|
||||
const TransactionHistoryScreen({super.key});
|
||||
|
||||
@override
|
||||
State<TransactionHistoryScreen> createState() => _TransactionHistoryScreenState();
|
||||
State<TransactionHistoryScreen> createState() =>
|
||||
_TransactionHistoryScreenState();
|
||||
}
|
||||
|
||||
/// Manages paginated loading state and wallet type lookup for display.
|
||||
@ -41,7 +46,6 @@ class _TransactionHistoryScreenState extends State<TransactionHistoryScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Paint wallet types immediately from the app-scoped WalletBloc when present.
|
||||
final blocTypes = context.read<WalletBloc>().state.walletTypes;
|
||||
if (blocTypes.isNotEmpty) {
|
||||
_walletTypes = blocTypes;
|
||||
@ -73,7 +77,6 @@ class _TransactionHistoryScreenState extends State<TransactionHistoryScreen> {
|
||||
_loading = true;
|
||||
if (!force) _error = null;
|
||||
} else {
|
||||
// Keep list painted during pull-to-refresh.
|
||||
_loadingMore = true;
|
||||
if (!force) _error = null;
|
||||
}
|
||||
@ -84,9 +87,9 @@ class _TransactionHistoryScreenState extends State<TransactionHistoryScreen> {
|
||||
|
||||
try {
|
||||
final list = await sl<WalletRepository>().getTransactions(
|
||||
limit: _pageSize,
|
||||
offset: reset ? 0 : _offset,
|
||||
);
|
||||
limit: _pageSize,
|
||||
offset: reset ? 0 : _offset,
|
||||
);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
if (reset) _transactions.clear();
|
||||
@ -121,150 +124,431 @@ class _TransactionHistoryScreenState extends State<TransactionHistoryScreen> {
|
||||
return null;
|
||||
}
|
||||
|
||||
String _formatDate(String isoDate) {
|
||||
try {
|
||||
final d = DateTime.parse(isoDate).toLocal();
|
||||
return '${d.day.toString().padLeft(2, '0')}/'
|
||||
'${d.month.toString().padLeft(2, '0')}/'
|
||||
'${d.year} '
|
||||
'${d.hour.toString().padLeft(2, '0')}:'
|
||||
'${d.minute.toString().padLeft(2, '0')}';
|
||||
} catch (_) {
|
||||
return isoDate;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
return Scaffold(
|
||||
key: const Key('transaction_history_screen'),
|
||||
appBar: AppBar(
|
||||
title: Text(s.activityHistory),
|
||||
flexibleSpace: Container(
|
||||
decoration: const BoxDecoration(gradient: AppTheme.goldGradient),
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
final bottomInset = MediaQuery.paddingOf(context).bottom;
|
||||
final muted = isDark ? AppColors.textMuted : const Color(0xFF94A3B8);
|
||||
final secondary =
|
||||
isDark ? AppColors.textSecondary : const Color(0xFF475569);
|
||||
|
||||
return AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: TlotoGradientAppBar.overlayStyle,
|
||||
child: Scaffold(
|
||||
key: const Key('transaction_history_screen'),
|
||||
body: Column(
|
||||
children: [
|
||||
TlotoGradientAppBar(
|
||||
title: s.activityHistory,
|
||||
showBack: true,
|
||||
),
|
||||
Expanded(
|
||||
child: RefreshIndicator(
|
||||
onRefresh: () => _loadPage(reset: true, force: true),
|
||||
child: _buildBody(s, muted, secondary, bottomInset),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: RefreshIndicator(
|
||||
onRefresh: () => _loadPage(reset: true, force: true),
|
||||
child: _error != null && _transactions.isEmpty
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _loadPage(reset: true, force: true),
|
||||
),
|
||||
],
|
||||
)
|
||||
: _loading && _transactions.isEmpty
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
],
|
||||
)
|
||||
: _transactions.isEmpty
|
||||
? ListView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(40),
|
||||
children: [
|
||||
Icon(Icons.inbox_outlined, size: 40, color: AppColors.textMuted),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
s.noTransactionsYet,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: ListView.builder(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: _transactions.length + (_hasMore ? 1 : 0),
|
||||
itemBuilder: (context, index) {
|
||||
if (index >= _transactions.length) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
||||
child: Center(
|
||||
child: _loadingMore
|
||||
? const SizedBox(
|
||||
width: 28,
|
||||
height: 28,
|
||||
child: CircularProgressIndicator(strokeWidth: 2.5),
|
||||
)
|
||||
: OutlinedButton(
|
||||
key: const Key('tx_history_load_more'),
|
||||
onPressed: () => _loadPage(),
|
||||
child: Text(s.loadMore),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final tx = _transactions[index];
|
||||
final wt = _typeFor(tx.walletTypeId);
|
||||
final decimals = wt?.decimals ?? 6;
|
||||
final code = wt?.code ?? '';
|
||||
final currency = wt?.name ?? 'ID ${tx.walletTypeId}';
|
||||
final credit = isTransactionCredit(tx);
|
||||
final amount = rawAmountToHuman(tx.amount, decimals);
|
||||
final fee = rawAmountToHuman(tx.fee, decimals);
|
||||
final feeValue = double.tryParse(fee) ?? 0;
|
||||
final showFee = tx.type == 'withdrawal' && feeValue > 0;
|
||||
final totalDisplay =
|
||||
showFee ? _addHumanAmounts(amount, fee) : amount;
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
child: ListTile(
|
||||
leading: CoinDisplay.iconWidget(context, code, size: 44),
|
||||
title: Text(
|
||||
'${transactionLabel(tx, s)} · $currency',
|
||||
style: const TextStyle(fontWeight: FontWeight.w600),
|
||||
),
|
||||
subtitle: Text(
|
||||
showFee
|
||||
? '${_formatDate(tx.createdAt)} · ${transactionStatusLabel(tx.status, s)}\n'
|
||||
'$amount · Fee $fee'
|
||||
: '${_formatDate(tx.createdAt)} · ${transactionStatusLabel(tx.status, s)}',
|
||||
),
|
||||
isThreeLine: showFee,
|
||||
trailing: Text(
|
||||
'${credit ? '+' : '-'}$totalDisplay',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w600,
|
||||
color: credit ? Colors.green : Colors.orange,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
static String _addHumanAmounts(String a, String b) {
|
||||
try {
|
||||
final da = double.parse(a);
|
||||
final db = double.parse(b);
|
||||
final sum = da + db;
|
||||
return sum
|
||||
.toStringAsFixed(6)
|
||||
.replaceAll(RegExp(r'0+$'), '')
|
||||
.replaceAll(RegExp(r'\.$'), '');
|
||||
} catch (_) {
|
||||
return a;
|
||||
Widget _buildBody(
|
||||
AppStrings s,
|
||||
Color muted,
|
||||
Color secondary,
|
||||
double bottomInset,
|
||||
) {
|
||||
const physics = AlwaysScrollableScrollPhysics(
|
||||
parent: BouncingScrollPhysics(),
|
||||
);
|
||||
|
||||
if (_error != null && _transactions.isEmpty) {
|
||||
return ListView(
|
||||
physics: physics,
|
||||
padding: EdgeInsets.fromLTRB(20, 16, 20, 24 + bottomInset),
|
||||
children: [
|
||||
SectionError(
|
||||
message: _error!,
|
||||
retrying: _retrying,
|
||||
onRetry: () => _loadPage(reset: true, force: true),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
if (_loading && _transactions.isEmpty) {
|
||||
return ListView(
|
||||
physics: physics,
|
||||
padding: EdgeInsets.fromLTRB(20, 16, 20, 24 + bottomInset),
|
||||
children: const [
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
SizedBox(height: 8),
|
||||
PredSkeletonCard(height: 72),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
if (_transactions.isEmpty) {
|
||||
return ListView(
|
||||
physics: physics,
|
||||
padding: EdgeInsets.fromLTRB(40, 40, 40, 40 + bottomInset),
|
||||
children: [
|
||||
Icon(Icons.inbox_outlined, size: 48, color: muted),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
s.noTransactionsYet,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: secondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
return ListView.separated(
|
||||
physics: physics,
|
||||
padding: EdgeInsets.fromLTRB(20, 12, 20, 24 + bottomInset),
|
||||
itemCount: _transactions.length + (_hasMore ? 1 : 0),
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 8),
|
||||
itemBuilder: (context, index) {
|
||||
if (index >= _transactions.length) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Center(
|
||||
child: _loadingMore
|
||||
? const SizedBox(
|
||||
width: 28,
|
||||
height: 28,
|
||||
child: CircularProgressIndicator(strokeWidth: 2.5),
|
||||
)
|
||||
: TextButton(
|
||||
key: const Key('tx_history_load_more'),
|
||||
onPressed: () => _loadPage(),
|
||||
child: Text(
|
||||
s.loadMoreRemaining(_pageSize),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final tx = _transactions[index];
|
||||
final wt = _typeFor(tx.walletTypeId);
|
||||
final decimals = wt?.decimals ?? 6;
|
||||
final code = wt?.code ?? '';
|
||||
final isPrediction = tx.type == 'game_stake' ||
|
||||
tx.type == 'game_payout' ||
|
||||
tx.type == 'game_refund';
|
||||
if (isPrediction) {
|
||||
return _HistoryPredictionTile(
|
||||
tx: tx,
|
||||
decimals: decimals,
|
||||
assetCode: code,
|
||||
strings: s,
|
||||
);
|
||||
}
|
||||
return _HistoryStatusTile(
|
||||
tx: tx,
|
||||
decimals: decimals,
|
||||
assetCode: code,
|
||||
strings: s,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _HistoryStatusTile extends StatelessWidget {
|
||||
const _HistoryStatusTile({
|
||||
required this.tx,
|
||||
required this.decimals,
|
||||
required this.assetCode,
|
||||
required this.strings,
|
||||
});
|
||||
|
||||
final TransactionModel tx;
|
||||
final int decimals;
|
||||
final String assetCode;
|
||||
final AppStrings strings;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final credit = isTransactionCredit(tx);
|
||||
final feeRaw = BigInt.tryParse(tx.fee) ?? BigInt.zero;
|
||||
final showWithdrawalFee = tx.type == 'withdrawal' && feeRaw > BigInt.zero;
|
||||
final amountRaw = BigInt.tryParse(tx.amount) ?? BigInt.zero;
|
||||
final totalRaw = amountRaw + feeRaw;
|
||||
final amount = showWithdrawalFee
|
||||
? '-${rawAmountToHuman(totalRaw.toString(), decimals)} USDT'
|
||||
: _formatSignedAmount(
|
||||
tx: tx,
|
||||
credit: credit,
|
||||
decimals: decimals,
|
||||
assetCode: assetCode,
|
||||
);
|
||||
final status = transactionStatusLabel(tx.status, strings);
|
||||
final statusColor = _statusColor(tx.status);
|
||||
final canShare = tx.type == 'deposit' ||
|
||||
tx.type == 'withdrawal' ||
|
||||
tx.type == 'transfer' ||
|
||||
tx.type == 'bonus' ||
|
||||
tx.type == 'admin_adjustment';
|
||||
|
||||
return PredCard(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
Container(
|
||||
width: 40,
|
||||
height: 40,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: (credit ? AppColors.success : AppColors.info)
|
||||
.withValues(alpha: 0.15),
|
||||
),
|
||||
child: Icon(
|
||||
credit ? Icons.south_west_rounded : Icons.north_east_rounded,
|
||||
size: 18,
|
||||
color: credit ? AppColors.success : AppColors.info,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
transactionLabel(tx, strings),
|
||||
style: const TextStyle(fontWeight: FontWeight.w700),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
if (canShare)
|
||||
ShareResultIconButton(
|
||||
transactionId: tx.id,
|
||||
operationType: tx.type,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
_formatDateTime(tx.createdAt),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
if (showWithdrawalFee) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
strings.withdrawnFeeDetail(
|
||||
rawAmountToHuman(tx.amount, decimals),
|
||||
rawAmountToHuman(tx.fee, decimals),
|
||||
),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
fontSize: 11,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(
|
||||
amount,
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w800,
|
||||
color: credit ? AppColors.success : AppColors.textPrimary,
|
||||
),
|
||||
),
|
||||
if (showWithdrawalFee) ...[
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
strings.totalDebitedLabel,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
fontSize: 10,
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 4),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: statusColor.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
),
|
||||
child: Text(
|
||||
status,
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w700,
|
||||
color: statusColor,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _HistoryPredictionTile extends StatelessWidget {
|
||||
const _HistoryPredictionTile({
|
||||
required this.tx,
|
||||
required this.decimals,
|
||||
required this.assetCode,
|
||||
required this.strings,
|
||||
});
|
||||
|
||||
final TransactionModel tx;
|
||||
final int decimals;
|
||||
final String assetCode;
|
||||
final AppStrings strings;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final credit = isTransactionCredit(tx);
|
||||
final amount = _formatSignedAmount(
|
||||
tx: tx,
|
||||
credit: credit,
|
||||
decimals: decimals,
|
||||
assetCode: assetCode,
|
||||
);
|
||||
final wallet = stakeAccountKindLabel(stakeAccountKind(tx), strings);
|
||||
final betId = (tx.metadata?['bet_id'] ?? '').toString();
|
||||
|
||||
return PredCard(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 40,
|
||||
height: 40,
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: (credit ? AppColors.success : AppColors.danger)
|
||||
.withValues(alpha: 0.15),
|
||||
),
|
||||
child: Icon(
|
||||
credit ? Icons.trending_up_rounded : Icons.trending_down_rounded,
|
||||
size: 18,
|
||||
color: credit ? AppColors.success : AppColors.danger,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
transactionLabel(tx, strings),
|
||||
style: const TextStyle(fontWeight: FontWeight.w700),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
_formatDateTime(tx.createdAt),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
'${strings.stakeWallet}: $wallet',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: AppColors.textMuted,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Text(
|
||||
amount,
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.w800,
|
||||
color: credit ? AppColors.success : AppColors.danger,
|
||||
),
|
||||
),
|
||||
if (betId.isNotEmpty) ...[
|
||||
if (tx.type == 'game_payout')
|
||||
ShareResultIconButton(
|
||||
key: ValueKey('share-hist-$betId'),
|
||||
betId: betId,
|
||||
status: 'won',
|
||||
stakeAccountKind: stakeAccountKind(tx),
|
||||
)
|
||||
else if (tx.type == 'game_refund')
|
||||
ShareResultIconButton(
|
||||
key: ValueKey('share-hist-$betId'),
|
||||
betId: betId,
|
||||
status: 'refunded',
|
||||
stakeAccountKind: stakeAccountKind(tx),
|
||||
)
|
||||
else if (tx.type == 'game_stake' &&
|
||||
tx.metadata?['bet_status']?.toString() == 'lost')
|
||||
ShareResultIconButton(
|
||||
key: ValueKey('share-hist-$betId'),
|
||||
betId: betId,
|
||||
status: 'lost',
|
||||
stakeAccountKind: stakeAccountKind(tx),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _formatDateTime(String iso) {
|
||||
final dt = DateTime.tryParse(iso)?.toLocal();
|
||||
if (dt == null) return iso;
|
||||
return DateFormat('dd/MM/yyyy HH:mm').format(dt);
|
||||
}
|
||||
|
||||
String _formatSignedAmount({
|
||||
required TransactionModel tx,
|
||||
required bool credit,
|
||||
required int decimals,
|
||||
required String assetCode,
|
||||
}) {
|
||||
final human = rawAmountToHuman(tx.amount, decimals);
|
||||
final symbol =
|
||||
assetCode.toUpperCase().contains('USDT') ? 'USDT' : assetCode;
|
||||
final sign = credit ? '+' : '-';
|
||||
return '$sign$human $symbol';
|
||||
}
|
||||
|
||||
Color _statusColor(String status) {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
case 'confirmed':
|
||||
return AppColors.success;
|
||||
case 'pending':
|
||||
case 'broadcasting':
|
||||
return AppColors.warning;
|
||||
case 'rejected':
|
||||
case 'failed':
|
||||
case 'cancelled':
|
||||
case 'canceled':
|
||||
return AppColors.danger;
|
||||
default:
|
||||
return AppColors.textSecondary;
|
||||
}
|
||||
}
|
||||
|
||||
@ -259,6 +259,15 @@ class AppStrings {
|
||||
'Code 2FA (requis pour le retrait)',
|
||||
);
|
||||
String get totpSixDigit => t('6-digit code', 'Code à 6 chiffres');
|
||||
String get enterSixDigitTotp => t(
|
||||
'Enter a valid 6-digit authenticator code',
|
||||
'Saisissez un code d’authentification à 6 chiffres valide',
|
||||
);
|
||||
String get twoFactorDisableSection => t('Disable 2FA', 'Désactiver la 2FA');
|
||||
String get twoFactorRegenSection => t(
|
||||
'Recovery codes',
|
||||
'Codes de récupération',
|
||||
);
|
||||
String get confirmWithdrawal => t('Confirm withdrawal', 'Confirmer le retrait');
|
||||
String get confirmTransfer => t('Confirm transfer', 'Confirmer le transfert');
|
||||
String get confirmAction => t('Confirm', 'Confirmer');
|
||||
@ -310,6 +319,11 @@ class AppStrings {
|
||||
t('Network fee: $fee USDT', 'Frais réseau : $fee USDT');
|
||||
String withdrawTotalDebited(String total) =>
|
||||
t('Total debited: $total USDT', 'Total débité : $total USDT');
|
||||
String get totalDebitedLabel => t('Total debited', 'Total débité');
|
||||
String withdrawnFeeDetail(String amount, String fee) => t(
|
||||
'Withdrawn $amount USDT · Fee $fee USDT',
|
||||
'Retiré $amount USDT · Frais $fee USDT',
|
||||
);
|
||||
String availableUsdt(String amount) =>
|
||||
t('Available: $amount USDT', 'Disponible : $amount USDT');
|
||||
String availableAsset(String amount, String code) =>
|
||||
@ -428,6 +442,10 @@ class AppStrings {
|
||||
String get placeBet => placePrediction;
|
||||
String get placeMultiBet => placeMultiPrediction;
|
||||
String get predictionPlaced => t('Prediction placed', 'Prédiction placée');
|
||||
String get predictionDbReadonly => t(
|
||||
'Server database is in read-only mode. Predictions cannot be saved right now — check DATABASE_URL points to the primary database.',
|
||||
'La base de données du serveur est en lecture seule. Les prédictions ne peuvent pas être enregistrées — vérifiez que DATABASE_URL pointe vers la base principale.',
|
||||
);
|
||||
String stakeAmountTitle(String coin) => t('Amount ($coin)', 'Montant ($coin)');
|
||||
String stakeAmountHint(num min, num max) => t(
|
||||
'Min $min · Max $max',
|
||||
@ -775,6 +793,27 @@ class AppStrings {
|
||||
'Le pays de résidence et le genre sont obligatoires.',
|
||||
);
|
||||
String get changePassword => t('Change password', 'Changer le mot de passe');
|
||||
String get changePasswordHint => t(
|
||||
'Enter your current password and choose a new one. New password must meet the system security policy.',
|
||||
'Saisissez votre mot de passe actuel puis un nouveau. Il doit respecter la politique de sécurité.',
|
||||
);
|
||||
String get currentPassword => t('Current password', 'Mot de passe actuel');
|
||||
String get newPassword => t('New password', 'Nouveau mot de passe');
|
||||
String get confirmNewPassword => t('Confirm new password', 'Confirmer le nouveau mot de passe');
|
||||
String get updatePassword => t('Update password', 'Mettre à jour le mot de passe');
|
||||
String get enterCurrentPassword => t(
|
||||
'Enter your current password',
|
||||
'Saisissez votre mot de passe actuel',
|
||||
);
|
||||
String get enterNewPassword => t('Enter a new password', 'Saisissez un nouveau mot de passe');
|
||||
String get passwordUpdatedSignInAgain => t(
|
||||
'Password updated. Please sign in again.',
|
||||
'Mot de passe mis à jour. Veuillez vous reconnecter.',
|
||||
);
|
||||
String get dateOfBirthHint => t('YYYY-MM-DD', 'AAAA-MM-JJ');
|
||||
String get profileSectionPersonal => t('Personal', 'Identité');
|
||||
String get profileSectionContact => t('Contact', 'Coordonnées');
|
||||
String get profileSectionLocation => t('Location', 'Localisation');
|
||||
String get twoFactor => t('Two-factor authentication (2FA)', 'Authentification à deux facteurs');
|
||||
String get twoFactorEnabledShort => t('2FA enabled', '2FA activée');
|
||||
String get twoFactorEnabled => t('2FA is enabled on your account.', 'La 2FA est activée sur votre compte.');
|
||||
@ -859,6 +898,122 @@ class AppStrings {
|
||||
String get settings => t('Settings', 'Paramètres');
|
||||
String get security => t('Security', 'Sécurité');
|
||||
String get users => t('Users', 'Utilisateurs');
|
||||
String get userManagement => t('User Management', 'Gestion des utilisateurs');
|
||||
String get usersManageSubtitle => t(
|
||||
'View and manage registered users',
|
||||
'Voir et gérer les utilisateurs inscrits',
|
||||
);
|
||||
String get usersSearchHint => t(
|
||||
'Email, user ID, name, or referral code',
|
||||
'E-mail, ID utilisateur, nom ou code de parrainage',
|
||||
);
|
||||
String get usersSearchHelper => t(
|
||||
'Exact email, full/partial UUID, name, or referral code',
|
||||
'E-mail exact, UUID (complet/partiel), nom ou code de parrainage',
|
||||
);
|
||||
String get noUsersFound => t('No users found', 'Aucun utilisateur trouvé');
|
||||
String get confirmChange => t('Confirm change', 'Confirmer la modification');
|
||||
String get viewUserDetails => t(
|
||||
'View full details & balance',
|
||||
'Voir le détail et le solde',
|
||||
);
|
||||
String get accountNonExpired => t(
|
||||
'Account non expired',
|
||||
'Compte non expiré',
|
||||
);
|
||||
String get accountNonLocked => t(
|
||||
'Account non locked',
|
||||
'Compte non verrouillé',
|
||||
);
|
||||
String get credentialsNonExpired => t(
|
||||
'Credentials non expired',
|
||||
'Identifiants non expirés',
|
||||
);
|
||||
String get createdAtLabel => t('Created', 'Créé');
|
||||
String get userDetails => t('User details', 'Détails utilisateur');
|
||||
String get accountStatus => t('Account status', 'État du compte');
|
||||
String get balances => t('Balances', 'Soldes');
|
||||
String get noBalances => t('No balances', 'Aucun solde');
|
||||
String get userNotFound => t('User not found', 'Utilisateur introuvable');
|
||||
String get userIdLabel => t('User ID', 'ID utilisateur');
|
||||
String get roleLabel => t('Role', 'Rôle');
|
||||
String get emailVerifiedLabel => t('Email verified', 'E-mail vérifié');
|
||||
String get totpEnabledLabel => t('TOTP enabled', 'TOTP activé');
|
||||
String get yes => t('Yes', 'Oui');
|
||||
String get no => t('No', 'Non');
|
||||
String confirmFlagChange({
|
||||
required String flagName,
|
||||
required bool enabled,
|
||||
required String userLabel,
|
||||
}) =>
|
||||
t(
|
||||
'Set "$flagName" to ${enabled ? "enabled" : "disabled"} for user $userLabel?',
|
||||
'Passer « $flagName » à ${enabled ? "activé" : "désactivé"} pour $userLabel ?',
|
||||
);
|
||||
String get systemSettingsSubtitle => t(
|
||||
'Password policy, tokens, system configuration',
|
||||
'Politique mot de passe, jetons, configuration système',
|
||||
);
|
||||
String get noAdminOptions => t(
|
||||
'No administrative options available.',
|
||||
'Aucune option administrative disponible.',
|
||||
);
|
||||
String get accessDeniedAdmin => t(
|
||||
'Access denied. Admin only.',
|
||||
'Accès refusé. Réservé aux admins.',
|
||||
);
|
||||
String get passwordPolicy => t('Password policy', 'Politique de mot de passe');
|
||||
String get passwordPolicySubtitle => t(
|
||||
'Minimum length and character requirements',
|
||||
'Longueur minimale et exigences de caractères',
|
||||
);
|
||||
String get passwordMinLength => t('Minimum length', 'Longueur minimale');
|
||||
String get passwordMinLengthHelper => t(
|
||||
'Minimum password length (e.g. 8)',
|
||||
'Longueur minimale du mot de passe (ex. 8)',
|
||||
);
|
||||
String get requireUppercase => t(
|
||||
'Require uppercase letter',
|
||||
'Exiger une majuscule',
|
||||
);
|
||||
String get requireLowercase => t(
|
||||
'Require lowercase letter',
|
||||
'Exiger une minuscule',
|
||||
);
|
||||
String get requireNumber => t('Require number', 'Exiger un chiffre');
|
||||
String get requireSpecial => t(
|
||||
'Require special character',
|
||||
'Exiger un caractère spécial',
|
||||
);
|
||||
String get tokenExpiration => t('Token expiration', 'Expiration des jetons');
|
||||
String get tokenExpirationSubtitle => t(
|
||||
'Access and refresh token validity',
|
||||
'Validité des jetons d’accès et de rafraîchissement',
|
||||
);
|
||||
String get tokenExpiryHint => t(
|
||||
'Use values like 15m, 1h, 7d (minutes, hours, days). New tokens will use these values.',
|
||||
'Utilisez des valeurs comme 15m, 1h, 7d (minutes, heures, jours). Les nouveaux jetons utiliseront ces valeurs.',
|
||||
);
|
||||
String get accessTokenExpiry => t(
|
||||
'Access token expiry',
|
||||
'Expiration du jeton d’accès',
|
||||
);
|
||||
String get refreshTokenExpiry => t(
|
||||
'Refresh token expiry',
|
||||
'Expiration du jeton de rafraîchissement',
|
||||
);
|
||||
String get tokenExpiryExampleShort => t('e.g. 15m, 1h', 'ex. 15m, 1h');
|
||||
String get tokenExpiryExampleLong => t('e.g. 7d, 30d', 'ex. 7d, 30d');
|
||||
String get saveSettings => t('Save settings', 'Enregistrer les paramètres');
|
||||
String get settingsSaved => t('Settings saved', 'Paramètres enregistrés');
|
||||
String get passwordMinLengthInvalid => t(
|
||||
'Password minimum length must be between 1 and 128',
|
||||
'La longueur minimale du mot de passe doit être entre 1 et 128',
|
||||
);
|
||||
String get tokenExpiryRequired => t(
|
||||
'Token expiry values are required (e.g. 15m, 7d)',
|
||||
'Les valeurs d’expiration des jetons sont requises (ex. 15m, 7d)',
|
||||
);
|
||||
}
|
||||
|
||||
extension AppStringsX on BuildContext {
|
||||
|
||||
@ -2,19 +2,24 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'prediqo_logo.dart';
|
||||
|
||||
/// Edge-to-edge emerald→navy top bar shared by authenticated Tloto screens.
|
||||
/// Edge-to-edge emerald→navy top bar shared by Tloto screens (auth + app).
|
||||
class TlotoGradientAppBar extends StatelessWidget {
|
||||
const TlotoGradientAppBar({
|
||||
super.key,
|
||||
required this.title,
|
||||
this.showBack = false,
|
||||
this.showLogo = true,
|
||||
this.onBack,
|
||||
this.backButtonKey,
|
||||
this.actions = const [],
|
||||
});
|
||||
|
||||
final String title;
|
||||
final bool showBack;
|
||||
final bool showLogo;
|
||||
/// Custom back handler (e.g. guest FAQ → welcome). Defaults to [Navigator.maybePop].
|
||||
final VoidCallback? onBack;
|
||||
final Key? backButtonKey;
|
||||
final List<Widget> actions;
|
||||
|
||||
static const gradient = LinearGradient(
|
||||
@ -50,9 +55,10 @@ class TlotoGradientAppBar extends StatelessWidget {
|
||||
children: [
|
||||
if (showBack)
|
||||
IconButton(
|
||||
key: backButtonKey,
|
||||
tooltip:
|
||||
MaterialLocalizations.of(context).backButtonTooltip,
|
||||
onPressed: () => Navigator.of(context).maybePop(),
|
||||
onPressed: onBack ?? () => Navigator.of(context).maybePop(),
|
||||
icon: const Icon(
|
||||
Icons.arrow_back_rounded,
|
||||
color: Colors.white,
|
||||
|
||||
@ -12,6 +12,7 @@ import 'package:prediqo_mobile/data/repositories/auth_repository_impl.dart';
|
||||
import 'package:prediqo_mobile/domain/repositories/health_repository.dart';
|
||||
import 'package:prediqo_mobile/domain/repositories/repositories.dart';
|
||||
import 'package:prediqo_mobile/features/admin/presentation/network_screen.dart';
|
||||
import 'package:prediqo_mobile/features/admin/presentation/options_screen.dart';
|
||||
import 'package:prediqo_mobile/features/admin/presentation/settings_screen.dart';
|
||||
import 'package:prediqo_mobile/features/admin/presentation/user_detail_screen.dart';
|
||||
import 'package:prediqo_mobile/features/admin/presentation/user_management_screen.dart';
|
||||
@ -19,6 +20,7 @@ import 'package:prediqo_mobile/features/auth/bloc/auth_bloc.dart';
|
||||
import 'package:prediqo_mobile/l10n/locale_controller.dart';
|
||||
import 'package:prediqo_mobile/shared/widgets/pred_skeleton.dart';
|
||||
import 'package:prediqo_mobile/shared/widgets/section_error.dart';
|
||||
import 'package:prediqo_mobile/shared/widgets/tloto_gradient_app_bar.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'support/e2e_fixtures.dart';
|
||||
@ -63,6 +65,7 @@ class _ControllableAdmin extends AdminRepositoryImpl {
|
||||
String? search,
|
||||
int limit = 50,
|
||||
int offset = 0,
|
||||
bool force = false,
|
||||
}) async {
|
||||
listCalls++;
|
||||
if (failWith != null) throw failWith!;
|
||||
@ -71,7 +74,10 @@ class _ControllableAdmin extends AdminRepositoryImpl {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<AdminUserDetails?> getUserDetails(String userId) async {
|
||||
Future<AdminUserDetails?> getUserDetails(
|
||||
String userId, {
|
||||
bool force = false,
|
||||
}) async {
|
||||
detailCalls++;
|
||||
if (failWith != null) throw failWith!;
|
||||
if (detailHold != null) return detailHold!.future;
|
||||
@ -93,7 +99,7 @@ class _ControllableAdmin extends AdminRepositoryImpl {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<SystemSettings> getSettings() async {
|
||||
Future<SystemSettings> getSettings({bool force = false}) async {
|
||||
settingsCalls++;
|
||||
if (failWith != null) throw failWith!;
|
||||
if (settingsHold != null) return settingsHold!.future;
|
||||
@ -117,18 +123,26 @@ class _ControllableHealth implements HealthRepository {
|
||||
Completer<HealthStatus>? hold;
|
||||
Object? failWith;
|
||||
var calls = 0;
|
||||
HealthStatus? cached;
|
||||
|
||||
@override
|
||||
Future<HealthStatus> getHealth() async {
|
||||
Future<HealthStatus> getHealth({bool force = false}) async {
|
||||
calls++;
|
||||
if (failWith != null) throw failWith!;
|
||||
if (hold != null) return hold!.future;
|
||||
return const HealthStatus(
|
||||
network: 'shasta',
|
||||
withdrawalsEnabled: false,
|
||||
env: 'test',
|
||||
);
|
||||
return cached ??
|
||||
const HealthStatus(
|
||||
network: 'shasta',
|
||||
withdrawalsEnabled: false,
|
||||
env: 'test',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
HealthStatus? peekLast() => cached;
|
||||
|
||||
@override
|
||||
void invalidate() => cached = null;
|
||||
}
|
||||
|
||||
class _StubAuth implements AuthRepository {
|
||||
@ -257,7 +271,10 @@ void main() {
|
||||
await tester.pump();
|
||||
|
||||
expect(find.byKey(const Key('admin_users_screen')), findsOneWidget);
|
||||
expect(find.byType(TlotoGradientAppBar), findsOneWidget);
|
||||
expect(find.text('User Management'), findsOneWidget);
|
||||
expect(find.byKey(const Key('admin_users_search')), findsOneWidget);
|
||||
expect(find.text('Search'), findsNothing);
|
||||
expect(find.byType(PredSkeletonCard), findsWidgets);
|
||||
expect(find.byType(CircularProgressIndicator), findsNothing);
|
||||
|
||||
@ -288,6 +305,7 @@ void main() {
|
||||
await tester.pump(const Duration(milliseconds: 50));
|
||||
|
||||
expect(find.byType(SectionError), findsOneWidget);
|
||||
expect(find.byType(TlotoGradientAppBar), findsOneWidget);
|
||||
expect(find.text('User Management'), findsOneWidget);
|
||||
|
||||
admin.failWith = null;
|
||||
@ -318,6 +336,7 @@ void main() {
|
||||
await tester.pump();
|
||||
|
||||
expect(find.byKey(const Key('admin_user_detail_screen')), findsOneWidget);
|
||||
expect(find.byType(TlotoGradientAppBar), findsOneWidget);
|
||||
expect(find.byType(PredSkeletonCard), findsWidgets);
|
||||
|
||||
hold.complete(
|
||||
@ -340,12 +359,42 @@ void main() {
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 50));
|
||||
|
||||
expect(find.text('ada@prediqo.test'), findsOneWidget);
|
||||
expect(find.text('ada@prediqo.test'), findsWidgets);
|
||||
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.pump();
|
||||
});
|
||||
|
||||
testWidgets('Options shows admin tiles for admin', (tester) async {
|
||||
_tallSurface(tester);
|
||||
await _bootLocale();
|
||||
final auth = AuthBloc(_StubAuth());
|
||||
final ready = auth.stream.firstWhere((s) => s.isAdmin);
|
||||
auth.add(const AuthCheckRequested());
|
||||
await ready;
|
||||
|
||||
await tester.pumpWidget(
|
||||
BlocProvider.value(
|
||||
value: auth,
|
||||
child: MaterialApp(
|
||||
theme: AppTheme.dark,
|
||||
home: const OptionsScreen(),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
|
||||
expect(find.byKey(const Key('options_screen')), findsOneWidget);
|
||||
expect(find.byType(TlotoGradientAppBar), findsOneWidget);
|
||||
expect(find.text('Network status'), findsOneWidget);
|
||||
expect(find.text('Users'), findsOneWidget);
|
||||
expect(find.text('Settings'), findsWidgets);
|
||||
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.pump();
|
||||
addTearDown(auth.close);
|
||||
});
|
||||
|
||||
testWidgets('Settings skeletons then form for admin', (tester) async {
|
||||
_tallSurface(tester);
|
||||
await _bootLocale();
|
||||
@ -369,6 +418,7 @@ void main() {
|
||||
await tester.pump();
|
||||
|
||||
expect(find.byKey(const Key('admin_settings_screen')), findsOneWidget);
|
||||
expect(find.byType(TlotoGradientAppBar), findsOneWidget);
|
||||
expect(find.byType(PredSkeletonCard), findsWidgets);
|
||||
|
||||
hold.complete(_sampleSettings);
|
||||
@ -444,4 +494,97 @@ void main() {
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.pump();
|
||||
});
|
||||
|
||||
testWidgets('Settings hydrates from cache without skeleton', (tester) async {
|
||||
_tallSurface(tester);
|
||||
await _bootLocale();
|
||||
final api = ApiClient(config: sl());
|
||||
final hold = Completer<SystemSettings>();
|
||||
final admin = _ControllableAdmin(api)..settingsHold = hold;
|
||||
admin.settingsStore.put(_sampleSettings);
|
||||
final auth = AuthBloc(_StubAuth());
|
||||
final ready = auth.stream.firstWhere((s) => s.isAdmin);
|
||||
auth.add(const AuthCheckRequested());
|
||||
await ready;
|
||||
|
||||
await tester.pumpWidget(
|
||||
BlocProvider.value(
|
||||
value: auth,
|
||||
child: MaterialApp(
|
||||
theme: AppTheme.dark,
|
||||
home: SettingsScreen(adminRepo: admin),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
|
||||
expect(find.byType(PredSkeletonCard), findsNothing);
|
||||
expect(find.text('Password policy'), findsOneWidget);
|
||||
|
||||
hold.complete(_sampleSettings);
|
||||
await tester.pump();
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.pump();
|
||||
addTearDown(auth.close);
|
||||
});
|
||||
|
||||
testWidgets('Users hydrates from cache without skeleton', (tester) async {
|
||||
_tallSurface(tester);
|
||||
await _bootLocale();
|
||||
final api = ApiClient(config: sl());
|
||||
final hold = Completer<AdminUserListResult>();
|
||||
final admin = _ControllableAdmin(api)..listHold = hold;
|
||||
await admin.usersStore.get(
|
||||
AdminUsersListStore.keyFor(limit: 25, offset: 0),
|
||||
() async => const AdminUserListResult(users: [_sampleUser], total: 1),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
theme: AppTheme.dark,
|
||||
home: UserManagementScreen(adminRepo: admin),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
|
||||
expect(find.byType(PredSkeletonCard), findsNothing);
|
||||
expect(find.text('ada@prediqo.test'), findsOneWidget);
|
||||
|
||||
hold.complete(const AdminUserListResult(users: [_sampleUser], total: 1));
|
||||
await tester.pump();
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.pump();
|
||||
});
|
||||
|
||||
testWidgets('Network hydrates from cache without skeleton', (tester) async {
|
||||
_tallSurface(tester);
|
||||
await _bootLocale();
|
||||
final hold = Completer<HealthStatus>();
|
||||
final health = _ControllableHealth()
|
||||
..hold = hold
|
||||
..cached = const HealthStatus(
|
||||
network: 'shasta',
|
||||
withdrawalsEnabled: false,
|
||||
env: 'test',
|
||||
);
|
||||
|
||||
await tester.pumpWidget(
|
||||
RepositoryProvider<HealthRepository>.value(
|
||||
value: health,
|
||||
child: MaterialApp(
|
||||
theme: AppTheme.dark,
|
||||
home: const NetworkScreen(),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
|
||||
expect(find.byType(PredSkeletonCard), findsNothing);
|
||||
expect(find.textContaining('SHASTA'), findsOneWidget);
|
||||
|
||||
hold.complete(health.cached!);
|
||||
await tester.pump();
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.pump();
|
||||
});
|
||||
}
|
||||
|
||||
@ -59,7 +59,11 @@ class _ControllableRepo implements PredictionRepository {
|
||||
Object? historyFail;
|
||||
|
||||
@override
|
||||
Future<GameStateModel> getState({int? intervalMinutes}) async => _gs();
|
||||
Future<GameStateModel> getState({
|
||||
int? intervalMinutes,
|
||||
bool force = false,
|
||||
}) async =>
|
||||
_gs();
|
||||
|
||||
@override
|
||||
Future<CandlesPageModel> getCandlesPage({
|
||||
|
||||
@ -49,7 +49,10 @@ class _RecordingPredictionRepo implements PredictionRepository {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<GameStateModel> getState({int? intervalMinutes}) async =>
|
||||
Future<GameStateModel> getState({
|
||||
int? intervalMinutes,
|
||||
bool force = false,
|
||||
}) async =>
|
||||
throw UnimplementedError();
|
||||
|
||||
@override
|
||||
|
||||
@ -72,7 +72,10 @@ class _IntervalRepo implements PredictionRepository {
|
||||
var candlesCalls = 0;
|
||||
|
||||
@override
|
||||
Future<GameStateModel> getState({int? intervalMinutes}) async =>
|
||||
Future<GameStateModel> getState({
|
||||
int? intervalMinutes,
|
||||
bool force = false,
|
||||
}) async =>
|
||||
_gs(intervalMinutes ?? 1);
|
||||
|
||||
@override
|
||||
|
||||
@ -267,7 +267,11 @@ class FakeAuthRepository implements AuthRepository {
|
||||
|
||||
class FakePredictionRepository implements PredictionRepository {
|
||||
@override
|
||||
Future<GameStateModel> getState({int? intervalMinutes}) async => _sampleState();
|
||||
Future<GameStateModel> getState({
|
||||
int? intervalMinutes,
|
||||
bool force = false,
|
||||
}) async =>
|
||||
_sampleState();
|
||||
|
||||
@override
|
||||
Future<CandlesPageModel> getCandlesPage({
|
||||
@ -367,12 +371,19 @@ class FakePredictionRepository implements PredictionRepository {
|
||||
|
||||
class FakeHealthRepository implements HealthRepository {
|
||||
@override
|
||||
Future<HealthStatus> getHealth() async => const HealthStatus(
|
||||
Future<HealthStatus> getHealth({bool force = false}) async =>
|
||||
const HealthStatus(
|
||||
network: 'shasta',
|
||||
withdrawalsEnabled: false,
|
||||
env: 'test',
|
||||
withdrawalNetworkFeeRaw: '1000000',
|
||||
);
|
||||
|
||||
@override
|
||||
HealthStatus? peekLast() => null;
|
||||
|
||||
@override
|
||||
void invalidate() {}
|
||||
}
|
||||
|
||||
class FakeReferralRepository implements ReferralRepository {
|
||||
|
||||
@ -220,9 +220,12 @@ void main() {
|
||||
expect(wallet.txCalls, greaterThanOrEqualTo(1));
|
||||
expect(find.textContaining('Deposit'), findsWidgets);
|
||||
|
||||
await tester.drag(find.byType(ListView), const Offset(0, -4000));
|
||||
await tester.scrollUntilVisible(
|
||||
find.byKey(const Key('tx_history_load_more')),
|
||||
400,
|
||||
scrollable: find.byType(Scrollable).first,
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 50));
|
||||
|
||||
expect(find.byKey(const Key('tx_history_load_more')), findsOneWidget);
|
||||
await tester.tap(find.byKey(const Key('tx_history_load_more')));
|
||||
|
||||
@ -127,7 +127,7 @@ class _FakeHealth implements HealthRepository {
|
||||
Completer<void>? hold;
|
||||
|
||||
@override
|
||||
Future<HealthStatus> getHealth() async {
|
||||
Future<HealthStatus> getHealth({bool force = false}) async {
|
||||
if (hold != null) await hold!.future;
|
||||
return const HealthStatus(
|
||||
network: 'mainnet',
|
||||
@ -136,6 +136,12 @@ class _FakeHealth implements HealthRepository {
|
||||
withdrawalNetworkFeeRaw: '1000000',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
HealthStatus? peekLast() => null;
|
||||
|
||||
@override
|
||||
void invalidate() {}
|
||||
}
|
||||
|
||||
class _FakeReferral implements ReferralRepository {
|
||||
|
||||
@ -90,7 +90,7 @@ class _ControllableHealth implements HealthRepository {
|
||||
_ControllableHealth({this.withdrawalsEnabled = true});
|
||||
|
||||
@override
|
||||
Future<HealthStatus> getHealth() async {
|
||||
Future<HealthStatus> getHealth({bool force = false}) async {
|
||||
healthCalls++;
|
||||
return HealthStatus(
|
||||
network: 'mainnet',
|
||||
@ -99,6 +99,12 @@ class _ControllableHealth implements HealthRepository {
|
||||
withdrawalNetworkFeeRaw: '1000000',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
HealthStatus? peekLast() => null;
|
||||
|
||||
@override
|
||||
void invalidate() {}
|
||||
}
|
||||
|
||||
void main() {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user