Commit after correcting about error message

This commit is contained in:
Your Name 2026-07-27 09:29:50 +02:00
parent d03ecdf894
commit cd19f3c81b
4 changed files with 178 additions and 106 deletions

View File

@ -24,18 +24,19 @@ class AppException implements Exception {
return en; 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( static String get connectionFailedMessage => _t(
'Connection failed. Please check your internet connection and try again.', '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( static String get serviceUnavailableMessage => _t(
'The service is temporarily unavailable. Please try again later. ' 'The service is temporarily unavailable. Please try again later.',
'If the problem persists, contact an administrator.', 'Le service est temporairement indisponible. Veuillez réessayer plus tard.',
'Le service est indisponible pour le moment. Veuillez réessayer ultérieurement. '
'Si le problème persiste, veuillez contacter l’administrateur.',
); );
static final RegExp _technicalLeak = RegExp( static final RegExp _technicalLeak = RegExp(
@ -47,8 +48,8 @@ class AppException implements Exception {
static String sanitizeApiMessage(String message, {String? fallback}) { static String sanitizeApiMessage(String message, {String? fallback}) {
final trimmed = message.trim(); final trimmed = message.trim();
if (trimmed.isEmpty) return fallback ?? serviceUnavailableMessage; if (trimmed.isEmpty) return fallback ?? connectionFailedMessage;
if (looksTechnical(trimmed)) return fallback ?? serviceUnavailableMessage; if (looksTechnical(trimmed)) return fallback ?? connectionFailedMessage;
return trimmed; 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( return AppException(
serviceUnavailableMessage, serviceUnavailableMessage,
statusCode: status, statusCode: status,
@ -79,11 +81,6 @@ class AppException implements Exception {
case DioExceptionType.connectionTimeout: case DioExceptionType.connectionTimeout:
case DioExceptionType.sendTimeout: case DioExceptionType.sendTimeout:
case DioExceptionType.receiveTimeout: case DioExceptionType.receiveTimeout:
return AppException(
serviceUnavailableMessage,
statusCode: status,
code: 'SERVICE_UNAVAILABLE',
);
case DioExceptionType.connectionError: case DioExceptionType.connectionError:
return AppException( return AppException(
connectionFailedMessage, connectionFailedMessage,
@ -99,16 +96,10 @@ class AppException implements Exception {
break; break;
} }
final raw = error.message?.trim();
if (raw != null && raw.isNotEmpty) {
return AppException(
sanitizeApiMessage(raw, fallback: connectionFailedMessage),
statusCode: status,
);
}
return AppException( return AppException(
sanitizeApiMessage(fallback), connectionFailedMessage,
statusCode: status, statusCode: status,
code: 'CONNECTION_FAILED',
); );
} }
} }

View File

@ -40,40 +40,48 @@ class GameStateModel {
return GameStateModel( return GameStateModel(
config: config ?? this.config, config: config ?? this.config,
intervals: intervals ?? this.intervals, intervals: intervals ?? this.intervals,
selectedIntervalMinutes: selectedIntervalMinutes ?? this.selectedIntervalMinutes, selectedIntervalMinutes:
selectedIntervalMinutes ?? this.selectedIntervalMinutes,
interval: interval ?? this.interval, interval: interval ?? this.interval,
round: clearRound ? null : (round ?? this.round), round: clearRound ? null : (round ?? this.round),
userBet: clearUserBet ? null : (userBet ?? this.userBet), userBet: clearUserBet ? null : (userBet ?? this.userBet),
userMultiBet: clearUserMultiBet ? null : (userMultiBet ?? this.userMultiBet), userMultiBet: clearUserMultiBet
? null
: (userMultiBet ?? this.userMultiBet),
multiLevels: multiLevels ?? this.multiLevels, multiLevels: multiLevels ?? this.multiLevels,
autoSettings: autoSettings ?? this.autoSettings, autoSettings: autoSettings ?? this.autoSettings,
); );
} }
factory GameStateModel.fromJson(Map<String, dynamic> json) => GameStateModel( factory GameStateModel.fromJson(Map<String, dynamic> json) => GameStateModel(
config: PredictConfigModel.fromJson(json['config'] as Map<String, dynamic>), config: PredictConfigModel.fromJson(json['config'] as Map<String, dynamic>),
intervals: (json['intervals'] as List<dynamic>? ?? []) intervals: (json['intervals'] as List<dynamic>? ?? [])
.map((e) => IntervalModel.fromJson(e as Map<String, dynamic>)) .map((e) => IntervalModel.fromJson(e as Map<String, dynamic>))
.toList(), .toList(),
selectedIntervalMinutes: (json['selectedIntervalMinutes'] as num?)?.toInt() ?? 1, selectedIntervalMinutes:
interval: IntervalModel.fromJson(json['interval'] as Map<String, dynamic>), (json['selectedIntervalMinutes'] as num?)?.toInt() ?? 1,
round: json['round'] != null interval: IntervalModel.fromJson(json['interval'] as Map<String, dynamic>),
? RoundModel.fromJson(json['round'] as Map<String, dynamic>) round: json['round'] != null
: null, ? RoundModel.fromJson(json['round'] as Map<String, dynamic>)
userBet: json['userBet'] != null : null,
? PredictionModel.fromJson(json['userBet'] as Map<String, dynamic>) userBet: json['userBet'] != null
: null, ? PredictionModel.fromJson(json['userBet'] as Map<String, dynamic>)
userMultiBet: json['userMultiBet'] != null : null,
? MultiCandlePredictionModel.fromJson(json['userMultiBet'] as Map<String, dynamic>) userMultiBet: json['userMultiBet'] != null
: null, ? MultiCandlePredictionModel.fromJson(
multiLevels: (json['multiLevels'] as List<dynamic>? ?? []) json['userMultiBet'] as Map<String, dynamic>,
.map((e) => MultiLevelModel.fromJson(e as Map<String, dynamic>)) )
.where((l) => l.enabled) : null,
.toList(), multiLevels: (json['multiLevels'] as List<dynamic>? ?? [])
autoSettings: json['autoSettings'] != null .map((e) => MultiLevelModel.fromJson(e as Map<String, dynamic>))
? AutoSettingsModel.fromJson(json['autoSettings'] as Map<String, dynamic>) .where((l) => l.enabled)
: null, .toList(),
); autoSettings: json['autoSettings'] != null
? AutoSettingsModel.fromJson(
json['autoSettings'] as Map<String, dynamic>,
)
: null,
);
} }
class PredictConfigModel { class PredictConfigModel {
@ -99,18 +107,22 @@ class PredictConfigModel {
final PredictionTypesModel predictionTypes; final PredictionTypesModel predictionTypes;
final List<String> autoModes; final List<String> autoModes;
factory PredictConfigModel.fromJson(Map<String, dynamic> json) => PredictConfigModel( factory PredictConfigModel.fromJson(Map<String, dynamic> json) =>
PredictConfigModel(
stakeAmounts: (json['stakeAmounts'] as List<dynamic>? ?? []) stakeAmounts: (json['stakeAmounts'] as List<dynamic>? ?? [])
.map((e) => (e as num).toDouble()) .map((e) => (e as num).toDouble())
.toList(), .toList(),
minStakeAmount: (json['minStakeAmount'] as num?)?.toDouble() ?? 1, minStakeAmount: (json['minStakeAmount'] as num?)?.toDouble() ?? 1,
maxStakeAmount: (json['maxStakeAmount'] as num?)?.toDouble() ?? 1000, maxStakeAmount: (json['maxStakeAmount'] as num?)?.toDouble() ?? 1000,
payoutMultiplier: (json['payoutMultiplier'] as num?)?.toDouble() ?? 1.8, 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, isActive: json['isActive'] != false,
walletTypeCode: (json['walletTypeCode'] ?? 'USDT_TRC20').toString(), walletTypeCode: (json['walletTypeCode'] ?? 'USDT_TRC20').toString(),
predictionTypes: json['predictionTypes'] != null predictionTypes: json['predictionTypes'] != null
? PredictionTypesModel.fromJson(json['predictionTypes'] as Map<String, dynamic>) ? PredictionTypesModel.fromJson(
json['predictionTypes'] as Map<String, dynamic>,
)
: const PredictionTypesModel(), : const PredictionTypesModel(),
autoModes: (json['autoModes'] as List<dynamic>? ?? ['each_round']) autoModes: (json['autoModes'] as List<dynamic>? ?? ['each_round'])
.map((e) => e.toString()) .map((e) => e.toString())
@ -129,7 +141,8 @@ class PredictionTypesModel {
final bool auto; final bool auto;
final bool multiCandle; final bool multiCandle;
factory PredictionTypesModel.fromJson(Map<String, dynamic> json) => PredictionTypesModel( factory PredictionTypesModel.fromJson(Map<String, dynamic> json) =>
PredictionTypesModel(
single: json['single'] != false, single: json['single'] != false,
auto: json['auto'] != false, auto: json['auto'] != false,
multiCandle: json['multiCandle'] != false, multiCandle: json['multiCandle'] != false,
@ -156,14 +169,14 @@ class IntervalModel {
final int chartCandleLimit; final int chartCandleLimit;
factory IntervalModel.fromJson(Map<String, dynamic> json) => IntervalModel( factory IntervalModel.fromJson(Map<String, dynamic> json) => IntervalModel(
id: (json['id'] as num).toInt(), id: (json['id'] as num).toInt(),
intervalMinutes: (json['intervalMinutes'] as num).toInt(), intervalMinutes: (json['intervalMinutes'] as num).toInt(),
label: (json['label'] ?? '${json['intervalMinutes']}m').toString(), label: (json['label'] ?? '${json['intervalMinutes']}m').toString(),
isDefault: json['isDefault'] == true, isDefault: json['isDefault'] == true,
isActive: json['isActive'] != false, isActive: json['isActive'] != false,
payoutMultiplier: (json['payoutMultiplier'] as num?)?.toDouble() ?? 1.8, payoutMultiplier: (json['payoutMultiplier'] as num?)?.toDouble() ?? 1.8,
chartCandleLimit: (json['chartCandleLimit'] as num?)?.toInt() ?? 80, chartCandleLimit: (json['chartCandleLimit'] as num?)?.toInt() ?? 80,
); );
} }
class RoundModel { class RoundModel {
@ -190,6 +203,7 @@ class RoundModel {
final double? shortPoolPercent; final double? shortPoolPercent;
final double? longPoolPercent; final double? longPoolPercent;
final int? serverNowMs; final int? serverNowMs;
/// Absolute ms when the open (betting) window ends — preferred for smooth countdown. /// Absolute ms when the open (betting) window ends — preferred for smooth countdown.
final int? bettingEndMs; final int? bettingEndMs;
final int? bettingStartMs; final int? bettingStartMs;
@ -197,18 +211,19 @@ class RoundModel {
bool get isBetting => status == 'betting'; bool get isBetting => status == 'betting';
factory RoundModel.fromJson(Map<String, dynamic> json) => RoundModel( factory RoundModel.fromJson(Map<String, dynamic> json) => RoundModel(
id: json['id'] as String, id: json['id'] as String,
status: (json['status'] ?? 'waiting').toString(), status: (json['status'] ?? 'waiting').toString(),
secondsToBettingEnd: (json['secondsToBettingEnd'] as num?)?.toInt() ?? 0, secondsToBettingEnd: (json['secondsToBettingEnd'] as num?)?.toInt() ?? 0,
secondsToBettingStart: (json['secondsToBettingStart'] as num?)?.toInt() ?? 0, secondsToBettingStart:
secondsToClose: (json['secondsToClose'] as num?)?.toInt() ?? 0, (json['secondsToBettingStart'] as num?)?.toInt() ?? 0,
outcome: json['outcome'] as String?, secondsToClose: (json['secondsToClose'] as num?)?.toInt() ?? 0,
shortPoolPercent: (json['shortPoolPercent'] as num?)?.toDouble(), outcome: json['outcome'] as String?,
longPoolPercent: (json['longPoolPercent'] as num?)?.toDouble(), shortPoolPercent: (json['shortPoolPercent'] as num?)?.toDouble(),
serverNowMs: (json['serverNowMs'] as num?)?.toInt(), longPoolPercent: (json['longPoolPercent'] as num?)?.toDouble(),
bettingEndMs: (json['bettingEndMs'] as num?)?.toInt(), serverNowMs: (json['serverNowMs'] as num?)?.toInt(),
bettingStartMs: (json['bettingStartMs'] as num?)?.toInt(), bettingEndMs: (json['bettingEndMs'] as num?)?.toInt(),
); bettingStartMs: (json['bettingStartMs'] as num?)?.toInt(),
);
} }
class PredictionModel { class PredictionModel {
@ -256,7 +271,8 @@ class PredictionModel {
return rid == round.id; return rid == round.id;
} }
factory PredictionModel.fromJson(Map<String, dynamic> json) => PredictionModel( factory PredictionModel.fromJson(Map<String, dynamic> json) =>
PredictionModel(
id: json['id'] as String, id: json['id'] as String,
direction: (json['direction'] ?? 'long').toString(), direction: (json['direction'] ?? 'long').toString(),
stakeDisplay: (json['stakeDisplay'] as num?)?.toDouble() ?? 0, stakeDisplay: (json['stakeDisplay'] as num?)?.toDouble() ?? 0,
@ -328,9 +344,12 @@ class MultiLevelModel {
final bool enabled; final bool enabled;
final double payoutMultiplier; final double payoutMultiplier;
factory MultiLevelModel.fromJson(Map<String, dynamic> json) => MultiLevelModel( factory MultiLevelModel.fromJson(Map<String, dynamic> json) =>
MultiLevelModel(
level: (json['level'] as num).toInt(), 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, enabled: json['enabled'] != false,
payoutMultiplier: (json['payoutMultiplier'] as num?)?.toDouble() ?? 1.8, payoutMultiplier: (json['payoutMultiplier'] as num?)?.toDouble() ?? 1.8,
); );
@ -361,7 +380,8 @@ class AutoSettingsModel {
final bool autoBetPlaced; final bool autoBetPlaced;
final String? autoBetError; final String? autoBetError;
factory AutoSettingsModel.fromJson(Map<String, dynamic> json) => AutoSettingsModel( factory AutoSettingsModel.fromJson(Map<String, dynamic> json) =>
AutoSettingsModel(
enabled: json['enabled'] == true, enabled: json['enabled'] == true,
direction: json['direction'] as String?, direction: json['direction'] as String?,
stakeDisplay: (json['stakeDisplay'] as num?)?.toDouble() ?? 0, stakeDisplay: (json['stakeDisplay'] as num?)?.toDouble() ?? 0,
@ -384,19 +404,18 @@ class AutoSettingsModel {
int? intervalSeconds, int? intervalSeconds,
bool attemptImmediateBet = true, bool attemptImmediateBet = true,
bool validateWalletBalance = true, bool validateWalletBalance = true,
}) => }) => {
{ 'enabled': enabled,
'enabled': enabled, 'direction': direction,
'direction': direction, 'stakeDisplay': stakeAmount,
'stakeDisplay': stakeAmount, 'stakeAmount': stakeAmount,
'stakeAmount': stakeAmount, 'mode': mode,
'mode': mode, 'periodMinutes': periodMinutes,
'periodMinutes': periodMinutes, 'stakeAccountKind': stakeAccountKind,
'stakeAccountKind': stakeAccountKind, if (intervalSeconds != null) 'intervalSeconds': intervalSeconds,
if (intervalSeconds != null) 'intervalSeconds': intervalSeconds, 'attemptImmediateBet': attemptImmediateBet,
'attemptImmediateBet': attemptImmediateBet, 'validateWalletBalance': validateWalletBalance,
'validateWalletBalance': validateWalletBalance, };
};
} }
class OhlcCandleModel { class OhlcCandleModel {
@ -415,6 +434,7 @@ class OhlcCandleModel {
final double high; final double high;
final double low; final double low;
final double close; final double close;
/// Absolute open timestamp in ms — required for paginated `beforeOpenMs` queries. /// Absolute open timestamp in ms — required for paginated `beforeOpenMs` queries.
final int? candleOpenMs; final int? candleOpenMs;
@ -422,7 +442,8 @@ class OhlcCandleModel {
int get openMs => candleOpenMs ?? time * 1000; int get openMs => candleOpenMs ?? time * 1000;
factory OhlcCandleModel.fromJson(Map<String, dynamic> json) => OhlcCandleModel( factory OhlcCandleModel.fromJson(Map<String, dynamic> json) =>
OhlcCandleModel(
time: (json['time'] as num?)?.toInt() ?? 0, time: (json['time'] as num?)?.toInt() ?? 0,
open: (json['open'] as num?)?.toDouble() ?? 0, open: (json['open'] as num?)?.toDouble() ?? 0,
high: (json['high'] as num?)?.toDouble() ?? 0, high: (json['high'] as num?)?.toDouble() ?? 0,
@ -468,7 +489,8 @@ class PredictionsPageModel {
final int page; final int page;
final int totalPages; final int totalPages;
factory PredictionsPageModel.fromJson(Map<String, dynamic> json) => PredictionsPageModel( factory PredictionsPageModel.fromJson(Map<String, dynamic> json) =>
PredictionsPageModel(
items: (json['items'] as List<dynamic>? ?? []) items: (json['items'] as List<dynamic>? ?? [])
.map((e) => PredictionModel.fromJson(e as Map<String, dynamic>)) .map((e) => PredictionModel.fromJson(e as Map<String, dynamic>))
.toList(), .toList(),

View File

@ -89,7 +89,7 @@ class _HomeScreenState extends State<HomeScreen> {
_totpEnabled = profile?.totpEnabled ?? false; _totpEnabled = profile?.totpEnabled ?? false;
_loading = false; _loading = false;
if (ads == null && games == null) { if (ads == null && games == null) {
_error = AppException.serviceUnavailableMessage; _error = AppException.connectionFailedMessage;
} }
}); });
} catch (e) { } catch (e) {

View File

@ -16,36 +16,62 @@ class NotificationsScreen extends StatefulWidget {
} }
class _NotificationsScreenState extends State<NotificationsScreen> { class _NotificationsScreenState extends State<NotificationsScreen> {
static const _pageSize = 20;
final _repo = sl<NotificationRepository>(); final _repo = sl<NotificationRepository>();
bool _loading = true; bool _loading = true;
bool _loadingMore = false;
String? _error; String? _error;
List<SecurityNotificationModel> _items = []; List<SecurityNotificationModel> _items = [];
int _unreadCount = 0; int _unreadCount = 0;
int _total = 0;
bool get _hasMore => _items.length < _total;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_load(); _load(reset: true);
} }
Future<void> _load() async { Future<void> _load({required bool reset}) async {
setState(() { if (reset) {
_loading = true; setState(() {
_error = null; _loading = true;
}); _error = null;
});
} else {
if (_loadingMore || !_hasMore) return;
setState(() => _loadingMore = true);
}
try { 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; if (!mounted) return;
setState(() { 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; _unreadCount = page.unreadCount;
_loading = false; _loading = false;
_loadingMore = false;
}); });
} catch (e) { } catch (e) {
if (!mounted) return; if (!mounted) return;
setState(() { setState(() {
_error = e.toString().replaceFirst(RegExp(r'^Exception:\s*'), ''); if (reset) {
_error = e.toString().replaceFirst(RegExp(r'^Exception:\s*'), '');
}
_loading = false; _loading = false;
_loadingMore = false;
}); });
} }
} }
@ -53,7 +79,7 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
Future<void> _markAll() async { Future<void> _markAll() async {
try { try {
await _repo.markAllRead(); await _repo.markAllRead();
await _load(); await _load(reset: true);
} catch (_) {} } catch (_) {}
} }
@ -61,6 +87,23 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
if (item.isUnread) { if (item.isUnread) {
try { try {
await _repo.markRead(item.id); 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 (_) {} } catch (_) {}
} }
if (!mounted) return; if (!mounted) return;
@ -112,7 +155,6 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
); );
}, },
); );
await _load();
} }
String _formatDate(String iso) { String _formatDate(String iso) {
@ -138,9 +180,9 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
body: _loading body: _loading
? PredLoadingView(message: s.loading) ? PredLoadingView(message: s.loading)
: _error != null : _error != null
? PredErrorView(message: _error!, onRetry: _load) ? PredErrorView(message: _error!, onRetry: () => _load(reset: true))
: RefreshIndicator( : RefreshIndicator(
onRefresh: _load, onRefresh: () => _load(reset: true),
child: _items.isEmpty child: _items.isEmpty
? ListView( ? ListView(
physics: const AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
@ -164,9 +206,26 @@ class _NotificationsScreenState extends State<NotificationsScreen> {
: ListView.separated( : ListView.separated(
physics: const AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.fromLTRB(20, 12, 20, 28), padding: const EdgeInsets.fromLTRB(20, 12, 20, 28),
itemCount: _items.length, itemCount: _items.length + (_hasMore ? 1 : 0),
separatorBuilder: (_, __) => const SizedBox(height: 10), separatorBuilder: (_, __) => const SizedBox(height: 10),
itemBuilder: (context, index) { 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]; final item = _items[index];
return PredCard( return PredCard(
onTap: () => _openItem(item), onTap: () => _openItem(item),