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:
@@ -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.')),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user