From cd19f3c81b0fa87b7b9a8c559ea932b60a110e95 Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 27 Jul 2026 09:29:50 +0200 Subject: [PATCH] Commit after correcting about error message --- .../lib/core/errors/app_exception.dart | 37 ++-- .../lib/data/models/prediction_models.dart | 158 ++++++++++-------- .../home/presentation/home_screen.dart | 2 +- .../presentation/notifications_screen.dart | 87 ++++++++-- 4 files changed, 178 insertions(+), 106 deletions(-) diff --git a/prediqo_mobile/lib/core/errors/app_exception.dart b/prediqo_mobile/lib/core/errors/app_exception.dart index 1ba56a61..3fcf6e2c 100644 --- a/prediqo_mobile/lib/core/errors/app_exception.dart +++ b/prediqo_mobile/lib/core/errors/app_exception.dart @@ -24,18 +24,19 @@ class AppException implements Exception { return en; } - /// Connection / device network failure — ask the user to check connectivity. + /// Generic unreachable message — covers network issues, timeouts, DNS failures, + /// and anything where we never got a meaningful server response. Blaming the + /// connection is friendlier than "service unavailable" when the real cause is + /// usually the user's network, not the backend being down. static String get connectionFailedMessage => _t( 'Connection failed. Please check your internet connection and try again.', - 'Échec de connexion. Veuillez vérifier votre connexion internet et réessayer.', + 'La connexion a échoué. Veuillez vérifier votre connexion internet et réessayer.', ); - /// API unreachable, timeouts, or gateway errors — no infra details exposed. + /// Only for confirmed server-side errors (5xx with a response body received). static String get serviceUnavailableMessage => _t( - 'The service is temporarily unavailable. Please try again later. ' - 'If the problem persists, contact an administrator.', - 'Le service est indisponible pour le moment. Veuillez réessayer ultérieurement. ' - 'Si le problème persiste, veuillez contacter l’administrateur.', + 'The service is temporarily unavailable. Please try again later.', + 'Le service est temporairement indisponible. Veuillez réessayer plus tard.', ); static final RegExp _technicalLeak = RegExp( @@ -47,8 +48,8 @@ class AppException implements Exception { static String sanitizeApiMessage(String message, {String? fallback}) { final trimmed = message.trim(); - if (trimmed.isEmpty) return fallback ?? serviceUnavailableMessage; - if (looksTechnical(trimmed)) return fallback ?? serviceUnavailableMessage; + if (trimmed.isEmpty) return fallback ?? connectionFailedMessage; + if (looksTechnical(trimmed)) return fallback ?? connectionFailedMessage; return trimmed; } @@ -67,7 +68,8 @@ class AppException implements Exception { } } - if (status == 502 || status == 503 || status == 504) { + // 5xx with a response actually received — confirmed server error. + if (status != null && status >= 500) { return AppException( serviceUnavailableMessage, statusCode: status, @@ -79,11 +81,6 @@ class AppException implements Exception { case DioExceptionType.connectionTimeout: case DioExceptionType.sendTimeout: case DioExceptionType.receiveTimeout: - return AppException( - serviceUnavailableMessage, - statusCode: status, - code: 'SERVICE_UNAVAILABLE', - ); case DioExceptionType.connectionError: return AppException( connectionFailedMessage, @@ -99,16 +96,10 @@ class AppException implements Exception { break; } - final raw = error.message?.trim(); - if (raw != null && raw.isNotEmpty) { - return AppException( - sanitizeApiMessage(raw, fallback: connectionFailedMessage), - statusCode: status, - ); - } return AppException( - sanitizeApiMessage(fallback), + connectionFailedMessage, statusCode: status, + code: 'CONNECTION_FAILED', ); } } diff --git a/prediqo_mobile/lib/data/models/prediction_models.dart b/prediqo_mobile/lib/data/models/prediction_models.dart index cd38d3e6..c6d3da8d 100644 --- a/prediqo_mobile/lib/data/models/prediction_models.dart +++ b/prediqo_mobile/lib/data/models/prediction_models.dart @@ -40,40 +40,48 @@ class GameStateModel { return GameStateModel( config: config ?? this.config, intervals: intervals ?? this.intervals, - selectedIntervalMinutes: selectedIntervalMinutes ?? this.selectedIntervalMinutes, + selectedIntervalMinutes: + selectedIntervalMinutes ?? this.selectedIntervalMinutes, interval: interval ?? this.interval, round: clearRound ? null : (round ?? this.round), userBet: clearUserBet ? null : (userBet ?? this.userBet), - userMultiBet: clearUserMultiBet ? null : (userMultiBet ?? this.userMultiBet), + userMultiBet: clearUserMultiBet + ? null + : (userMultiBet ?? this.userMultiBet), multiLevels: multiLevels ?? this.multiLevels, autoSettings: autoSettings ?? this.autoSettings, ); } factory GameStateModel.fromJson(Map json) => GameStateModel( - config: PredictConfigModel.fromJson(json['config'] as Map), - intervals: (json['intervals'] as List? ?? []) - .map((e) => IntervalModel.fromJson(e as Map)) - .toList(), - selectedIntervalMinutes: (json['selectedIntervalMinutes'] as num?)?.toInt() ?? 1, - interval: IntervalModel.fromJson(json['interval'] as Map), - round: json['round'] != null - ? RoundModel.fromJson(json['round'] as Map) - : null, - userBet: json['userBet'] != null - ? PredictionModel.fromJson(json['userBet'] as Map) - : null, - userMultiBet: json['userMultiBet'] != null - ? MultiCandlePredictionModel.fromJson(json['userMultiBet'] as Map) - : null, - multiLevels: (json['multiLevels'] as List? ?? []) - .map((e) => MultiLevelModel.fromJson(e as Map)) - .where((l) => l.enabled) - .toList(), - autoSettings: json['autoSettings'] != null - ? AutoSettingsModel.fromJson(json['autoSettings'] as Map) - : null, - ); + config: PredictConfigModel.fromJson(json['config'] as Map), + intervals: (json['intervals'] as List? ?? []) + .map((e) => IntervalModel.fromJson(e as Map)) + .toList(), + selectedIntervalMinutes: + (json['selectedIntervalMinutes'] as num?)?.toInt() ?? 1, + interval: IntervalModel.fromJson(json['interval'] as Map), + round: json['round'] != null + ? RoundModel.fromJson(json['round'] as Map) + : null, + userBet: json['userBet'] != null + ? PredictionModel.fromJson(json['userBet'] as Map) + : null, + userMultiBet: json['userMultiBet'] != null + ? MultiCandlePredictionModel.fromJson( + json['userMultiBet'] as Map, + ) + : null, + multiLevels: (json['multiLevels'] as List? ?? []) + .map((e) => MultiLevelModel.fromJson(e as Map)) + .where((l) => l.enabled) + .toList(), + autoSettings: json['autoSettings'] != null + ? AutoSettingsModel.fromJson( + json['autoSettings'] as Map, + ) + : null, + ); } class PredictConfigModel { @@ -99,18 +107,22 @@ class PredictConfigModel { final PredictionTypesModel predictionTypes; final List autoModes; - factory PredictConfigModel.fromJson(Map json) => PredictConfigModel( + factory PredictConfigModel.fromJson(Map json) => + PredictConfigModel( stakeAmounts: (json['stakeAmounts'] as List? ?? []) .map((e) => (e as num).toDouble()) .toList(), minStakeAmount: (json['minStakeAmount'] as num?)?.toDouble() ?? 1, maxStakeAmount: (json['maxStakeAmount'] as num?)?.toDouble() ?? 1000, payoutMultiplier: (json['payoutMultiplier'] as num?)?.toDouble() ?? 1.8, - predictionWindowSeconds: (json['predictionWindowSeconds'] as num?)?.toInt() ?? 30, + predictionWindowSeconds: + (json['predictionWindowSeconds'] as num?)?.toInt() ?? 30, isActive: json['isActive'] != false, walletTypeCode: (json['walletTypeCode'] ?? 'USDT_TRC20').toString(), predictionTypes: json['predictionTypes'] != null - ? PredictionTypesModel.fromJson(json['predictionTypes'] as Map) + ? PredictionTypesModel.fromJson( + json['predictionTypes'] as Map, + ) : const PredictionTypesModel(), autoModes: (json['autoModes'] as List? ?? ['each_round']) .map((e) => e.toString()) @@ -129,7 +141,8 @@ class PredictionTypesModel { final bool auto; final bool multiCandle; - factory PredictionTypesModel.fromJson(Map json) => PredictionTypesModel( + factory PredictionTypesModel.fromJson(Map json) => + PredictionTypesModel( single: json['single'] != false, auto: json['auto'] != false, multiCandle: json['multiCandle'] != false, @@ -156,14 +169,14 @@ class IntervalModel { final int chartCandleLimit; factory IntervalModel.fromJson(Map json) => IntervalModel( - id: (json['id'] as num).toInt(), - intervalMinutes: (json['intervalMinutes'] as num).toInt(), - label: (json['label'] ?? '${json['intervalMinutes']}m').toString(), - isDefault: json['isDefault'] == true, - isActive: json['isActive'] != false, - payoutMultiplier: (json['payoutMultiplier'] as num?)?.toDouble() ?? 1.8, - chartCandleLimit: (json['chartCandleLimit'] as num?)?.toInt() ?? 80, - ); + id: (json['id'] as num).toInt(), + intervalMinutes: (json['intervalMinutes'] as num).toInt(), + label: (json['label'] ?? '${json['intervalMinutes']}m').toString(), + isDefault: json['isDefault'] == true, + isActive: json['isActive'] != false, + payoutMultiplier: (json['payoutMultiplier'] as num?)?.toDouble() ?? 1.8, + chartCandleLimit: (json['chartCandleLimit'] as num?)?.toInt() ?? 80, + ); } class RoundModel { @@ -190,6 +203,7 @@ class RoundModel { final double? shortPoolPercent; final double? longPoolPercent; final int? serverNowMs; + /// Absolute ms when the open (betting) window ends — preferred for smooth countdown. final int? bettingEndMs; final int? bettingStartMs; @@ -197,18 +211,19 @@ class RoundModel { bool get isBetting => status == 'betting'; factory RoundModel.fromJson(Map json) => RoundModel( - id: json['id'] as String, - status: (json['status'] ?? 'waiting').toString(), - secondsToBettingEnd: (json['secondsToBettingEnd'] as num?)?.toInt() ?? 0, - secondsToBettingStart: (json['secondsToBettingStart'] as num?)?.toInt() ?? 0, - secondsToClose: (json['secondsToClose'] as num?)?.toInt() ?? 0, - outcome: json['outcome'] as String?, - shortPoolPercent: (json['shortPoolPercent'] as num?)?.toDouble(), - longPoolPercent: (json['longPoolPercent'] as num?)?.toDouble(), - serverNowMs: (json['serverNowMs'] as num?)?.toInt(), - bettingEndMs: (json['bettingEndMs'] as num?)?.toInt(), - bettingStartMs: (json['bettingStartMs'] as num?)?.toInt(), - ); + id: json['id'] as String, + status: (json['status'] ?? 'waiting').toString(), + secondsToBettingEnd: (json['secondsToBettingEnd'] as num?)?.toInt() ?? 0, + secondsToBettingStart: + (json['secondsToBettingStart'] as num?)?.toInt() ?? 0, + secondsToClose: (json['secondsToClose'] as num?)?.toInt() ?? 0, + outcome: json['outcome'] as String?, + shortPoolPercent: (json['shortPoolPercent'] as num?)?.toDouble(), + longPoolPercent: (json['longPoolPercent'] as num?)?.toDouble(), + serverNowMs: (json['serverNowMs'] as num?)?.toInt(), + bettingEndMs: (json['bettingEndMs'] as num?)?.toInt(), + bettingStartMs: (json['bettingStartMs'] as num?)?.toInt(), + ); } class PredictionModel { @@ -256,7 +271,8 @@ class PredictionModel { return rid == round.id; } - factory PredictionModel.fromJson(Map json) => PredictionModel( + factory PredictionModel.fromJson(Map json) => + PredictionModel( id: json['id'] as String, direction: (json['direction'] ?? 'long').toString(), stakeDisplay: (json['stakeDisplay'] as num?)?.toDouble() ?? 0, @@ -328,9 +344,12 @@ class MultiLevelModel { final bool enabled; final double payoutMultiplier; - factory MultiLevelModel.fromJson(Map json) => MultiLevelModel( + factory MultiLevelModel.fromJson(Map json) => + MultiLevelModel( level: (json['level'] as num).toInt(), - candleCount: (json['candleCount'] as num?)?.toInt() ?? (json['level'] as num).toInt(), + candleCount: + (json['candleCount'] as num?)?.toInt() ?? + (json['level'] as num).toInt(), enabled: json['enabled'] != false, payoutMultiplier: (json['payoutMultiplier'] as num?)?.toDouble() ?? 1.8, ); @@ -361,7 +380,8 @@ class AutoSettingsModel { final bool autoBetPlaced; final String? autoBetError; - factory AutoSettingsModel.fromJson(Map json) => AutoSettingsModel( + factory AutoSettingsModel.fromJson(Map json) => + AutoSettingsModel( enabled: json['enabled'] == true, direction: json['direction'] as String?, stakeDisplay: (json['stakeDisplay'] as num?)?.toDouble() ?? 0, @@ -384,19 +404,18 @@ class AutoSettingsModel { int? intervalSeconds, bool attemptImmediateBet = true, bool validateWalletBalance = true, - }) => - { - 'enabled': enabled, - 'direction': direction, - 'stakeDisplay': stakeAmount, - 'stakeAmount': stakeAmount, - 'mode': mode, - 'periodMinutes': periodMinutes, - 'stakeAccountKind': stakeAccountKind, - if (intervalSeconds != null) 'intervalSeconds': intervalSeconds, - 'attemptImmediateBet': attemptImmediateBet, - 'validateWalletBalance': validateWalletBalance, - }; + }) => { + 'enabled': enabled, + 'direction': direction, + 'stakeDisplay': stakeAmount, + 'stakeAmount': stakeAmount, + 'mode': mode, + 'periodMinutes': periodMinutes, + 'stakeAccountKind': stakeAccountKind, + if (intervalSeconds != null) 'intervalSeconds': intervalSeconds, + 'attemptImmediateBet': attemptImmediateBet, + 'validateWalletBalance': validateWalletBalance, + }; } class OhlcCandleModel { @@ -415,6 +434,7 @@ class OhlcCandleModel { final double high; final double low; final double close; + /// Absolute open timestamp in ms — required for paginated `beforeOpenMs` queries. final int? candleOpenMs; @@ -422,7 +442,8 @@ class OhlcCandleModel { int get openMs => candleOpenMs ?? time * 1000; - factory OhlcCandleModel.fromJson(Map json) => OhlcCandleModel( + factory OhlcCandleModel.fromJson(Map json) => + OhlcCandleModel( time: (json['time'] as num?)?.toInt() ?? 0, open: (json['open'] as num?)?.toDouble() ?? 0, high: (json['high'] as num?)?.toDouble() ?? 0, @@ -468,7 +489,8 @@ class PredictionsPageModel { final int page; final int totalPages; - factory PredictionsPageModel.fromJson(Map json) => PredictionsPageModel( + factory PredictionsPageModel.fromJson(Map json) => + PredictionsPageModel( items: (json['items'] as List? ?? []) .map((e) => PredictionModel.fromJson(e as Map)) .toList(), diff --git a/prediqo_mobile/lib/features/home/presentation/home_screen.dart b/prediqo_mobile/lib/features/home/presentation/home_screen.dart index 2677f7d0..80ba612e 100644 --- a/prediqo_mobile/lib/features/home/presentation/home_screen.dart +++ b/prediqo_mobile/lib/features/home/presentation/home_screen.dart @@ -89,7 +89,7 @@ class _HomeScreenState extends State { _totpEnabled = profile?.totpEnabled ?? false; _loading = false; if (ads == null && games == null) { - _error = AppException.serviceUnavailableMessage; + _error = AppException.connectionFailedMessage; } }); } catch (e) { diff --git a/prediqo_mobile/lib/features/notifications/presentation/notifications_screen.dart b/prediqo_mobile/lib/features/notifications/presentation/notifications_screen.dart index 92b7799c..a6b2e1bc 100644 --- a/prediqo_mobile/lib/features/notifications/presentation/notifications_screen.dart +++ b/prediqo_mobile/lib/features/notifications/presentation/notifications_screen.dart @@ -16,36 +16,62 @@ class NotificationsScreen extends StatefulWidget { } class _NotificationsScreenState extends State { + static const _pageSize = 20; + final _repo = sl(); bool _loading = true; + bool _loadingMore = false; String? _error; List _items = []; int _unreadCount = 0; + int _total = 0; + + bool get _hasMore => _items.length < _total; @override void initState() { super.initState(); - _load(); + _load(reset: true); } - Future _load() async { - setState(() { - _loading = true; - _error = null; - }); + Future _load({required bool reset}) async { + if (reset) { + setState(() { + _loading = true; + _error = null; + }); + } else { + if (_loadingMore || !_hasMore) return; + setState(() => _loadingMore = true); + } + try { - final page = await _repo.list(limit: 50); + final offset = reset ? 0 : _items.length; + final page = await _repo.list(limit: _pageSize, offset: offset); if (!mounted) return; setState(() { - _items = page.items; + if (reset) { + _items = page.items; + } else { + final existingIds = _items.map((e) => e.id).toSet(); + _items = [ + ..._items, + ...page.items.where((e) => !existingIds.contains(e.id)), + ]; + } + _total = page.total; _unreadCount = page.unreadCount; _loading = false; + _loadingMore = false; }); } catch (e) { if (!mounted) return; setState(() { - _error = e.toString().replaceFirst(RegExp(r'^Exception:\s*'), ''); + if (reset) { + _error = e.toString().replaceFirst(RegExp(r'^Exception:\s*'), ''); + } _loading = false; + _loadingMore = false; }); } } @@ -53,7 +79,7 @@ class _NotificationsScreenState extends State { Future _markAll() async { try { await _repo.markAllRead(); - await _load(); + await _load(reset: true); } catch (_) {} } @@ -61,6 +87,23 @@ class _NotificationsScreenState extends State { if (item.isUnread) { try { await _repo.markRead(item.id); + if (mounted) { + setState(() { + final idx = _items.indexWhere((e) => e.id == item.id); + if (idx >= 0) { + final current = _items[idx]; + _items[idx] = SecurityNotificationModel( + id: current.id, + eventType: current.eventType, + title: current.title, + body: current.body, + readAt: DateTime.now().toUtc().toIso8601String(), + createdAt: current.createdAt, + ); + } + if (_unreadCount > 0) _unreadCount -= 1; + }); + } } catch (_) {} } if (!mounted) return; @@ -112,7 +155,6 @@ class _NotificationsScreenState extends State { ); }, ); - await _load(); } String _formatDate(String iso) { @@ -138,9 +180,9 @@ class _NotificationsScreenState extends State { body: _loading ? PredLoadingView(message: s.loading) : _error != null - ? PredErrorView(message: _error!, onRetry: _load) + ? PredErrorView(message: _error!, onRetry: () => _load(reset: true)) : RefreshIndicator( - onRefresh: _load, + onRefresh: () => _load(reset: true), child: _items.isEmpty ? ListView( physics: const AlwaysScrollableScrollPhysics(), @@ -164,9 +206,26 @@ class _NotificationsScreenState extends State { : ListView.separated( physics: const AlwaysScrollableScrollPhysics(), padding: const EdgeInsets.fromLTRB(20, 12, 20, 28), - itemCount: _items.length, + itemCount: _items.length + (_hasMore ? 1 : 0), separatorBuilder: (_, __) => const SizedBox(height: 10), itemBuilder: (context, index) { + if (index >= _items.length) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Center( + child: _loadingMore + ? const SizedBox( + width: 28, + height: 28, + child: CircularProgressIndicator(strokeWidth: 2.5), + ) + : OutlinedButton( + onPressed: () => _load(reset: false), + child: Text(s.loadMore), + ), + ), + ); + } final item = _items[index]; return PredCard( onTap: () => _openItem(item),