Phase 3: session-end UX overhaul + closing-grace cleanup
Promotes the customer-side chat WebSocket to active-session-scoped (driven by a new `activeSessionProvider`) so home reflects session state in real time without a per-screen connection. Backend now auto-completes sessions left in `closing` after a 5-minute grace window so abandoned goodbye flows don't leave the customer's home permanently locked. Customer: - New `activeSessionProvider` (replaces `unread_notifier`) — single source of truth for the active session + unread count; polled every 15s. - Chat WS lifecycle moved to `main.dart` listener on activeSessionProvider. Chat screen joins via `connectIfNotConnected`; the new `refreshSessionStatus` reconciles flags from the server when re-entering an already-connected session (covers missed `sessionClosing`/`sessionExpired` WS events). - Home filters `closing` from the "Sesi Aktif" CTA so a session pending goodbye doesn't block "Mulai Curhat". - Timer-expired UX is a non-dismissible modal (Tutup / Perpanjang) instead of an inline bar. - Early-end goodbye composer gets an amber "Sesi telah ditutup oleh Bestie" banner. Goodbye TextEditingController lifted to state so focus changes no longer wipe the message. - Closure provider reset on chat_screen mount to avoid stale `ClosureCompleteData` from a previous session leaking into a new view. - Chat history now lists `closing` sessions with a "Belum ditutup" badge that routes to the live chat (goodbye composer) instead of the transcript. Mitra: - Same goodbye-controller fix as customer. - Same chat-history badge + routing for `closing` items. Backend: - New `EndedBy.SYSTEM_AUTO_CLOSE` constant. - `startClosureGraceTimer` extracted in `session-timer.service.js`; wired in from `closure.initiateEarlyEnd`, `extension.rejectExtension`, and `extension.handleExtensionTimeout`. Cancelled when customer submits goodbye. - Restart recovery (`restoreActiveTimers`) re-arms grace timers and stamps any orphaned `closing` rows with `system_auto_close`. - `getCustomerHistory` / `getMitraHistory` include `closing` alongside `completed`; ordering uses `COALESCE(ended_at, created_at)`. Removed: dead `session_active_screen.dart` (no router entry). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
89
client_app/lib/core/chat/active_session_notifier.dart
Normal file
89
client_app/lib/core/chat/active_session_notifier.dart
Normal file
@@ -0,0 +1,89 @@
|
||||
import 'dart:async';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import '../api/api_client_provider.dart';
|
||||
|
||||
part 'active_session_notifier.g.dart';
|
||||
|
||||
/// Snapshot of the current customer's active session (if any) plus its
|
||||
/// unread-message count. Backed by `/api/client/chat/session/active-with-unread`.
|
||||
///
|
||||
/// Lives at app-scope so the home CTA, the global chat WebSocket lifecycle
|
||||
/// (see `main.dart`), and any badge consumers all share one source of truth.
|
||||
class ActiveSessionData {
|
||||
final Map<String, dynamic>? session;
|
||||
final int unreadCount;
|
||||
|
||||
const ActiveSessionData({this.session, this.unreadCount = 0});
|
||||
|
||||
bool get hasSession => session != null;
|
||||
String? get sessionId => session?['id'] as String?;
|
||||
String get mitraName =>
|
||||
(session?['mitra_display_name'] as String?) ?? 'Bestie';
|
||||
|
||||
static const empty = ActiveSessionData();
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class ActiveSession extends _$ActiveSession {
|
||||
Timer? _pollTimer;
|
||||
|
||||
@override
|
||||
Future<ActiveSessionData> build() async {
|
||||
ref.onDispose(_stopPolling);
|
||||
_startPolling();
|
||||
return await _fetch();
|
||||
}
|
||||
|
||||
void _startPolling() {
|
||||
_stopPolling();
|
||||
_pollTimer = Timer.periodic(const Duration(seconds: 15), (_) async {
|
||||
try {
|
||||
final next = await _fetch();
|
||||
state = AsyncData(next);
|
||||
} catch (_) {
|
||||
// Keep last known state on transient failures.
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _stopPolling() {
|
||||
_pollTimer?.cancel();
|
||||
_pollTimer = null;
|
||||
}
|
||||
|
||||
Future<ActiveSessionData> _fetch() async {
|
||||
final apiClient = ref.read(apiClientProvider);
|
||||
final response = await apiClient.get('/api/client/chat/session/active-with-unread');
|
||||
final data = response['data'];
|
||||
if (data is Map<String, dynamic>) {
|
||||
return ActiveSessionData(
|
||||
session: data,
|
||||
unreadCount: data['unread_count'] as int? ?? 0,
|
||||
);
|
||||
}
|
||||
return ActiveSessionData.empty;
|
||||
}
|
||||
|
||||
/// Force a fresh fetch (e.g. on resume, after pairing succeeds, after a
|
||||
/// session ends). Updates `state` synchronously to AsyncLoading-with-prev
|
||||
/// then to AsyncData.
|
||||
Future<void> refresh() async {
|
||||
try {
|
||||
final next = await _fetch();
|
||||
state = AsyncData(next);
|
||||
} catch (e, st) {
|
||||
state = AsyncError(e, st);
|
||||
}
|
||||
}
|
||||
|
||||
/// Optimistic local-only update: clear unread without a round-trip
|
||||
/// (used after the chat screen marks messages read).
|
||||
void markRead() {
|
||||
final current = state.valueOrNull;
|
||||
if (current == null || !current.hasSession) return;
|
||||
state = AsyncData(ActiveSessionData(
|
||||
session: current.session,
|
||||
unreadCount: 0,
|
||||
));
|
||||
}
|
||||
}
|
||||
26
client_app/lib/core/chat/active_session_notifier.g.dart
Normal file
26
client_app/lib/core/chat/active_session_notifier.g.dart
Normal file
@@ -0,0 +1,26 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'active_session_notifier.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$activeSessionHash() => r'8d7dec22d94b3efc32e0401b9a82a5f712e6cc16';
|
||||
|
||||
/// See also [ActiveSession].
|
||||
@ProviderFor(ActiveSession)
|
||||
final activeSessionProvider =
|
||||
AsyncNotifierProvider<ActiveSession, ActiveSessionData>.internal(
|
||||
ActiveSession.new,
|
||||
name: r'activeSessionProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$activeSessionHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$ActiveSession = AsyncNotifier<ActiveSessionData>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package
|
||||
@@ -6,6 +6,7 @@ import '../api/api_client.dart';
|
||||
import '../api/api_client_provider.dart';
|
||||
import '../auth/auth_bridge.dart';
|
||||
import '../constants.dart';
|
||||
import 'active_session_notifier.dart';
|
||||
|
||||
part 'chat_notifier.g.dart';
|
||||
|
||||
@@ -102,13 +103,64 @@ class Chat extends _$Chat {
|
||||
WebSocketChannel? _channel;
|
||||
StreamSubscription? _wsSubscription;
|
||||
Timer? _typingTimer;
|
||||
String? _connectedSessionId;
|
||||
|
||||
ApiClient get _apiClient => ref.read(apiClientProvider);
|
||||
|
||||
@override
|
||||
ChatData build() => const ChatInitialData();
|
||||
|
||||
/// Idempotent connect: if we're already connected to [sessionId], refresh
|
||||
/// the session status from the server (in case it transitioned to closing /
|
||||
/// expired while we weren't watching closely) but reuse the live WS.
|
||||
/// If we're connected to a different session, disconnect first.
|
||||
Future<void> connectIfNotConnected(String sessionId) async {
|
||||
// ignore: avoid_print
|
||||
print('[CONNECT_IF_NOT] target=$sessionId existing=$_connectedSessionId state=${state.runtimeType}');
|
||||
if (_connectedSessionId == sessionId &&
|
||||
(state is ChatConnectedData || state is ChatConnectingData)) {
|
||||
await refreshSessionStatus(sessionId);
|
||||
return;
|
||||
}
|
||||
if (_connectedSessionId != null && _connectedSessionId != sessionId) {
|
||||
_cleanup();
|
||||
}
|
||||
await connect(sessionId);
|
||||
}
|
||||
|
||||
/// Re-pull session status from the server and reconcile local flags. Used
|
||||
/// when re-entering the chat screen for a session we're already connected
|
||||
/// to — covers the case where a `sessionClosing` / `sessionExpired` WS event
|
||||
/// was missed (e.g. socket dropped, app backgrounded, status changed before
|
||||
/// we connected).
|
||||
Future<void> refreshSessionStatus(String sessionId) async {
|
||||
final current = state;
|
||||
// ignore: avoid_print
|
||||
print('[REFRESH_STATUS] called sessionId=$sessionId currentState=${current.runtimeType}');
|
||||
if (current is! ChatConnectedData) return;
|
||||
try {
|
||||
final info = await _apiClient.get('/api/shared/chat/$sessionId/info');
|
||||
final data = info['data'] as Map<String, dynamic>?;
|
||||
final status = data?['status'] as String?;
|
||||
// ignore: avoid_print
|
||||
print('[REFRESH_STATUS] backend status=$status');
|
||||
if (status == SessionStatus.completed ||
|
||||
status == SessionStatus.cancelled ||
|
||||
status == SessionStatus.expired) {
|
||||
state = current.copyWith(sessionExpired: true);
|
||||
return;
|
||||
}
|
||||
state = current.copyWith(
|
||||
sessionClosing: status == SessionStatus.closing,
|
||||
);
|
||||
} catch (e) {
|
||||
// ignore: avoid_print
|
||||
print('[REFRESH_STATUS] error=$e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> connect(String sessionId) async {
|
||||
_connectedSessionId = sessionId;
|
||||
state = const ChatConnectingData();
|
||||
|
||||
try {
|
||||
@@ -174,6 +226,8 @@ class Chat extends _$Chat {
|
||||
state = const ChatInitialData();
|
||||
}
|
||||
|
||||
String? get connectedSessionId => _connectedSessionId;
|
||||
|
||||
void sendMessage(String content) {
|
||||
if (state is! ChatConnectedData || _channel == null) return;
|
||||
final current = state as ChatConnectedData;
|
||||
@@ -317,6 +371,9 @@ class Chat extends _$Chat {
|
||||
|
||||
case WsMessage.sessionCompleted:
|
||||
_cleanup();
|
||||
// Home CTA must clear immediately — backend just told us the session
|
||||
// is gone, so refresh the shared snapshot.
|
||||
ref.invalidate(activeSessionProvider);
|
||||
break;
|
||||
|
||||
case WsMessage.sessionTopicUpdated:
|
||||
@@ -336,5 +393,6 @@ class Chat extends _$Chat {
|
||||
_channel = null;
|
||||
_typingTimer?.cancel();
|
||||
_typingTimer = null;
|
||||
_connectedSessionId = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ part of 'chat_notifier.dart';
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$chatHash() => r'b704f27f25fb06bbb266f394daf05ca12f518363';
|
||||
String _$chatHash() => r'30e0aa41d2022e5bb080877e23fcb0a0c0c4b927';
|
||||
|
||||
/// See also [Chat].
|
||||
@ProviderFor(Chat)
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'package:dio/dio.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import '../api/api_client_provider.dart';
|
||||
import 'active_session_notifier.dart';
|
||||
|
||||
part 'session_closure_notifier.g.dart';
|
||||
|
||||
@@ -68,10 +69,14 @@ class SessionClosure extends _$SessionClosure {
|
||||
'message': message,
|
||||
});
|
||||
state = const ClosureCompleteData();
|
||||
// The session is now completed server-side; refresh home snapshot so the
|
||||
// CTA returns to "Mulai Curhat" without waiting for the next poll tick.
|
||||
ref.invalidate(activeSessionProvider);
|
||||
} on DioException catch (e) {
|
||||
final code = e.response?.data?['error']?['code'];
|
||||
if (code == 'SESSION_NOT_ACTIVE' || e.response?.statusCode == 409) {
|
||||
state = const ClosureCompleteData();
|
||||
ref.invalidate(activeSessionProvider);
|
||||
} else {
|
||||
state = const ClosureErrorData('Gagal mengirim pesan penutup.');
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ part of 'session_closure_notifier.dart';
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$sessionClosureHash() => r'22a7994290c3a0cc3c692a68063bdc8ffcb2bf87';
|
||||
String _$sessionClosureHash() => r'f238e4098aefdd942314a13eb3fb77ed19cd2b77';
|
||||
|
||||
/// See also [SessionClosure].
|
||||
@ProviderFor(SessionClosure)
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import '../api/api_client_provider.dart';
|
||||
|
||||
part 'unread_notifier.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class UnreadCount extends _$UnreadCount {
|
||||
Timer? _pollTimer;
|
||||
|
||||
@override
|
||||
int build() {
|
||||
_startPolling();
|
||||
ref.onDispose(_stopPolling);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void _startPolling() {
|
||||
_stopPolling();
|
||||
_fetchUnreadCount();
|
||||
_pollTimer = Timer.periodic(const Duration(seconds: 15), (_) {
|
||||
_fetchUnreadCount();
|
||||
});
|
||||
}
|
||||
|
||||
void _stopPolling() {
|
||||
_pollTimer?.cancel();
|
||||
_pollTimer = null;
|
||||
}
|
||||
|
||||
Future<void> _fetchUnreadCount() async {
|
||||
try {
|
||||
final apiClient = ref.read(apiClientProvider);
|
||||
final response = await apiClient.get('/api/client/chat/session/active-with-unread');
|
||||
final data = response['data'];
|
||||
if (data is Map<String, dynamic>) {
|
||||
state = data['unread_count'] as int? ?? 0;
|
||||
} else {
|
||||
state = 0;
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
void markRead() {
|
||||
state = 0;
|
||||
}
|
||||
|
||||
void refresh() => _fetchUnreadCount();
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'unread_notifier.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$unreadCountHash() => r'6a0b31b86ae616177f54346392d9675f916a7bec';
|
||||
|
||||
/// See also [UnreadCount].
|
||||
@ProviderFor(UnreadCount)
|
||||
final unreadCountProvider = NotifierProvider<UnreadCount, int>.internal(
|
||||
UnreadCount.new,
|
||||
name: r'unreadCountProvider',
|
||||
debugGetCreateSourceHash:
|
||||
const bool.fromEnvironment('dart.vm.product') ? null : _$unreadCountHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$UnreadCount = Notifier<int>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package
|
||||
@@ -6,6 +6,7 @@ import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
import '../api/api_client.dart';
|
||||
import '../api/api_client_provider.dart';
|
||||
import '../auth/auth_bridge.dart';
|
||||
import '../chat/active_session_notifier.dart';
|
||||
import '../constants.dart';
|
||||
|
||||
part 'pairing_notifier.g.dart';
|
||||
@@ -148,6 +149,11 @@ class Pairing extends _$Pairing {
|
||||
final sessionId = data['session_id'] as String;
|
||||
state = PairingBestieFoundData(sessionId: sessionId, mitraName: mitraName);
|
||||
|
||||
// A session now exists for this customer — refresh the shared snapshot
|
||||
// so the home CTA reflects it immediately when the user returns.
|
||||
// ignore: unawaited_futures
|
||||
ref.read(activeSessionProvider.notifier).refresh();
|
||||
|
||||
await Future.delayed(const Duration(seconds: 2));
|
||||
state = PairingActiveData(sessionId: sessionId, mitraName: mitraName);
|
||||
} else if (type == SessionStatus.expired) {
|
||||
|
||||
@@ -6,7 +6,7 @@ part of 'pairing_notifier.dart';
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$pairingHash() => r'a283e74d7cb4244bac74a950205c91d4b2cf3e9a';
|
||||
String _$pairingHash() => r'e1c3074239cc4efda99885331ff91b3e0f903c8d';
|
||||
|
||||
/// See also [Pairing].
|
||||
@ProviderFor(Pairing)
|
||||
|
||||
@@ -46,7 +46,10 @@ class _ChatHistoryScreenState extends ConsumerState<ChatHistoryScreen> {
|
||||
itemCount: _sessions.length,
|
||||
itemBuilder: (context, index) {
|
||||
final s = _sessions[index];
|
||||
final sessionId = s['id'] as String;
|
||||
final mitraName = s['mitra_display_name'] as String? ?? 'Bestie';
|
||||
final status = s['status'] as String?;
|
||||
final isClosing = status == 'closing';
|
||||
final endedAt = s['ended_at'] != null
|
||||
? DateTime.parse(s['ended_at'] as String).toLocal()
|
||||
: null;
|
||||
@@ -55,17 +58,51 @@ class _ChatHistoryScreenState extends ConsumerState<ChatHistoryScreen> {
|
||||
|
||||
return ListTile(
|
||||
leading: const CircleAvatar(child: Icon(Icons.person)),
|
||||
title: Text(mitraName),
|
||||
title: Row(
|
||||
children: [
|
||||
Flexible(child: Text(mitraName, overflow: TextOverflow.ellipsis)),
|
||||
if (isClosing) ...[
|
||||
const SizedBox(width: 8),
|
||||
const _OutstandingClosureBadge(),
|
||||
],
|
||||
],
|
||||
),
|
||||
subtitle: Text([
|
||||
if (endedAt != null) '${endedAt.day}/${endedAt.month}/${endedAt.year}',
|
||||
if (duration != null) '$duration menit',
|
||||
if (closureMsg != null) '"$closureMsg"',
|
||||
].join(' - ')),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => context.push('/chat/history/${s['id']}'),
|
||||
onTap: () => isClosing
|
||||
? context.push('/chat/session/$sessionId', extra: mitraName)
|
||||
: context.push('/chat/history/$sessionId'),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _OutstandingClosureBadge extends StatelessWidget {
|
||||
const _OutstandingClosureBadge();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.amber.shade100,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: Colors.amber.shade700, width: 0.5),
|
||||
),
|
||||
child: Text(
|
||||
'Belum ditutup',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
color: Colors.amber.shade900,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../core/chat/active_session_notifier.dart';
|
||||
import '../../../core/chat/chat_notifier.dart';
|
||||
import '../../../core/chat/session_closure_notifier.dart';
|
||||
import '../../../core/constants.dart';
|
||||
@@ -12,6 +13,8 @@ const _kUserBubbleColor = Color(0xFFD4929A);
|
||||
const _kBgTint = Color(0xFFF5D0D6);
|
||||
const _kBannerColor = Color(0xFFC4868F);
|
||||
const _kAccentPink = Color(0xFFBE7C8A);
|
||||
const _kEndedBannerColor = Color(0xFFFFE0B2); // soft amber for early-end notice
|
||||
const _kEndedBannerText = Color(0xFF8B5A00);
|
||||
|
||||
class ChatScreen extends ConsumerStatefulWidget {
|
||||
final String sessionId;
|
||||
@@ -25,27 +28,37 @@ class ChatScreen extends ConsumerStatefulWidget {
|
||||
|
||||
class _ChatScreenState extends ConsumerState<ChatScreen> {
|
||||
final _messageController = TextEditingController();
|
||||
final _goodbyeController = TextEditingController();
|
||||
final _scrollController = ScrollController();
|
||||
Timer? _typingThrottle;
|
||||
bool _showBestieBanner = true;
|
||||
bool _showUserBanner = true;
|
||||
bool _expiredDialogShown = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// The chat WebSocket is owned globally by `App` (see main.dart).
|
||||
// We just ask it to be on this session — no-op if it already is.
|
||||
Future.microtask(() {
|
||||
ref.read(chatProvider.notifier).connect(widget.sessionId);
|
||||
// Reset any closure state left over from a prior session view (the
|
||||
// closure notifier is keepAlive, so e.g. `ClosureCompleteData` from
|
||||
// the last goodbye submission would otherwise leak into this mount
|
||||
// and suppress the goodbye composer for a fresh `closing` session).
|
||||
ref.read(sessionClosureProvider.notifier).reset();
|
||||
ref.read(chatProvider.notifier).connectIfNotConnected(widget.sessionId);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
final notifier = ref.read(chatProvider.notifier);
|
||||
_messageController.dispose();
|
||||
_goodbyeController.dispose();
|
||||
_scrollController.dispose();
|
||||
_typingThrottle?.cancel();
|
||||
super.dispose();
|
||||
Future.microtask(() => notifier.disconnect());
|
||||
// Intentionally do NOT disconnect the WS here. The global lifecycle in
|
||||
// `App` decides when to disconnect (logout / no active session).
|
||||
}
|
||||
|
||||
void _scrollToBottom() {
|
||||
@@ -82,6 +95,38 @@ class _ChatScreenState extends ConsumerState<ChatScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showSessionExpiredDialog() async {
|
||||
if (_expiredDialogShown) return;
|
||||
_expiredDialogShown = true;
|
||||
if (!mounted) return;
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: const Text('Waktu Curhat Berakhir'),
|
||||
content: const Text(
|
||||
'Sesi curhatmu sudah habis waktunya. Kamu bisa menutup obrolan atau memperpanjang waktu untuk lanjut bicara.',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.of(dialogContext).pop();
|
||||
_exitChat();
|
||||
},
|
||||
child: const Text('Tutup'),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
Navigator.of(dialogContext).pop();
|
||||
PricingBottomSheet.showForExtension(context, sessionId: widget.sessionId);
|
||||
},
|
||||
child: const Text('Perpanjang'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final chatState = ref.watch(chatProvider);
|
||||
@@ -90,24 +135,35 @@ class _ChatScreenState extends ConsumerState<ChatScreen> {
|
||||
// Listen for closure complete to navigate home
|
||||
ref.listen(sessionClosureProvider, (prev, next) {
|
||||
if (next is ClosureCompleteData) {
|
||||
// Make doubly sure home picks up the cleared session.
|
||||
ref.invalidate(activeSessionProvider);
|
||||
context.go('/home');
|
||||
}
|
||||
});
|
||||
|
||||
// Listen for chat state changes to manage closure state
|
||||
// Listen for chat state changes to manage closure state and timer-expired modal
|
||||
ref.listen(chatProvider, (prev, next) {
|
||||
if (next is ChatConnectedData) {
|
||||
// Early-end (mitra/customer ended before timer): show goodbye composer.
|
||||
if (next.sessionClosing && !next.sessionExpired) {
|
||||
final closure = ref.read(sessionClosureProvider);
|
||||
if (closure is ClosureInitialData) {
|
||||
ref.read(sessionClosureProvider.notifier).declineExtension();
|
||||
}
|
||||
}
|
||||
// Timer-expired: show non-dismissible modal once on false→true flip.
|
||||
final wasExpired = prev is ChatConnectedData && prev.sessionExpired;
|
||||
if (next.sessionExpired && !wasExpired) {
|
||||
_showSessionExpiredDialog();
|
||||
}
|
||||
if (!next.sessionPaused && !next.sessionExpired && !next.sessionClosing) {
|
||||
final closure = ref.read(sessionClosureProvider);
|
||||
if (closure is! ClosureInitialData) {
|
||||
ref.read(sessionClosureProvider.notifier).reset();
|
||||
}
|
||||
// If we're back to a healthy active state, allow the modal to fire
|
||||
// again on a later expiry (e.g. after extension then re-expiry).
|
||||
_expiredDialogShown = false;
|
||||
}
|
||||
_scrollToBottom();
|
||||
final unread = next.messages
|
||||
@@ -116,6 +172,8 @@ class _ChatScreenState extends ConsumerState<ChatScreen> {
|
||||
.toList();
|
||||
if (unread.isNotEmpty) {
|
||||
ref.read(chatProvider.notifier).markRead(unread);
|
||||
// Optimistically clear the home badge.
|
||||
ref.read(activeSessionProvider.notifier).markRead();
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -171,7 +229,16 @@ class _ChatScreenState extends ConsumerState<ChatScreen> {
|
||||
}
|
||||
|
||||
Widget _buildChatBody(ChatConnectedData state, SessionClosureData closureState) {
|
||||
if (closureState is ClosureShowGoodbyeData || closureState is ClosureSubmittingData) {
|
||||
// Show goodbye composer when closure flow is in goodbye/submitting OR when
|
||||
// we mounted directly into a `closing` session (e.g. opened from history).
|
||||
// The chatProvider listener can't catch this case because it only fires on
|
||||
// transitions, not the current state at mount time.
|
||||
final shouldShowGoodbye = closureState is ClosureShowGoodbyeData ||
|
||||
closureState is ClosureSubmittingData ||
|
||||
(state.sessionClosing &&
|
||||
!state.sessionExpired &&
|
||||
closureState is! ClosureCompleteData);
|
||||
if (shouldShowGoodbye) {
|
||||
return _buildGoodbyeView(closureState);
|
||||
}
|
||||
|
||||
@@ -228,11 +295,8 @@ class _ChatScreenState extends ConsumerState<ChatScreen> {
|
||||
child: Text('Bestie sedang mengetik...', style: TextStyle(color: Colors.grey, fontSize: 12)),
|
||||
),
|
||||
),
|
||||
// Input bar or session ended bar
|
||||
if (state.sessionExpired)
|
||||
_buildSessionEndedBar()
|
||||
else
|
||||
_buildInputBar(),
|
||||
// Input bar — disabled when timer expired (modal handles next step)
|
||||
if (!state.sessionExpired) _buildInputBar(),
|
||||
],
|
||||
),
|
||||
],
|
||||
@@ -352,76 +416,66 @@ class _ChatScreenState extends ConsumerState<ChatScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSessionEndedBar() {
|
||||
return SafeArea(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: _kBgTint,
|
||||
border: Border(top: BorderSide(color: Colors.grey.shade300)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.access_time, color: Colors.red, size: 18),
|
||||
const SizedBox(width: 8),
|
||||
const Expanded(
|
||||
child: Text(
|
||||
'Waktu Curhat Berakhir',
|
||||
style: TextStyle(color: Colors.red, fontWeight: FontWeight.w500),
|
||||
),
|
||||
),
|
||||
GestureDetector(
|
||||
onTap: () => PricingBottomSheet.showForExtension(context, sessionId: widget.sessionId),
|
||||
child: const Text(
|
||||
'Curhat Lagi',
|
||||
style: TextStyle(color: _kAccentPink, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildGoodbyeView(SessionClosureData closureState) {
|
||||
final controller = TextEditingController();
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
children: [
|
||||
const SizedBox(height: 48),
|
||||
// Early-end banner — visually distinct, separate from the closing
|
||||
// composer below. We don't surface "Perpanjang" in this flow.
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: _kEndedBannerColor,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: const Row(
|
||||
children: [
|
||||
Icon(Icons.info_outline, color: _kEndedBannerText, size: 20),
|
||||
SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Sesi telah ditutup oleh Bestie',
|
||||
style: TextStyle(color: _kEndedBannerText, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 32),
|
||||
const Icon(Icons.waving_hand, size: 64, color: Colors.amber),
|
||||
const SizedBox(height: 16),
|
||||
const Text('Pesan Penutup', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 8),
|
||||
const Text('Tuliskan pesan terakhirmu untuk Bestie', textAlign: TextAlign.center),
|
||||
const SizedBox(height: 24),
|
||||
TextField(
|
||||
controller: controller,
|
||||
maxLines: 3,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Terima kasih, Bestie...',
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
const Text('Pesan Penutup', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 8),
|
||||
const Text('Tuliskan pesan terakhirmu untuk Bestie', textAlign: TextAlign.center),
|
||||
const SizedBox(height: 24),
|
||||
TextField(
|
||||
controller: _goodbyeController,
|
||||
maxLines: 3,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Terima kasih, Bestie...',
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: closureState is ClosureSubmittingData
|
||||
? null
|
||||
: () {
|
||||
final text = controller.text.trim();
|
||||
if (text.isNotEmpty) {
|
||||
ref.read(sessionClosureProvider.notifier).submitGoodbye(
|
||||
widget.sessionId, text,
|
||||
);
|
||||
}
|
||||
},
|
||||
child: closureState is ClosureSubmittingData
|
||||
? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Text('Kirim & Selesai'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: closureState is ClosureSubmittingData
|
||||
? null
|
||||
: () {
|
||||
final text = _goodbyeController.text.trim();
|
||||
if (text.isNotEmpty) {
|
||||
ref.read(sessionClosureProvider.notifier).submitGoodbye(
|
||||
widget.sessionId, text,
|
||||
);
|
||||
}
|
||||
},
|
||||
child: closureState is ClosureSubmittingData
|
||||
? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Text('Kirim & Selesai'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../core/api/api_client_provider.dart';
|
||||
|
||||
class SessionActiveScreen extends ConsumerWidget {
|
||||
final String sessionId;
|
||||
final String mitraName;
|
||||
|
||||
const SessionActiveScreen({
|
||||
super.key,
|
||||
required this.sessionId,
|
||||
required this.mitraName,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Sesi Aktif'),
|
||||
automaticallyImplyLeading: false,
|
||||
),
|
||||
body: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(Icons.chat_bubble, size: 80, color: Colors.blue),
|
||||
const SizedBox(height: 24),
|
||||
Text(
|
||||
'Terhubung dengan $mitraName',
|
||||
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const Text(
|
||||
'Sesi chat akan tersedia di fase berikutnya.',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey),
|
||||
),
|
||||
const SizedBox(height: 48),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
|
||||
onPressed: () => _endSession(context, ref),
|
||||
child: const Text('Akhiri Sesi', style: TextStyle(color: Colors.white)),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _endSession(BuildContext context, WidgetRef ref) async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('Akhiri Sesi?'),
|
||||
content: const Text('Apakah kamu yakin ingin mengakhiri sesi ini?'),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: const Text('Batal')),
|
||||
TextButton(onPressed: () => Navigator.of(ctx).pop(true), child: const Text('Ya, Akhiri')),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmed == true && context.mounted) {
|
||||
try {
|
||||
final apiClient = ref.read(apiClientProvider);
|
||||
await apiClient.post('/api/client/chat/session/$sessionId/end');
|
||||
if (context.mounted) context.go('/home');
|
||||
} catch (_) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Gagal mengakhiri sesi. Coba lagi.')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../core/auth/auth_notifier.dart';
|
||||
import '../../core/api/api_client_provider.dart';
|
||||
import '../../core/chat/unread_notifier.dart';
|
||||
import '../../core/chat/active_session_notifier.dart';
|
||||
import '../../core/pairing/pairing_notifier.dart';
|
||||
import '../chat/widgets/pricing_bottom_sheet.dart';
|
||||
import '../chat/widgets/topic_selection_bottom_sheet.dart';
|
||||
@@ -16,14 +15,10 @@ class HomeScreen extends ConsumerStatefulWidget {
|
||||
}
|
||||
|
||||
class _HomeScreenState extends ConsumerState<HomeScreen> with WidgetsBindingObserver {
|
||||
Map<String, dynamic>? _activeSession;
|
||||
bool _loadingSession = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_checkActiveSession();
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -35,29 +30,8 @@ class _HomeScreenState extends ConsumerState<HomeScreen> with WidgetsBindingObse
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.resumed) {
|
||||
_checkActiveSession();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
_checkActiveSession();
|
||||
}
|
||||
|
||||
Future<void> _checkActiveSession() async {
|
||||
try {
|
||||
final apiClient = ref.read(apiClientProvider);
|
||||
final response = await apiClient.get('/api/client/chat/session/active');
|
||||
final data = response['data'];
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_activeSession = data is Map<String, dynamic> ? data : null;
|
||||
_loadingSession = false;
|
||||
});
|
||||
}
|
||||
} catch (_) {
|
||||
if (mounted) setState(() => _loadingSession = false);
|
||||
// Re-fetch in case a session ended/started while backgrounded.
|
||||
ref.read(activeSessionProvider.notifier).refresh();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,6 +45,7 @@ class _HomeScreenState extends ConsumerState<HomeScreen> with WidgetsBindingObse
|
||||
Widget build(BuildContext context) {
|
||||
final authState = ref.watch(authProvider);
|
||||
final authData = authState.valueOrNull;
|
||||
final activeSessionAsync = ref.watch(activeSessionProvider);
|
||||
|
||||
final displayName = switch (authData) {
|
||||
AuthAuthenticatedData d => d.profile['display_name'] as String? ?? '',
|
||||
@@ -112,27 +87,31 @@ class _HomeScreenState extends ConsumerState<HomeScreen> with WidgetsBindingObse
|
||||
children: [
|
||||
Text('Halo, $displayName!', style: const TextStyle(fontSize: 24)),
|
||||
const SizedBox(height: 32),
|
||||
if (_loadingSession)
|
||||
const CircularProgressIndicator()
|
||||
else if (_activeSession != null)
|
||||
_ActiveSessionCard(
|
||||
session: _activeSession!,
|
||||
onTap: () {
|
||||
final sessionId = _activeSession!['id'] as String;
|
||||
final mitraName = _activeSession!['mitra_display_name'] as String? ?? 'Bestie';
|
||||
context.push('/chat/session/$sessionId', extra: mitraName);
|
||||
},
|
||||
)
|
||||
else ...[
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 16),
|
||||
),
|
||||
onPressed: () => _onStartChatPressed(context),
|
||||
child: const Text('Mulai Curhat', style: TextStyle(fontSize: 18)),
|
||||
),
|
||||
],
|
||||
activeSessionAsync.when(
|
||||
loading: () => const CircularProgressIndicator(),
|
||||
error: (_, __) => _StartChatButton(onPressed: () => _onStartChatPressed(context)),
|
||||
data: (snapshot) {
|
||||
// Hide the "Sesi Aktif" CTA when the session is in `closing`
|
||||
// — the conversation is over, only the goodbye composer
|
||||
// remains. Backend auto-completes such sessions after a
|
||||
// grace period; until then the user shouldn't be invited
|
||||
// back into them from home.
|
||||
final status = snapshot.session?['status'] as String?;
|
||||
final isCurhatable = snapshot.hasSession && status != 'closing';
|
||||
if (isCurhatable) {
|
||||
return _ActiveSessionCard(
|
||||
mitraName: snapshot.mitraName,
|
||||
unreadCount: snapshot.unreadCount,
|
||||
onTap: () {
|
||||
final sessionId = snapshot.sessionId;
|
||||
if (sessionId == null) return;
|
||||
context.push('/chat/session/$sessionId', extra: snapshot.mitraName);
|
||||
},
|
||||
);
|
||||
}
|
||||
return _StartChatButton(onPressed: () => _onStartChatPressed(context));
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -141,17 +120,40 @@ class _HomeScreenState extends ConsumerState<HomeScreen> with WidgetsBindingObse
|
||||
}
|
||||
}
|
||||
|
||||
class _ActiveSessionCard extends ConsumerWidget {
|
||||
final Map<String, dynamic> session;
|
||||
final VoidCallback onTap;
|
||||
|
||||
const _ActiveSessionCard({required this.session, required this.onTap});
|
||||
class _StartChatButton extends StatelessWidget {
|
||||
final VoidCallback onPressed;
|
||||
const _StartChatButton({required this.onPressed});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final mitraName = session['mitra_display_name'] as String? ?? 'Bestie';
|
||||
final unreadCount = ref.watch(unreadCountProvider);
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
children: [
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 16),
|
||||
),
|
||||
onPressed: onPressed,
|
||||
child: const Text('Mulai Curhat', style: TextStyle(fontSize: 18)),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ActiveSessionCard extends StatelessWidget {
|
||||
final String mitraName;
|
||||
final int unreadCount;
|
||||
final VoidCallback onTap;
|
||||
|
||||
const _ActiveSessionCard({
|
||||
required this.mitraName,
|
||||
required this.unreadCount,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
elevation: 2,
|
||||
child: InkWell(
|
||||
|
||||
@@ -4,6 +4,8 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'core/api/api_client_provider.dart';
|
||||
import 'core/auth/auth_notifier.dart';
|
||||
import 'core/chat/active_session_notifier.dart';
|
||||
import 'core/chat/chat_notifier.dart';
|
||||
import 'core/notifications/notification_service.dart';
|
||||
import 'firebase_options.dart';
|
||||
import 'router.dart';
|
||||
@@ -45,10 +47,33 @@ class _AppState extends ConsumerState<App> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// FCM registration on auth.
|
||||
ref.listen(authProvider, (prev, next) {
|
||||
final data = next.valueOrNull;
|
||||
if (data is AuthAuthenticatedData || data is AuthAnonymousData) {
|
||||
_registerFcmToken();
|
||||
} else {
|
||||
// Logged out (or initial) — ensure the chat WS is closed.
|
||||
ref.read(chatProvider.notifier).disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
// Global chat WebSocket lifecycle: connect whenever the user has an
|
||||
// active session, regardless of which screen is mounted. The chat screen
|
||||
// only joins this connection — it doesn't own it. FCM remains the
|
||||
// background-only fallback.
|
||||
ref.listen(activeSessionProvider, (prev, next) {
|
||||
final snapshot = next.valueOrNull;
|
||||
final notifier = ref.read(chatProvider.notifier);
|
||||
if (snapshot == null || !snapshot.hasSession) {
|
||||
if (notifier.connectedSessionId != null) {
|
||||
notifier.disconnect();
|
||||
}
|
||||
return;
|
||||
}
|
||||
final sessionId = snapshot.sessionId;
|
||||
if (sessionId != null && notifier.connectedSessionId != sessionId) {
|
||||
notifier.connectIfNotConnected(sessionId);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user