diff --git a/prediqo_mobile/ios/Runner/Info.plist b/prediqo_mobile/ios/Runner/Info.plist index 4393e9d3..88c581ba 100644 --- a/prediqo_mobile/ios/Runner/Info.plist +++ b/prediqo_mobile/ios/Runner/Info.plist @@ -45,6 +45,10 @@ UIApplicationSupportsIndirectInputEvents + NSPhotoLibraryUsageDescription + Tloto uses your photo library to send images to support. + NSCameraUsageDescription + Tloto uses the camera to send photos to support. UIStatusBarHidden diff --git a/prediqo_mobile/lib/app.dart b/prediqo_mobile/lib/app.dart index 59d2138c..0ae18665 100644 --- a/prediqo_mobile/lib/app.dart +++ b/prediqo_mobile/lib/app.dart @@ -13,8 +13,11 @@ import 'domain/repositories/health_repository.dart'; import 'domain/repositories/prediction_repository.dart'; import 'domain/repositories/referral_repository.dart'; import 'domain/repositories/repositories.dart'; +import 'data/repositories/support_repository.dart'; import 'features/auth/bloc/auth_bloc.dart'; import 'features/prediction/bloc/prediction_bloc.dart'; +import 'features/support/bloc/support_bloc.dart'; +import 'features/support/presentation/support_widget.dart'; import 'features/wallet/bloc/wallet_bloc.dart'; import 'l10n/app_locale.dart'; import 'l10n/locale_controller.dart'; @@ -28,6 +31,7 @@ class PrediqoApp extends StatefulWidget { class _PrediqoAppState extends State { late final AuthBloc _authBloc; + late final SupportBloc _supportBloc; late final GoRouter _router; late final LocaleController _localeController; @@ -36,6 +40,7 @@ class _PrediqoAppState extends State { super.initState(); _localeController = sl(); _authBloc = sl(); + _supportBloc = sl(); sl().onSessionExpired = () { if (!_authBloc.isClosed) { _authBloc.add(const AuthSessionExpired()); @@ -47,6 +52,7 @@ class _PrediqoAppState extends State { @override void dispose() { sl().onSessionExpired = null; + _supportBloc.close(); _authBloc.close(); super.dispose(); } @@ -63,10 +69,12 @@ class _PrediqoAppState extends State { RepositoryProvider.value(value: sl()), RepositoryProvider.value(value: sl()), RepositoryProvider.value(value: sl()), + RepositoryProvider.value(value: sl()), ], child: MultiBlocProvider( providers: [ BlocProvider.value(value: _authBloc), + BlocProvider.value(value: _supportBloc), BlocProvider(create: (_) => sl()), BlocProvider(create: (_) => sl()), ], @@ -87,6 +95,9 @@ class _PrediqoAppState extends State { GlobalCupertinoLocalizations.delegate, ], routerConfig: _router, + builder: (context, child) { + return _SupportRouteLayer(router: _router, child: child); + }, ); }, ), @@ -94,3 +105,47 @@ class _PrediqoAppState extends State { ); } } + +/// Rebuilds the support overlay only when the route path actually changes. +class _SupportRouteLayer extends StatefulWidget { + const _SupportRouteLayer({required this.router, this.child}); + + final GoRouter router; + final Widget? child; + + @override + State<_SupportRouteLayer> createState() => _SupportRouteLayerState(); +} + +class _SupportRouteLayerState extends State<_SupportRouteLayer> { + late String _path; + + @override + void initState() { + super.initState(); + _path = widget.router.routerDelegate.currentConfiguration.uri.path; + widget.router.routerDelegate.addListener(_onRoute); + } + + @override + void dispose() { + widget.router.routerDelegate.removeListener(_onRoute); + super.dispose(); + } + + void _onRoute() { + final path = widget.router.routerDelegate.currentConfiguration.uri.path; + if (path == _path) return; + setState(() => _path = path); + } + + @override + Widget build(BuildContext context) { + return Stack( + children: [ + widget.child ?? const SizedBox.shrink(), + SupportOverlay(currentPath: _path), + ], + ); + } +} diff --git a/prediqo_mobile/lib/core/config/app_config.dart b/prediqo_mobile/lib/core/config/app_config.dart index 3a4a677d..85df5fa2 100644 --- a/prediqo_mobile/lib/core/config/app_config.dart +++ b/prediqo_mobile/lib/core/config/app_config.dart @@ -27,6 +27,31 @@ class AppConfig { /// Defaults to the same host/port as [apiBaseUrl] with path `/ws/...` /// (Docker/nginx proxies `/ws/` on 9080). Override with `--dart-define=WS_URL=...` /// or `--dart-define=WS_PORT=4001` for a dedicated WS port. + /// WebSocket URL for player support chat (`/ws/v1/support`). + String get resolvedSupportWsUrl { + if (wsUrl != null && wsUrl!.isNotEmpty) { + final game = Uri.parse(wsUrl!); + return game.replace(path: '/ws/v1/support', query: '').toString(); + } + final api = Uri.parse(apiBaseUrl); + final wsScheme = api.scheme == 'https' ? 'wss' : 'ws'; + const wsPortOverride = String.fromEnvironment('WS_PORT', defaultValue: ''); + final int? port; + if (wsPortOverride.isNotEmpty) { + port = int.tryParse(wsPortOverride); + } else if (api.hasPort) { + port = api.port; + } else { + port = null; + } + return Uri( + scheme: wsScheme, + host: api.host, + port: port, + path: '/ws/v1/support', + ).toString(); + } + String get resolvedWsUrl { if (wsUrl != null && wsUrl!.isNotEmpty) return wsUrl!; final api = Uri.parse(apiBaseUrl); diff --git a/prediqo_mobile/lib/core/di/injection.dart b/prediqo_mobile/lib/core/di/injection.dart index 06cbb4f6..30179572 100644 --- a/prediqo_mobile/lib/core/di/injection.dart +++ b/prediqo_mobile/lib/core/di/injection.dart @@ -21,9 +21,12 @@ import '../../domain/repositories/repositories.dart'; import '../../features/auth/bloc/auth_bloc.dart'; import '../../features/prediction/bloc/prediction_bloc.dart'; import '../../features/wallet/bloc/wallet_bloc.dart'; +import '../../data/repositories/support_repository.dart'; +import '../../features/support/bloc/support_bloc.dart'; import '../config/app_config.dart'; import '../network/api_client.dart'; import '../realtime/game_socket_service.dart'; +import '../realtime/support_socket_service.dart'; import '../../l10n/locale_controller.dart'; final sl = GetIt.instance; @@ -45,6 +48,14 @@ Future configureDependencies({AppConfig? config}) async { if (!sl.isRegistered()) { sl.registerLazySingleton(() => GameSocketService(sl(), sl())); } + if (!sl.isRegistered()) { + sl.registerLazySingleton(() => SupportRepository(sl())); + } + if (!sl.isRegistered()) { + sl.registerLazySingleton( + () => SupportSocketService(sl(), sl(), sl()), + ); + } if (!sl.isRegistered()) { sl.registerLazySingleton(() => AuthRepositoryImpl(sl())); } @@ -93,4 +104,7 @@ Future configureDependencies({AppConfig? config}) async { if (!sl.isRegistered()) { sl.registerFactory(() => PredictionBloc(sl(), sl(), sl())); } + if (!sl.isRegistered()) { + sl.registerFactory(() => SupportBloc(sl(), sl())); + } } diff --git a/prediqo_mobile/lib/core/network/api_client.dart b/prediqo_mobile/lib/core/network/api_client.dart index fe9c0727..f1bae2ca 100644 --- a/prediqo_mobile/lib/core/network/api_client.dart +++ b/prediqo_mobile/lib/core/network/api_client.dart @@ -121,6 +121,11 @@ class _AuthInterceptor extends Interceptor { return handler.next(err); } } + final refreshToken = await _client.readRefreshToken(); + final isSupport = path.contains('/support/') || uriPath.contains('/support/'); + if (isSupport && (refreshToken == null || refreshToken.isEmpty)) { + return handler.next(err); + } await _expireSession(); } handler.next(err); diff --git a/prediqo_mobile/lib/core/realtime/support_socket_service.dart b/prediqo_mobile/lib/core/realtime/support_socket_service.dart new file mode 100644 index 00000000..680a9aeb --- /dev/null +++ b/prediqo_mobile/lib/core/realtime/support_socket_service.dart @@ -0,0 +1,137 @@ +import 'dart:async'; +import 'dart:convert'; +import 'package:web_socket_channel/web_socket_channel.dart'; +import '../../data/repositories/support_repository.dart'; +import '../config/app_config.dart'; +import '../network/api_client.dart'; + +typedef SupportSocketListener = void Function(Map message); + +/// WebSocket client for `/ws/v1/support` (mirrors web SupportSocketClient). +class SupportSocketService { + SupportSocketService(this._config, this._api, this._repo); + + final AppConfig _config; + final ApiClient _api; + final SupportRepository _repo; + + WebSocketChannel? _channel; + StreamSubscription? _sub; + Timer? _heartbeat; + Timer? _reconnectTimer; + final _listeners = {}; + String? _subscribedConversationId; + bool _connecting = false; + int _reconnectAttempt = 0; + + bool get isConnected => _channel != null; + bool get isEnabled => _config.wsEnabled; + + void addListener(SupportSocketListener listener) => _listeners.add(listener); + void removeListener(SupportSocketListener listener) => _listeners.remove(listener); + + Future connect() async { + if (!isEnabled || _channel != null || _connecting) return; + _connecting = true; + try { + final token = await _api.readAccessToken(); + final visitor = await _repo.visitorToken(); + final uri = Uri.parse(_config.resolvedSupportWsUrl); + final url = uri.replace(queryParameters: { + ...uri.queryParameters, + if (token != null && token.isNotEmpty) 'token': token, + 'visitorToken': visitor, + }).toString(); + final channel = WebSocketChannel.connect(Uri.parse(url)); + await channel.ready.timeout(const Duration(seconds: 8)); + _channel = channel; + _sub = channel.stream.listen( + _onMessage, + onError: (_) => _scheduleReconnect(), + onDone: _scheduleReconnect, + cancelOnError: true, + ); + _reconnectAttempt = 0; + _heartbeat?.cancel(); + _heartbeat = Timer.periodic(const Duration(seconds: 30), (_) { + _send({'type': 'ping', 'ts': DateTime.now().millisecondsSinceEpoch}); + }); + final conv = _subscribedConversationId; + if (conv != null) subscribe(conv); + } catch (_) { + _disposeChannel(); + _scheduleReconnect(); + } finally { + _connecting = false; + } + } + + void subscribe(String conversationId) { + _subscribedConversationId = conversationId; + _send({'type': 'subscribe', 'conversationId': conversationId}); + } + + void unsubscribe() { + final id = _subscribedConversationId; + if (id != null) { + _send({'type': 'unsubscribe', 'conversationId': id}); + } + _subscribedConversationId = null; + } + + void _onMessage(dynamic raw) { + try { + final text = raw is String + ? raw + : raw is List + ? utf8.decode(raw) + : null; + if (text == null) return; + final decoded = jsonDecode(text); + if (decoded is! Map) return; + final map = Map.from(decoded); + for (final l in _listeners) { + l(map); + } + } catch (_) {} + } + + void _send(Map msg) { + final ch = _channel; + if (ch == null) return; + try { + ch.sink.add(jsonEncode(msg)); + } catch (_) {} + } + + void _scheduleReconnect() { + _disposeChannel(); + if (!isEnabled) return; + _reconnectTimer?.cancel(); + final delay = Duration( + milliseconds: (1000 * (1 << _reconnectAttempt.clamp(0, 5))).clamp(1000, 15000), + ); + _reconnectAttempt++; + _reconnectTimer = Timer(delay, () async { + await connect(); + }); + } + + void _disposeChannel() { + _heartbeat?.cancel(); + _heartbeat = null; + _sub?.cancel(); + _sub = null; + try { + _channel?.sink.close(); + } catch (_) {} + _channel = null; + } + + Future dispose() async { + _reconnectTimer?.cancel(); + unsubscribe(); + _disposeChannel(); + _listeners.clear(); + } +} diff --git a/prediqo_mobile/lib/core/router/app_router.dart b/prediqo_mobile/lib/core/router/app_router.dart index 3fa13d42..ce256a3e 100644 --- a/prediqo_mobile/lib/core/router/app_router.dart +++ b/prediqo_mobile/lib/core/router/app_router.dart @@ -33,11 +33,11 @@ import '../../features/wallet/presentation/withdraw_screen.dart'; import '../../features/welcome/presentation/welcome_screen.dart'; import '../../shared/layout/app_shell.dart'; -final _rootNavigatorKey = GlobalKey(); +final rootNavigatorKey = GlobalKey(); GoRouter createAppRouter(AuthBloc authBloc) { return GoRouter( - navigatorKey: _rootNavigatorKey, + navigatorKey: rootNavigatorKey, initialLocation: '/', refreshListenable: GoRouterRefreshStream(authBloc.stream), redirect: (context, state) { diff --git a/prediqo_mobile/lib/data/models/support_models.dart b/prediqo_mobile/lib/data/models/support_models.dart new file mode 100644 index 00000000..e7b16804 --- /dev/null +++ b/prediqo_mobile/lib/data/models/support_models.dart @@ -0,0 +1,88 @@ +class SupportConversationModel { + const SupportConversationModel({ + required this.id, + required this.status, + this.unreadUser = 0, + }); + + final String id; + final String status; + final int unreadUser; + + factory SupportConversationModel.fromJson(Map json) { + return SupportConversationModel( + id: json['id'] as String, + status: (json['status'] ?? 'open').toString(), + unreadUser: (json['unreadUser'] as num?)?.toInt() ?? 0, + ); + } +} + +class SupportMessageModel { + const SupportMessageModel({ + required this.id, + required this.conversationId, + required this.senderType, + required this.createdAt, + this.senderDisplayName, + this.body, + this.attachmentUrl, + this.attachmentName, + this.attachmentMime, + this.readAt, + }); + + final String id; + final String conversationId; + final String senderType; + final String createdAt; + final String? senderDisplayName; + final String? body; + final String? attachmentUrl; + final String? attachmentName; + final String? attachmentMime; + final String? readAt; + + bool get isMine => senderType == 'user' || senderType == 'visitor'; + bool get isImage => attachmentMime?.startsWith('image/') == true; + + SupportMessageModel copyWith({String? readAt}) { + return SupportMessageModel( + id: id, + conversationId: conversationId, + senderType: senderType, + createdAt: createdAt, + senderDisplayName: senderDisplayName, + body: body, + attachmentUrl: attachmentUrl, + attachmentName: attachmentName, + attachmentMime: attachmentMime, + readAt: readAt ?? this.readAt, + ); + } + + factory SupportMessageModel.fromJson(Map json) { + return SupportMessageModel( + id: json['id'] as String, + conversationId: (json['conversationId'] ?? '').toString(), + senderType: (json['senderType'] ?? 'staff').toString(), + createdAt: (json['createdAt'] ?? '').toString(), + senderDisplayName: json['senderDisplayName'] as String?, + body: json['body'] as String?, + attachmentUrl: json['attachmentUrl'] as String?, + attachmentName: json['attachmentName'] as String?, + attachmentMime: json['attachmentMime'] as String?, + readAt: json['readAt'] as String?, + ); + } +} + +class SupportMessagesPage { + const SupportMessagesPage({ + required this.messages, + required this.staffTyping, + }); + + final List messages; + final bool staffTyping; +} diff --git a/prediqo_mobile/lib/data/repositories/support_repository.dart b/prediqo_mobile/lib/data/repositories/support_repository.dart new file mode 100644 index 00000000..d09c0f23 --- /dev/null +++ b/prediqo_mobile/lib/data/repositories/support_repository.dart @@ -0,0 +1,129 @@ +import 'package:dio/dio.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:uuid/uuid.dart'; +import '../../core/errors/app_exception.dart'; +import '../../core/network/api_client.dart'; +import '../models/support_models.dart'; + +const _visitorTokenKey = 'prediqo_support_visitor_token'; + +class SupportRepository { + SupportRepository(this._api); + + final ApiClient _api; + String? _visitorToken; + + Future visitorToken() async { + if (_visitorToken != null && _visitorToken!.length >= 16) { + return _visitorToken!; + } + final prefs = await SharedPreferences.getInstance(); + var token = prefs.getString(_visitorTokenKey); + if (token == null || token.length < 16) { + token = const Uuid().v4().replaceAll('-', ''); + await prefs.setString(_visitorTokenKey, token); + } + _visitorToken = token; + return token; + } + + Future _options() async { + return Options(headers: { + 'X-Support-Visitor-Token': await visitorToken(), + }); + } + + Future getOrCreateConversation() async { + try { + final res = await _api.dio.post>( + '/api/v1/support/conversations/current', + data: const {}, + options: await _options(), + ); + return SupportConversationModel.fromJson(res.data!); + } on DioException catch (e) { + throw AppException.fromDio(e, fallback: 'Failed to open support chat'); + } + } + + Future getMessages(String conversationId) async { + try { + final res = await _api.dio.get>( + '/api/v1/support/conversations/$conversationId/messages', + options: await _options(), + ); + final items = (res.data?['messages'] as List? ?? []) + .map((e) => SupportMessageModel.fromJson(e as Map)) + .toList(); + final typing = res.data?['typing'] as Map?; + return SupportMessagesPage( + messages: items, + staffTyping: typing?['staffTyping'] == true, + ); + } on DioException catch (e) { + throw AppException.fromDio(e, fallback: 'Failed to load messages'); + } + } + + Future sendMessage(String conversationId, String body) async { + try { + final res = await _api.dio.post>( + '/api/v1/support/conversations/$conversationId/messages', + data: {'body': body}, + options: await _options(), + ); + return SupportMessageModel.fromJson(res.data!); + } on DioException catch (e) { + throw AppException.fromDio(e, fallback: 'Failed to send message'); + } + } + + Future sendImage(String conversationId, String filePath) async { + try { + final form = FormData.fromMap({ + 'file': await MultipartFile.fromFile(filePath), + }); + final uploaded = await _api.dio.post>( + '/api/v1/support/conversations/$conversationId/upload', + data: form, + options: Options( + headers: { + 'X-Support-Visitor-Token': await visitorToken(), + }, + contentType: 'multipart/form-data', + ), + ); + final data = uploaded.data!; + final res = await _api.dio.post>( + '/api/v1/support/conversations/$conversationId/messages/attachment', + data: { + 'attachmentUrl': data['attachmentUrl'], + 'attachmentName': data['attachmentName'], + 'attachmentMime': data['attachmentMime'], + }, + options: await _options(), + ); + return SupportMessageModel.fromJson(res.data!); + } on DioException catch (e) { + throw AppException.fromDio(e, fallback: 'Failed to send image'); + } + } + + Future setTyping(String conversationId, bool active) async { + try { + await _api.dio.post( + '/api/v1/support/conversations/$conversationId/typing', + data: {'active': active}, + options: await _options(), + ); + } on DioException { + // Typing is best-effort. + } + } + + String attachmentFullUrl(String relativeUrl) { + if (relativeUrl.startsWith('http')) return relativeUrl; + final base = _api.baseUrl.replaceAll(RegExp(r'/$'), ''); + return '$base$relativeUrl'; + } +} diff --git a/prediqo_mobile/lib/features/prediction/presentation/prediction_screen.dart b/prediqo_mobile/lib/features/prediction/presentation/prediction_screen.dart index c6afaf8e..e5616522 100644 --- a/prediqo_mobile/lib/features/prediction/presentation/prediction_screen.dart +++ b/prediqo_mobile/lib/features/prediction/presentation/prediction_screen.dart @@ -167,27 +167,10 @@ class _PredictionScreenState extends State with WidgetsBinding child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Row( - children: [ - // Web parity: `round.status` is already the authoritative, - // baked-in effective status (see `mergeRound` / - // `_withEffectiveStatus`). Re-deriving it here from a second, - // independent `DateTime.now()` clock (out of sync with - // `_LiveCountdown`'s own ticking clock below) is exactly what - // caused the badge and the big countdown number to briefly - // disagree. Trust the single source of truth instead. - _StatusChip(round?.status ?? 'waiting'), - const Spacer(), - if (round != null) - _LiveCountdown( - key: ValueKey( - '${state.selectedIntervalMinutes}-${round.id}', - ), - round: round, - openLabel: s.timeLeft, - waitLabel: s.waitingRound, - ), - ], + _RoundPhaseHeader( + round: round, + openLabel: s.timeLeft, + waitLabel: s.waitingRound, ), const SizedBox(height: 16), CandleChartWidget( @@ -775,68 +758,55 @@ class _StatusChip extends StatelessWidget { } } -/// Smooth local countdown using serverNowMs skew (web parity). -/// -/// Always derives from the LATEST [widget.round] (already de-duplicated and -/// made monotonic upstream by [mergeRound] / [roundUiChanged] in the bloc) plus -/// a locally ticking clock — exactly like the web `useServerAdjustedCountdown` -/// hook. Deliberately does **not** keep a separate frozen "anchor" snapshot: -/// an earlier version did, and because that anchor was reset independently -/// from the bloc's own change-detection, the two layers could disagree and -/// produce the "55 → 0 → 52 → 0 → 49 → 0" jump bug. A single source of truth -/// (the round passed down) avoids that entirely. -class _LiveCountdown extends StatefulWidget { - const _LiveCountdown({ - super.key, +/// Chip + seconds from the same snapshot, same formula as web +/// `useServerAdjustedCountdown`. Ticks come from the screen's 1s [_uiClock] +/// — no extra timer and no network per second. +class _RoundPhaseHeader extends StatelessWidget { + const _RoundPhaseHeader({ required this.round, required this.openLabel, required this.waitLabel, }); - final RoundModel round; + final RoundModel? round; final String openLabel; final String waitLabel; - @override - State<_LiveCountdown> createState() => _LiveCountdownState(); -} - -class _LiveCountdownState extends State<_LiveCountdown> { - Timer? _timer; - int _nowMs = DateTime.now().millisecondsSinceEpoch; - - @override - void initState() { - super.initState(); - _timer = Timer.periodic(const Duration(milliseconds: 200), (_) { - if (!mounted) return; - setState(() => _nowMs = DateTime.now().millisecondsSinceEpoch); - }); - } - - @override - void dispose() { - _timer?.cancel(); - super.dispose(); - } - @override Widget build(BuildContext context) { - final adjusted = serverAdjustedCountdown(widget.round, clientNowMs: _nowMs); + final current = round; + if (current == null) { + return const Row( + children: [ + _StatusChip('waiting'), + Spacer(), + ], + ); + } + + final adjusted = serverAdjustedCountdown(current); final isOpen = adjusted.bettingOpen; final seconds = isOpen ? adjusted.secondsToBettingEnd : adjusted.secondsToBettingStart; - return Column( - crossAxisAlignment: CrossAxisAlignment.end, + return Row( children: [ - Text( - isOpen ? widget.openLabel : widget.waitLabel, - style: Theme.of(context).textTheme.bodySmall, - ), - Text( - '${seconds}s', - style: Theme.of(context).textTheme.titleLarge?.copyWith(color: AppColors.primary), + _StatusChip(adjusted.effectiveStatus), + const Spacer(), + Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + isOpen ? openLabel : waitLabel, + style: Theme.of(context).textTheme.bodySmall, + ), + Text( + '${seconds}s', + style: Theme.of(context).textTheme.titleLarge?.copyWith( + color: AppColors.primary, + ), + ), + ], ), ], ); diff --git a/prediqo_mobile/lib/features/prediction/utils/server_adjusted_countdown.dart b/prediqo_mobile/lib/features/prediction/utils/server_adjusted_countdown.dart index 81a6196c..00023389 100644 --- a/prediqo_mobile/lib/features/prediction/utils/server_adjusted_countdown.dart +++ b/prediqo_mobile/lib/features/prediction/utils/server_adjusted_countdown.dart @@ -1,5 +1,15 @@ -/// Live countdown using [RoundModel.serverNowMs] skew — same idea as web -/// `useServerAdjustedCountdown`. Avoids stale WS/cache windows jumping the UI. +/// Mobile port of web `useServerAdjustedCountdown`. +/// +/// The web countdown does **not** read `bettingStartMs` / `bettingEndMs`. +/// It freezes one server snapshot (`status`, `secondsToBetting*`, `serverNowMs`) +/// and subtracts local elapsed time: +/// +/// elapsed = floor((clientNow − serverNowMs) / 1000) +/// remaining = max(0, secondsToBettingEnd − elapsed) +/// +/// A 1s local timer drives [clientNow]. No network call is required per tick. +/// A later WS/HTTP message only replaces the snapshot as an atomic unit +/// (same pairing the web `mergeRound` spread keeps when the payload is complete). library; import 'dart:math' as math; @@ -25,7 +35,7 @@ class ServerAdjustedCountdown { final String effectiveStatus; } -/// Computes a stable countdown from a round payload and the current client clock. +/// Same formula as web `useServerAdjustedCountdown`. ServerAdjustedCountdown serverAdjustedCountdown( RoundModel round, { int? clientNowMs, @@ -66,68 +76,41 @@ bool roundUiChanged(RoundModel? prev, RoundModel? next) { prev.longPoolPercent != next.longPoolPercent; } -/// Merges an incoming WS/HTTP round onto [prev], preserving absolute deadlines -/// when the payload omits them (Redis cache historically stripped them). -/// -/// Guards against **out-of-order delivery**: the safety HTTP poll and WS ticks -/// race independently, so a slow HTTP response can resolve *after* a newer WS -/// tick already advanced the countdown. If that stale response's `serverNowMs` -/// is older than what we already have for the same round, its timing fields -/// (status / secondsToBetting* / serverNowMs) are ignored — otherwise the -/// countdown regresses and the derived status flaps (betting → locked → -/// betting), which is exactly what produced the "55 → 0 → 52 → 0 → 49 → 0" bug. +/// Web `mergeRound` is `{ ...prev, ...incoming }` — timing fields of one +/// payload stay together. Mobile must do the same, with one extra guard: +/// Redis/WS ticks sometimes omit `serverNowMs`. Spreading that would pair +/// new `secondsToBetting*` with the previous clock (the 55→0→52→0 flap). +/// In that case the whole previous timing tuple is kept. RoundModel mergeRound(RoundModel? prev, RoundModel incoming) { - if (prev == null) return _withEffectiveStatus(incoming); + if (prev == null) return incoming; final sameRound = prev.id == incoming.id; - final prevServerNow = prev.serverNowMs; - final incomingServerNow = incoming.serverNowMs; - final incomingIsFresher = !sameRound || - incomingServerNow == null || - prevServerNow == null || - incomingServerNow >= prevServerNow; + final incomingHasClock = incoming.serverNowMs != null; + final takeIncomingTiming = !sameRound || incomingHasClock; - final merged = RoundModel( + return RoundModel( id: incoming.id, - status: incomingIsFresher ? incoming.status : prev.status, + status: takeIncomingTiming ? incoming.status : prev.status, secondsToBettingEnd: - incomingIsFresher ? incoming.secondsToBettingEnd : prev.secondsToBettingEnd, - secondsToBettingStart: incomingIsFresher + takeIncomingTiming ? incoming.secondsToBettingEnd : prev.secondsToBettingEnd, + secondsToBettingStart: takeIncomingTiming ? incoming.secondsToBettingStart : prev.secondsToBettingStart, - secondsToClose: incomingIsFresher ? incoming.secondsToClose : prev.secondsToClose, + secondsToClose: + takeIncomingTiming ? incoming.secondsToClose : prev.secondsToClose, outcome: incoming.outcome ?? (sameRound ? prev.outcome : null), shortPoolPercent: incoming.shortPoolPercent ?? (sameRound ? prev.shortPoolPercent : null), longPoolPercent: incoming.longPoolPercent ?? (sameRound ? prev.longPoolPercent : null), - serverNowMs: incomingIsFresher ? (incomingServerNow ?? prevServerNow) : prevServerNow, + serverNowMs: + takeIncomingTiming ? (incoming.serverNowMs ?? prev.serverNowMs) : prev.serverNowMs, candleOpenMs: incoming.candleOpenMs ?? (sameRound ? prev.candleOpenMs : null), bettingEndMs: incoming.bettingEndMs ?? (sameRound ? prev.bettingEndMs : null) ?? incoming.candleOpenMs ?? (sameRound ? prev.candleOpenMs : null), - bettingStartMs: incoming.bettingStartMs ?? - (sameRound ? prev.bettingStartMs : null), - ); - return _withEffectiveStatus(merged); -} - -RoundModel _withEffectiveStatus(RoundModel round) { - final adjusted = serverAdjustedCountdown(round); - if (adjusted.effectiveStatus == round.status) return round; - return RoundModel( - id: round.id, - status: adjusted.effectiveStatus, - secondsToBettingEnd: round.secondsToBettingEnd, - secondsToBettingStart: round.secondsToBettingStart, - secondsToClose: round.secondsToClose, - outcome: round.outcome, - shortPoolPercent: round.shortPoolPercent, - longPoolPercent: round.longPoolPercent, - serverNowMs: round.serverNowMs, - candleOpenMs: round.candleOpenMs, - bettingEndMs: round.bettingEndMs, - bettingStartMs: round.bettingStartMs, + bettingStartMs: + incoming.bettingStartMs ?? (sameRound ? prev.bettingStartMs : null), ); } diff --git a/prediqo_mobile/lib/features/support/bloc/support_bloc.dart b/prediqo_mobile/lib/features/support/bloc/support_bloc.dart new file mode 100644 index 00000000..6f43f6a3 --- /dev/null +++ b/prediqo_mobile/lib/features/support/bloc/support_bloc.dart @@ -0,0 +1,203 @@ +import 'dart:async'; +import 'package:equatable/equatable.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import '../../../core/realtime/support_socket_service.dart'; +import '../../../data/models/support_models.dart'; +import '../../../data/repositories/support_repository.dart'; + +part 'support_event.dart'; +part 'support_state.dart'; + +class SupportBloc extends Bloc { + SupportBloc(this._repo, this._socket) : super(const SupportState()) { + on(_onOpened); + on(_onClosed); + on(_onSend); + on(_onSendImage); + on(_onWs); + on(_onPoll); + on(_onIdentityReset); + _socket.addListener(_handleSocket); + } + + final SupportRepository _repo; + final SupportSocketService _socket; + Timer? _pollTimer; + bool _panelOpen = false; + + void _handleSocket(Map msg) { + add(SupportWsMessageReceived(msg)); + } + + void _startPoll() { + _pollTimer?.cancel(); + _pollTimer = Timer.periodic(const Duration(milliseconds: 2500), (_) { + if (!_panelOpen) return; + add(const SupportPollTick()); + }); + } + + void _stopPoll() { + _pollTimer?.cancel(); + _pollTimer = null; + } + + Future _onOpened(SupportPanelOpened event, Emitter emit) async { + _panelOpen = true; + emit(state.copyWith(open: true, clearError: true)); + if (state.conversation == null) { + emit(state.copyWith(loading: true)); + } + try { + final conv = state.conversation ?? await _repo.getOrCreateConversation(); + if (_socket.isEnabled) { + await _socket.connect(); + _socket.subscribe(conv.id); + } + final page = await _repo.getMessages(conv.id); + emit(state.copyWith( + loading: false, + conversation: conv, + messages: page.messages, + staffTyping: page.staffTyping, + wsConnected: _socket.isConnected, + )); + _startPoll(); + } catch (e) { + emit(state.copyWith(loading: false, errorMessage: e.toString())); + } + } + + Future _onIdentityReset( + SupportIdentityReset event, + Emitter emit, + ) async { + _stopPoll(); + _socket.unsubscribe(); + final keepOpen = state.open; + emit(SupportState(open: keepOpen)); + if (keepOpen) { + add(const SupportPanelOpened()); + } + } + + void _onClosed(SupportPanelClosed event, Emitter emit) { + _panelOpen = false; + _stopPoll(); + final id = state.conversation?.id; + if (id != null) { + unawaited(_repo.setTyping(id, false)); + } + emit(state.copyWith(open: false, staffTyping: false)); + } + + Future _onSend(SupportSendRequested event, Emitter emit) async { + final body = event.body.trim(); + if (body.isEmpty || state.sending) return; + emit(state.copyWith(sending: true, clearError: true)); + try { + var conv = state.conversation; + conv ??= await _repo.getOrCreateConversation(); + unawaited(_repo.setTyping(conv.id, false)); + final msg = await _repo.sendMessage(conv.id, body); + emit(state.copyWith( + sending: false, + conversation: conv, + messages: _append(state.messages, msg), + )); + } catch (e) { + emit(state.copyWith(sending: false, errorMessage: e.toString())); + } + } + + Future _onSendImage( + SupportImageSendRequested event, + Emitter emit, + ) async { + if (state.sending) return; + emit(state.copyWith(sending: true, clearError: true)); + try { + var conv = state.conversation; + conv ??= await _repo.getOrCreateConversation(); + final msg = await _repo.sendImage(conv.id, event.filePath); + emit(state.copyWith( + sending: false, + conversation: conv, + messages: _append(state.messages, msg), + )); + } catch (e) { + emit(state.copyWith(sending: false, errorMessage: e.toString())); + } + } + + void _onWs(SupportWsMessageReceived event, Emitter emit) { + final msg = event.message; + final type = msg['type'] as String?; + final convId = state.conversation?.id; + final msgConv = msg['conversationId'] as String?; + if (convId != null && msgConv != null && msgConv != convId) return; + + switch (type) { + case 'connected': + case 'subscribed': + emit(state.copyWith(wsConnected: true)); + case 'typing': + if (msg['party'] == 'staff') { + emit(state.copyWith(staffTyping: _isTruthy(msg['active']))); + } + case 'message.new': + final raw = msg['message']; + final incoming = raw is Map + ? SupportMessageModel.fromJson(Map.from(raw)) + : null; + if (incoming != null) { + emit(state.copyWith( + messages: _append(state.messages, incoming), + staffTyping: incoming.isMine ? state.staffTyping : false, + )); + } else { + add(const SupportPollTick()); + } + case 'message.read': + emit(state.copyWith( + messages: state.messages + .map((m) => m.isMine ? m.copyWith(readAt: m.readAt ?? DateTime.now().toIso8601String()) : m) + .toList(), + )); + default: + break; + } + } + + Future _onPoll(SupportPollTick event, Emitter emit) async { + final id = state.conversation?.id; + if (id == null) return; + try { + final page = await _repo.getMessages(id); + emit(state.copyWith( + messages: page.messages, + staffTyping: page.staffTyping, + wsConnected: _socket.isConnected, + )); + } catch (_) {} + } + + static bool _isTruthy(dynamic value) { + return value == true || value == 1 || value == 'true'; + } + + static List _append( + List current, + SupportMessageModel incoming, + ) { + if (current.any((m) => m.id == incoming.id)) return current; + return [...current, incoming]; + } + + @override + Future close() { + _stopPoll(); + _socket.removeListener(_handleSocket); + return super.close(); + } +} diff --git a/prediqo_mobile/lib/features/support/bloc/support_event.dart b/prediqo_mobile/lib/features/support/bloc/support_event.dart new file mode 100644 index 00000000..4579da83 --- /dev/null +++ b/prediqo_mobile/lib/features/support/bloc/support_event.dart @@ -0,0 +1,44 @@ +part of 'support_bloc.dart'; + +abstract class SupportEvent extends Equatable { + const SupportEvent(); + @override + List get props => []; +} + +class SupportPanelOpened extends SupportEvent { + const SupportPanelOpened(); +} + +class SupportPanelClosed extends SupportEvent { + const SupportPanelClosed(); +} + +class SupportSendRequested extends SupportEvent { + const SupportSendRequested(this.body); + final String body; + @override + List get props => [body]; +} + +class SupportImageSendRequested extends SupportEvent { + const SupportImageSendRequested(this.filePath); + final String filePath; + @override + List get props => [filePath]; +} + +class SupportWsMessageReceived extends SupportEvent { + const SupportWsMessageReceived(this.message); + final Map message; + @override + List get props => [message]; +} + +class SupportPollTick extends SupportEvent { + const SupportPollTick(); +} + +class SupportIdentityReset extends SupportEvent { + const SupportIdentityReset(); +} diff --git a/prediqo_mobile/lib/features/support/bloc/support_state.dart b/prediqo_mobile/lib/features/support/bloc/support_state.dart new file mode 100644 index 00000000..2755c0b6 --- /dev/null +++ b/prediqo_mobile/lib/features/support/bloc/support_state.dart @@ -0,0 +1,58 @@ +part of 'support_bloc.dart'; + +class SupportState extends Equatable { + const SupportState({ + this.open = false, + this.loading = false, + this.sending = false, + this.wsConnected = false, + this.staffTyping = false, + this.conversation, + this.messages = const [], + this.errorMessage, + }); + + final bool open; + final bool loading; + final bool sending; + final bool wsConnected; + final bool staffTyping; + final SupportConversationModel? conversation; + final List messages; + final String? errorMessage; + + SupportState copyWith({ + bool? open, + bool? loading, + bool? sending, + bool? wsConnected, + bool? staffTyping, + SupportConversationModel? conversation, + List? messages, + String? errorMessage, + bool clearError = false, + }) { + return SupportState( + open: open ?? this.open, + loading: loading ?? this.loading, + sending: sending ?? this.sending, + wsConnected: wsConnected ?? this.wsConnected, + staffTyping: staffTyping ?? this.staffTyping, + conversation: conversation ?? this.conversation, + messages: messages ?? this.messages, + errorMessage: clearError ? null : (errorMessage ?? this.errorMessage), + ); + } + + @override + List get props => [ + open, + loading, + sending, + wsConnected, + staffTyping, + conversation, + messages, + errorMessage, + ]; +} diff --git a/prediqo_mobile/lib/features/support/presentation/support_message_input.dart b/prediqo_mobile/lib/features/support/presentation/support_message_input.dart new file mode 100644 index 00000000..fbdb47ba --- /dev/null +++ b/prediqo_mobile/lib/features/support/presentation/support_message_input.dart @@ -0,0 +1,53 @@ +import 'package:flutter/material.dart'; +import '../../../core/theme/app_colors.dart'; + +/// Single [TextEditingController] owned by the parent. This widget never +/// writes into the controller — only the user (IME) and an explicit [clear] +/// after a successful send may change the value. +class SupportMessageInput extends StatelessWidget { + const SupportMessageInput({ + super.key, + required this.controller, + required this.focusNode, + required this.hintText, + this.onChanged, + this.onSubmitted, + }); + + final TextEditingController controller; + final FocusNode focusNode; + final String hintText; + final ValueChanged? onChanged; + final VoidCallback? onSubmitted; + + @override + Widget build(BuildContext context) { + return TextField( + controller: controller, + focusNode: focusNode, + minLines: 1, + maxLines: 1, + textInputAction: TextInputAction.send, + onChanged: onChanged, + onSubmitted: (_) => onSubmitted?.call(), + decoration: InputDecoration( + hintText: hintText, + filled: true, + fillColor: AppColors.surfaceElevated, + contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(20), + borderSide: BorderSide.none, + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(20), + borderSide: const BorderSide(color: AppColors.primary, width: 1.2), + ), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(20), + borderSide: BorderSide.none, + ), + ), + ); + } +} diff --git a/prediqo_mobile/lib/features/support/presentation/support_widget.dart b/prediqo_mobile/lib/features/support/presentation/support_widget.dart new file mode 100644 index 00000000..9c263743 --- /dev/null +++ b/prediqo_mobile/lib/features/support/presentation/support_widget.dart @@ -0,0 +1,745 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:image_picker/image_picker.dart'; +import '../../../core/router/app_router.dart'; +import '../../../core/theme/app_colors.dart'; +import '../../../data/models/support_models.dart'; +import '../../../data/repositories/support_repository.dart'; +import '../../../l10n/app_strings.dart'; +import '../../auth/bloc/auth_bloc.dart'; +import '../bloc/support_bloc.dart'; +import 'support_message_input.dart'; + +/// Floating support chat for players and guests (hidden for admins, like web). +class SupportOverlay extends StatelessWidget { + const SupportOverlay({super.key, this.currentPath}); + + final String? currentPath; + + static final _hostKey = GlobalKey(); + + @override + Widget build(BuildContext context) { + final hide = context.select((bloc) { + final auth = bloc.state; + return auth.isAdmin || + auth.status == AuthStatus.initial || + auth.status == AuthStatus.loading; + }); + if (hide) return const SizedBox.shrink(); + + final path = currentPath ?? ''; + if (path == '/') return const SizedBox.shrink(); + + return BlocListener( + listenWhen: (prev, next) => + prev.userId != next.userId || prev.isSignedIn != next.isSignedIn, + listener: (context, _) { + context.read().add(const SupportIdentityReset()); + }, + child: SupportChatHost(key: _hostKey), + ); + } +} + +class SupportChatHost extends StatefulWidget { + const SupportChatHost({super.key}); + + @override + State createState() => _SupportChatHostState(); +} + +class _SupportChatHostState extends State { + bool _revealed = false; + Timer? _hideTimer; + + @override + void dispose() { + _hideTimer?.cancel(); + super.dispose(); + } + + void _revealLauncher() { + _hideTimer?.cancel(); + setState(() => _revealed = true); + _hideTimer = Timer(const Duration(seconds: 5), () { + if (!mounted) return; + if (context.read().state.open) return; + setState(() => _revealed = false); + }); + } + + void _collapseLauncher() { + _hideTimer?.cancel(); + if (_revealed) setState(() => _revealed = false); + } + + Future _openChat() async { + _hideTimer?.cancel(); + final bloc = context.read(); + if (bloc.state.open) return; + bloc.add(const SupportPanelOpened()); + final navContext = rootNavigatorKey.currentContext; + if (navContext == null || !navContext.mounted) { + bloc.add(const SupportPanelClosed()); + return; + } + await showModalBottomSheet( + context: navContext, + useRootNavigator: true, + isScrollControlled: true, + useSafeArea: true, + backgroundColor: Colors.transparent, + builder: (ctx) { + return Padding( + padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(ctx).bottom), + child: const _SupportSheet(), + ); + }, + ); + if (!bloc.isClosed) { + bloc.add(const SupportPanelClosed()); + } + if (mounted) _collapseLauncher(); + } + + @override + Widget build(BuildContext context) { + return BlocBuilder( + buildWhen: (prev, next) => prev.open != next.open, + builder: (context, state) { + if (state.open) return const SizedBox.shrink(); + final tabTop = MediaQuery.sizeOf(context).height * 0.38; + return Stack( + children: [ + Positioned( + right: 0, + top: tabTop, + child: _SupportEdgeLauncher( + revealed: _revealed, + onPeekTap: _revealLauncher, + onFabTap: _openChat, + ), + ), + ], + ); + }, + ); + } +} + +class _SupportEdgeLauncher extends StatelessWidget { + const _SupportEdgeLauncher({ + required this.revealed, + required this.onPeekTap, + required this.onFabTap, + }); + + final bool revealed; + final VoidCallback onPeekTap; + final VoidCallback onFabTap; + + @override + Widget build(BuildContext context) { + final s = context.strings; + return AnimatedSize( + duration: const Duration(milliseconds: 220), + curve: Curves.easeOutCubic, + alignment: Alignment.centerRight, + child: revealed + ? Padding( + padding: const EdgeInsets.only(right: 12), + child: FloatingActionButton( + heroTag: 'tloto-support-fab', + mini: true, + tooltip: s.supportTitle, + backgroundColor: AppColors.primary, + foregroundColor: const Color(0xFF0B0F1A), + onPressed: onFabTap, + child: const Icon(Icons.headset_mic_rounded), + ), + ) + : Tooltip( + message: s.supportTitle, + child: Material( + color: AppColors.primary, + elevation: 4, + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(12), + bottomLeft: Radius.circular(12), + ), + child: InkWell( + onTap: onPeekTap, + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(12), + bottomLeft: Radius.circular(12), + ), + child: const SizedBox( + width: 22, + height: 52, + child: Icon( + Icons.headset_mic_rounded, + size: 16, + color: Color(0xFF0B0F1A), + ), + ), + ), + ), + ), + ); + } +} + +class _SupportSheet extends StatelessWidget { + const _SupportSheet(); + + @override + Widget build(BuildContext context) { + final s = context.strings; + final maxHeight = + (MediaQuery.sizeOf(context).height * 0.62).clamp(320.0, 520.0); + return Material( + elevation: 12, + color: AppColors.surfaceCard, + borderRadius: BorderRadius.circular(16), + clipBehavior: Clip.antiAlias, + child: SizedBox( + height: maxHeight, + child: Column( + children: [ + Container( + padding: const EdgeInsets.fromLTRB(16, 12, 4, 12), + color: AppColors.primary, + child: Row( + children: [ + const Icon(Icons.headset_mic_rounded, color: Color(0xFF0B0F1A)), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + s.supportTitle, + style: const TextStyle( + color: Color(0xFF0B0F1A), + fontWeight: FontWeight.w800, + fontSize: 15, + ), + ), + BlocBuilder( + buildWhen: (p, c) => p.staffTyping != c.staffTyping, + builder: (context, state) { + return Text( + state.staffTyping + ? s.supportTyping + : '${s.supportSubtitle} · 2.0.2', + style: TextStyle( + color: const Color(0xFF0B0F1A).withValues(alpha: 0.8), + fontSize: 11, + fontWeight: FontWeight.w600, + ), + ); + }, + ), + ], + ), + ), + IconButton( + onPressed: () => Navigator.of(context).maybePop(), + icon: const Icon(Icons.close_rounded, color: Color(0xFF0B0F1A)), + ), + ], + ), + ), + const Expanded(child: _SupportMessages()), + const _SupportComposer(), + ], + ), + ), + ); + } +} + +class _SupportMessages extends StatefulWidget { + const _SupportMessages(); + + @override + State<_SupportMessages> createState() => _SupportMessagesState(); +} + +class _SupportMessagesState extends State<_SupportMessages> { + final _scroll = ScrollController(); + + @override + void dispose() { + _scroll.dispose(); + super.dispose(); + } + + void _jumpToEnd() { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!_scroll.hasClients) return; + _scroll.jumpTo(_scroll.position.maxScrollExtent); + }); + } + + @override + Widget build(BuildContext context) { + final s = context.strings; + return BlocConsumer( + listenWhen: (prev, next) => + prev.messages.length != next.messages.length || + prev.staffTyping != next.staffTyping, + listener: (context, state) => _jumpToEnd(), + builder: (context, state) { + if (state.loading && state.messages.isEmpty) { + return const Center(child: CircularProgressIndicator(strokeWidth: 2)); + } + if (state.errorMessage != null && state.messages.isEmpty) { + return Center( + child: Padding( + padding: const EdgeInsets.all(20), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(s.supportLoadError, textAlign: TextAlign.center), + const SizedBox(height: 12), + TextButton( + onPressed: () => + context.read().add(const SupportPanelOpened()), + child: Text(s.retry), + ), + ], + ), + ), + ); + } + if (state.messages.isEmpty) { + return Column( + children: [ + Expanded( + child: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Text( + s.supportGreeting, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + color: AppColors.textMuted, + ), + ), + ), + ), + ), + if (state.staffTyping) + const Padding( + padding: EdgeInsets.fromLTRB(12, 0, 12, 10), + child: Align( + alignment: Alignment.centerLeft, + child: _StaffTypingBubble(), + ), + ), + ], + ); + } + + var lastDay = ''; + return ListView.builder( + controller: _scroll, + padding: const EdgeInsets.fromLTRB(12, 12, 12, 8), + itemCount: state.messages.length + (state.staffTyping ? 1 : 0), + itemBuilder: (context, index) { + if (index == state.messages.length) { + return const Padding( + padding: EdgeInsets.only(top: 4, bottom: 4), + child: Align( + alignment: Alignment.centerLeft, + child: _StaffTypingBubble(), + ), + ); + } + final msg = state.messages[index]; + final day = _dayLabel(s, msg.createdAt); + final showDay = day != lastDay; + lastDay = day; + return Column( + children: [ + if (showDay) + Padding( + padding: const EdgeInsets.symmetric(vertical: 10), + child: Text( + day, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: AppColors.textMuted, + fontWeight: FontWeight.w700, + ), + ), + ), + _MessageBubble(message: msg), + ], + ); + }, + ); + }, + ); + } + + String _dayLabel(AppStrings s, String iso) { + final dt = DateTime.tryParse(iso)?.toLocal(); + if (dt == null) return ''; + final now = DateTime.now(); + final today = DateTime(now.year, now.month, now.day); + final day = DateTime(dt.year, dt.month, dt.day); + if (day == today) return s.supportToday; + if (day == today.subtract(const Duration(days: 1))) return s.supportYesterday; + return '${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')}/${dt.year}'; + } +} + +class _StaffTypingBubble extends StatefulWidget { + const _StaffTypingBubble(); + + @override + State<_StaffTypingBubble> createState() => _StaffTypingBubbleState(); +} + +class _StaffTypingBubbleState extends State<_StaffTypingBubble> + with SingleTickerProviderStateMixin { + late final AnimationController _pulse; + + @override + void initState() { + super.initState(); + _pulse = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 900), + )..repeat(); + } + + @override + void dispose() { + _pulse.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final s = context.strings; + return Container( + padding: const EdgeInsets.fromLTRB(12, 8, 14, 8), + decoration: BoxDecoration( + color: AppColors.surfaceElevated, + borderRadius: const BorderRadius.only( + topLeft: Radius.circular(16), + topRight: Radius.circular(16), + bottomLeft: Radius.circular(4), + bottomRight: Radius.circular(16), + ), + border: Border.all(color: AppColors.border), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + AnimatedBuilder( + animation: _pulse, + builder: (context, _) { + return Row( + mainAxisSize: MainAxisSize.min, + children: List.generate(3, (i) { + final t = (_pulse.value + i * 0.2) % 1.0; + final dy = -3.5 * (1 - (2 * t - 1).abs()); + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 2), + child: Transform.translate( + offset: Offset(0, dy), + child: Container( + width: 6, + height: 6, + decoration: const BoxDecoration( + color: AppColors.textMuted, + shape: BoxShape.circle, + ), + ), + ), + ); + }), + ); + }, + ), + const SizedBox(width: 8), + Text( + s.supportTyping, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: AppColors.textMuted, + fontStyle: FontStyle.italic, + ), + ), + ], + ), + ); + } +} + +class _MessageBubble extends StatelessWidget { + const _MessageBubble({required this.message}); + + final SupportMessageModel message; + + @override + Widget build(BuildContext context) { + final s = context.strings; + final mine = message.isMine; + final repo = context.read(); + final time = _formatTime(message.createdAt); + + return Align( + alignment: mine ? Alignment.centerRight : Alignment.centerLeft, + child: Container( + constraints: BoxConstraints( + maxWidth: MediaQuery.sizeOf(context).width * 0.72, + ), + margin: const EdgeInsets.only(bottom: 8), + padding: const EdgeInsets.fromLTRB(12, 8, 12, 6), + decoration: BoxDecoration( + color: mine ? AppColors.primary : AppColors.surfaceElevated, + borderRadius: BorderRadius.only( + topLeft: const Radius.circular(16), + topRight: const Radius.circular(16), + bottomLeft: Radius.circular(mine ? 16 : 4), + bottomRight: Radius.circular(mine ? 4 : 16), + ), + border: mine ? null : Border.all(color: AppColors.border), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (!mine && + message.senderType == 'staff' && + (message.senderDisplayName ?? '').isNotEmpty) + Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Text( + message.senderDisplayName!, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w800, + color: mine ? const Color(0xFF0B0F1A) : AppColors.primary, + ), + ), + ), + if ((message.body ?? '').isNotEmpty) + Text( + message.body!, + style: TextStyle( + color: mine ? const Color(0xFF0B0F1A) : Colors.white, + height: 1.35, + ), + ), + if (message.attachmentUrl != null) ...[ + if ((message.body ?? '').isNotEmpty) const SizedBox(height: 8), + if (message.isImage) + ClipRRect( + borderRadius: BorderRadius.circular(8), + child: Image.network( + repo.attachmentFullUrl(message.attachmentUrl!), + fit: BoxFit.cover, + errorBuilder: (_, __, ___) => Text( + message.attachmentName ?? s.supportAttachment, + style: TextStyle( + color: mine ? const Color(0xFF0B0F1A) : Colors.white, + fontWeight: FontWeight.w700, + ), + ), + ), + ) + else + Text( + '📎 ${message.attachmentName ?? s.supportFile}', + style: TextStyle( + color: mine ? const Color(0xFF0B0F1A) : Colors.white, + fontWeight: FontWeight.w700, + ), + ), + ], + const SizedBox(height: 4), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + time, + style: TextStyle( + fontSize: 10, + color: mine + ? const Color(0xFF0B0F1A).withValues(alpha: 0.7) + : AppColors.textMuted, + ), + ), + if (mine) ...[ + const SizedBox(width: 4), + Icon( + message.readAt != null ? Icons.done_all : Icons.done, + size: 14, + color: message.readAt != null + ? const Color(0xFF065F46) + : const Color(0xFF0B0F1A).withValues(alpha: 0.55), + ), + ], + ], + ), + ], + ), + ), + ); + } + + String _formatTime(String iso) { + final dt = DateTime.tryParse(iso)?.toLocal(); + if (dt == null) return ''; + return '${dt.hour.toString().padLeft(2, '0')}:${dt.minute.toString().padLeft(2, '0')}'; + } +} + +class _SupportComposer extends StatefulWidget { + const _SupportComposer(); + + @override + State<_SupportComposer> createState() => _SupportComposerState(); +} + +class _SupportComposerState extends State<_SupportComposer> { + late final TextEditingController _text; + late final FocusNode _focus; + Timer? _typingTimer; + + @override + void initState() { + super.initState(); + _text = TextEditingController(); + _focus = FocusNode(); + } + + @override + void dispose() { + _typingTimer?.cancel(); + _focus.dispose(); + _text.dispose(); + super.dispose(); + } + + void _notifyTyping(bool active) { + if (!mounted) return; + final id = context.read().state.conversation?.id; + if (id == null) return; + unawaited(context.read().setTyping(id, active)); + } + + void _onChanged(String value) { + _notifyTyping(value.trim().isNotEmpty); + _typingTimer?.cancel(); + _typingTimer = Timer(const Duration(seconds: 2), () => _notifyTyping(false)); + } + + void _submit() { + final body = _text.text.trim(); + if (body.isEmpty) return; + _typingTimer?.cancel(); + _notifyTyping(false); + context.read().add(SupportSendRequested(body)); + } + + Future _pickImage() async { + final picker = ImagePicker(); + final file = await picker.pickImage(source: ImageSource.gallery, imageQuality: 85); + if (!mounted || file == null) return; + context.read().add(SupportImageSendRequested(file.path)); + } + + @override + Widget build(BuildContext context) { + final s = context.strings; + return BlocListener( + listenWhen: (p, c) => + (p.sending && !c.sending && c.errorMessage == null) || + (p.errorMessage != c.errorMessage && c.errorMessage != null), + listener: (context, state) { + if (!state.sending && state.errorMessage == null) { + _text.clear(); + } + final error = state.errorMessage; + if (error != null) { + ScaffoldMessenger.maybeOf(context)?.showSnackBar( + SnackBar(content: Text(error)), + ); + } + }, + child: Container( + padding: const EdgeInsets.fromLTRB(10, 8, 10, 10), + decoration: const BoxDecoration( + border: Border(top: BorderSide(color: AppColors.border)), + ), + child: Row( + children: [ + BlocBuilder( + buildWhen: (p, c) => p.sending != c.sending, + builder: (context, state) { + return IconButton( + onPressed: state.sending ? null : _pickImage, + icon: const Icon(Icons.attach_file_rounded), + color: AppColors.textMuted, + ); + }, + ), + Expanded( + child: SupportMessageInput( + controller: _text, + focusNode: _focus, + hintText: s.supportPlaceholder, + onChanged: _onChanged, + onSubmitted: _submit, + ), + ), + const SizedBox(width: 6), + ListenableBuilder( + listenable: _text, + builder: (context, _) { + return BlocBuilder( + buildWhen: (p, c) => p.sending != c.sending, + builder: (context, state) { + final canSend = _text.text.trim().isNotEmpty && !state.sending; + return Material( + color: canSend ? AppColors.primary : AppColors.surfaceElevated, + shape: const CircleBorder(), + child: InkWell( + customBorder: const CircleBorder(), + onTap: canSend ? _submit : null, + child: SizedBox( + width: 44, + height: 44, + child: Center( + child: state.sending + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : Icon( + Icons.send_rounded, + color: canSend + ? const Color(0xFF0B0F1A) + : AppColors.textMuted, + ), + ), + ), + ), + ); + }, + ); + }, + ), + ], + ), + ), + ); + } +} diff --git a/prediqo_mobile/lib/l10n/app_strings.dart b/prediqo_mobile/lib/l10n/app_strings.dart index f9605921..21ce8f66 100644 --- a/prediqo_mobile/lib/l10n/app_strings.dart +++ b/prediqo_mobile/lib/l10n/app_strings.dart @@ -643,6 +643,26 @@ class AppStrings { String get referralProgram => t('Referral program', 'Programme de parrainage'); String get helpFaq => t('Help & FAQ', 'Aide & FAQ'); + String get supportTitle => t('Tloto Support', 'Assistance Tloto'); + String get supportSubtitle => t( + 'Real-time response from our team', + 'Réponse en temps réel de notre équipe', + ); + String get supportGreeting => t( + 'Hello! How can we help you?', + 'Bonjour ! Comment pouvons-nous vous aider ?', + ); + String get supportTyping => t('The team is typing…', 'L’équipe est en train d’écrire…'); + String get supportPlaceholder => t('Type your message…', 'Écrivez votre message…'); + String get supportToday => t('Today', 'Aujourd’hui'); + String get supportYesterday => t('Yesterday', 'Hier'); + String get supportFile => t('File', 'Fichier'); + String get supportAttachment => t('attachment', 'pièce jointe'); + String get supportLoadError => t( + 'Could not open support chat. Please try again.', + 'Impossible d’ouvrir le chat support. Réessayez.', + ); + // Common String get cancel => t('Cancel', 'Annuler'); String get retry => t('Retry', 'Réessayer'); diff --git a/prediqo_mobile/pubspec.lock b/prediqo_mobile/pubspec.lock index ee067cbd..b8de38a6 100644 --- a/prediqo_mobile/pubspec.lock +++ b/prediqo_mobile/pubspec.lock @@ -169,6 +169,38 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.1" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: "2567f398e06ac72dcf2e98a0c95df2a9edd03c2c2e0cacd4780f20cdf56263a0" + url: "https://pub.dev" + source: hosted + version: "0.9.4" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: "5e0bbe9c312416f1787a68259ea1505b52f258c587f12920422671807c4d618a" + url: "https://pub.dev" + source: hosted + version: "0.9.5" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85" + url: "https://pub.dev" + source: hosted + version: "2.7.0" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: "62197474ae75893a62df75939c777763d39c2bc5f73ce5b88497208bc269abfd" + url: "https://pub.dev" + source: hosted + version: "0.9.3+5" fixnum: dependency: transitive description: @@ -232,6 +264,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.4.7" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: "38d1c268de9097ff59cf0e844ac38759fc78f76836d37edad06fa21e182055a0" + url: "https://pub.dev" + source: hosted + version: "2.0.34" flutter_secure_storage: dependency: "direct main" description: @@ -359,6 +399,70 @@ packages: url: "https://pub.dev" source: hosted version: "4.8.0" + image_picker: + dependency: "direct main" + description: + name: image_picker + sha256: "91c025426c2881c551100bce834e201c835a170151545f58d17da5180ca7d9ac" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + image_picker_android: + dependency: transitive + description: + name: image_picker_android + sha256: d5b3e1774af29c9ab00103afb0d4614070f924d2e0057ac867ec98800114793f + url: "https://pub.dev" + source: hosted + version: "0.8.13+17" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + sha256: "66257a3191ab360d23a55c8241c91a6e329d31e94efa7be9cf7a212e65850214" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + image_picker_ios: + dependency: transitive + description: + name: image_picker_ios + sha256: "956c16a42c0c708f914021666ffcd8265dde36e673c9fa68c81f7d085d9774ad" + url: "https://pub.dev" + source: hosted + version: "0.8.13+3" + image_picker_linux: + dependency: transitive + description: + name: image_picker_linux + sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4" + url: "https://pub.dev" + source: hosted + version: "0.2.2" + image_picker_macos: + dependency: transitive + description: + name: image_picker_macos + sha256: "86f0f15a309de7e1a552c12df9ce5b59fe927e71385329355aec4776c6a8ec91" + url: "https://pub.dev" + source: hosted + version: "0.2.2+1" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + sha256: "567e056716333a1647c64bb6bd873cff7622233a5c3f694be28a583d4715690c" + url: "https://pub.dev" + source: hosted + version: "2.11.1" + image_picker_windows: + dependency: transitive + description: + name: image_picker_windows + sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae + url: "https://pub.dev" + source: hosted + version: "0.2.2" integration_test: dependency: "direct dev" description: flutter diff --git a/prediqo_mobile/pubspec.yaml b/prediqo_mobile/pubspec.yaml index 3ef46637..ba5b0dfe 100644 --- a/prediqo_mobile/pubspec.yaml +++ b/prediqo_mobile/pubspec.yaml @@ -1,7 +1,7 @@ name: prediqo_mobile description: "Tloto mobile app - prediction games and crypto wallet." publish_to: 'none' -version: 2.0.0+1 +version: 2.0.2+3 environment: sdk: ^3.9.2 @@ -30,6 +30,7 @@ dependencies: package_info_plus: ^9.0.1 share_plus: ^12.0.2 path_provider: ^2.1.5 + image_picker: ^1.1.2 dev_dependencies: flutter_test: