Phase 3 scaffold: chat engine (WebSocket, FCM, pricing, timer, extension, history)

- Backend: WebSocket plugin, chat/pricing/timer/extension/closure/notification services
- Client app: ChatBloc, pricing dialog, chat screen with message status, extension/goodbye flow, history
- Mitra app: MitraChatBloc, ExtensionBloc, chat screen, extension accept/reject, history
- Control center: free trial, extension timeout, early end config toggles
- DB migration: chat_messages, session_closures, session_extensions, customer_transactions tables

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-07 23:58:11 +08:00
parent 844d7234e6
commit b4efcf14c2
47 changed files with 4361 additions and 44 deletions

View File

@@ -0,0 +1,71 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../../core/api/api_client.dart';
class ChatHistoryScreen extends StatefulWidget {
const ChatHistoryScreen({super.key});
@override
State<ChatHistoryScreen> createState() => _ChatHistoryScreenState();
}
class _ChatHistoryScreenState extends State<ChatHistoryScreen> {
List<Map<String, dynamic>> _sessions = [];
bool _loading = true;
@override
void initState() {
super.initState();
_loadHistory();
}
Future<void> _loadHistory() async {
try {
final api = context.read<ApiClient>();
final response = await api.get('/api/client/chat/history');
final items = (response['data']['items'] as List<dynamic>).cast<Map<String, dynamic>>();
setState(() {
_sessions = items;
_loading = false;
});
} catch (_) {
setState(() => _loading = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Riwayat Chat')),
body: _loading
? const Center(child: CircularProgressIndicator())
: _sessions.isEmpty
? const Center(child: Text('Belum ada riwayat chat'))
: ListView.builder(
itemCount: _sessions.length,
itemBuilder: (context, index) {
final s = _sessions[index];
final mitraName = s['mitra_display_name'] as String? ?? 'Bestie';
final endedAt = s['ended_at'] != null
? DateTime.parse(s['ended_at'] as String).toLocal()
: null;
final duration = s['duration_minutes'] as int?;
final closureMsg = s['customer_closure_message'] as String?;
return ListTile(
leading: const CircleAvatar(child: Icon(Icons.person)),
title: Text(mitraName),
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']}'),
);
},
),
);
}
}

View File

@@ -0,0 +1,352 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../../core/chat/chat_bloc.dart';
import '../../../core/chat/session_closure_bloc.dart';
import '../widgets/pricing_bottom_sheet.dart';
class ChatScreen extends StatefulWidget {
final String sessionId;
final String mitraName;
const ChatScreen({super.key, required this.sessionId, required this.mitraName});
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final _messageController = TextEditingController();
final _scrollController = ScrollController();
Timer? _typingThrottle;
@override
void dispose() {
_messageController.dispose();
_scrollController.dispose();
_typingThrottle?.cancel();
super.dispose();
}
void _scrollToBottom() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollController.hasClients) {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
);
}
});
}
void _onTextChanged(String text) {
if (_typingThrottle?.isActive ?? false) return;
context.read<ChatBloc>().add(SendTyping());
_typingThrottle = Timer(const Duration(seconds: 2), () {});
}
void _sendMessage() {
final text = _messageController.text.trim();
if (text.isEmpty) return;
context.read<ChatBloc>().add(SendMessage(text));
_messageController.clear();
_scrollToBottom();
}
@override
Widget build(BuildContext context) {
return MultiBlocListener(
listeners: [
BlocListener<ChatBloc, ChatState>(
listenWhen: (prev, curr) {
if (prev is ChatConnected && curr is ChatConnected) {
return prev.sessionExpired != curr.sessionExpired ||
prev.sessionClosing != curr.sessionClosing ||
prev.messages.length != curr.messages.length;
}
return true;
},
listener: (context, state) {
if (state is ChatConnected) {
if (state.sessionClosing) {
context.read<SessionClosureBloc>().add(DeclineExtension());
}
_scrollToBottom();
// Auto-mark received messages as read
final unread = state.messages
.where((m) => m.senderType == 'mitra' && m.status != 'read')
.map((m) => m.id)
.toList();
if (unread.isNotEmpty) {
context.read<ChatBloc>().add(MarkMessagesRead(unread));
}
}
},
),
BlocListener<SessionClosureBloc, SessionClosureState>(
listener: (context, state) {
if (state is ClosureComplete) {
context.go('/home');
}
},
),
],
child: Scaffold(
appBar: AppBar(
title: Text(widget.mitraName),
automaticallyImplyLeading: false,
actions: [
BlocBuilder<ChatBloc, ChatState>(
builder: (context, state) {
if (state is ChatConnected && state.remainingSeconds != null) {
return Padding(
padding: const EdgeInsets.only(right: 16),
child: Center(
child: Text(
'${state.remainingSeconds}s',
style: TextStyle(
color: state.remainingSeconds! < 30 ? Colors.red : null,
fontWeight: FontWeight.bold,
),
),
),
);
}
return const SizedBox.shrink();
},
),
],
),
body: BlocBuilder<ChatBloc, ChatState>(
builder: (context, state) {
if (state is ChatConnecting) {
return const Center(child: CircularProgressIndicator());
}
if (state is ChatError) {
return Center(child: Text(state.message));
}
if (state is ChatConnected) {
return _buildChatBody(context, state);
}
return const SizedBox.shrink();
},
),
),
);
}
Widget _buildChatBody(BuildContext context, ChatConnected state) {
// Show session expired dialog
if (state.sessionExpired) {
return _buildExpiredView(context);
}
// Show goodbye input
final closureState = context.watch<SessionClosureBloc>().state;
if (closureState is ClosureShowGoodbye || closureState is ClosureSubmitting) {
return _buildGoodbyeView(context, closureState);
}
if (state.sessionPaused) {
return _buildPausedView();
}
return Column(
children: [
Expanded(
child: ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.all(16),
itemCount: state.messages.length,
itemBuilder: (context, index) {
final msg = state.messages[index];
final isMe = msg.senderType == 'customer';
return _buildMessageBubble(msg, isMe);
},
),
),
if (state.isOtherTyping)
const Padding(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Align(
alignment: Alignment.centerLeft,
child: Text('Bestie sedang mengetik...', style: TextStyle(color: Colors.grey, fontSize: 12)),
),
),
_buildInputBar(context, state),
],
);
}
Widget _buildMessageBubble(ChatMessage msg, bool isMe) {
return Align(
alignment: isMe ? Alignment.centerRight : Alignment.centerLeft,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4),
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.75),
decoration: BoxDecoration(
color: isMe ? Colors.blue.shade100 : Colors.grey.shade200,
borderRadius: BorderRadius.circular(16),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(msg.content, style: const TextStyle(fontSize: 15)),
const SizedBox(height: 4),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'${msg.createdAt.hour.toString().padLeft(2, '0')}:${msg.createdAt.minute.toString().padLeft(2, '0')}',
style: const TextStyle(fontSize: 10, color: Colors.grey),
),
if (isMe) ...[
const SizedBox(width: 4),
_buildStatusIcon(msg.status),
],
],
),
],
),
),
);
}
Widget _buildStatusIcon(String status) {
switch (status) {
case 'sending':
return const Icon(Icons.access_time, size: 14, color: Colors.grey);
case 'sent':
return const Icon(Icons.check, size: 14, color: Colors.grey);
case 'delivered':
return const Icon(Icons.done_all, size: 14, color: Colors.grey);
case 'read':
return const Icon(Icons.done_all, size: 14, color: Colors.blue);
default:
return const SizedBox.shrink();
}
}
Widget _buildInputBar(BuildContext context, ChatConnected state) {
return SafeArea(
child: Padding(
padding: const EdgeInsets.all(8),
child: Row(
children: [
Expanded(
child: TextField(
controller: _messageController,
onChanged: _onTextChanged,
textInputAction: TextInputAction.send,
onSubmitted: (_) => _sendMessage(),
decoration: InputDecoration(
hintText: 'Ketik pesan...',
border: OutlineInputBorder(borderRadius: BorderRadius.circular(24)),
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
),
),
),
const SizedBox(width: 8),
IconButton(
icon: const Icon(Icons.send, color: Colors.blue),
onPressed: _sendMessage,
),
],
),
),
);
}
Widget _buildExpiredView(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.timer_off, size: 64, color: Colors.orange),
const SizedBox(height: 16),
const Text('Waktu sesi habis', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
const SizedBox(height: 8),
const Text('Apakah kamu ingin memperpanjang sesi?', textAlign: TextAlign.center),
const SizedBox(height: 24),
ElevatedButton(
onPressed: () => PricingBottomSheet.show(context),
child: const Text('Perpanjang Sesi'),
),
const SizedBox(height: 12),
TextButton(
onPressed: () => context.read<SessionClosureBloc>().add(DeclineExtension()),
child: const Text('Tidak, akhiri sesi'),
),
],
),
),
);
}
Widget _buildGoodbyeView(BuildContext context, SessionClosureState closureState) {
final controller = TextEditingController();
return Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
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),
ElevatedButton(
onPressed: closureState is ClosureSubmitting
? null
: () {
final text = controller.text.trim();
if (text.isNotEmpty) {
context.read<SessionClosureBloc>().add(
SubmitGoodbye(sessionId: widget.sessionId, message: text),
);
}
},
child: closureState is ClosureSubmitting
? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2))
: const Text('Kirim & Selesai'),
),
],
),
),
);
}
Widget _buildPausedView() {
return const Center(
child: Padding(
padding: EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
SizedBox(height: 24),
Text('Menunggu konfirmasi Bestie...', style: TextStyle(fontSize: 18)),
SizedBox(height: 8),
Text('Chat dijeda sementara', style: TextStyle(color: Colors.grey)),
],
),
),
);
}
}

View File

@@ -0,0 +1,91 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/api/api_client.dart';
class ChatTranscriptScreen extends StatefulWidget {
final String sessionId;
const ChatTranscriptScreen({super.key, required this.sessionId});
@override
State<ChatTranscriptScreen> createState() => _ChatTranscriptScreenState();
}
class _ChatTranscriptScreenState extends State<ChatTranscriptScreen> {
List<Map<String, dynamic>> _messages = [];
List<Map<String, dynamic>> _closures = [];
bool _loading = true;
@override
void initState() {
super.initState();
_loadTranscript();
}
Future<void> _loadTranscript() async {
try {
final api = context.read<ApiClient>();
final response = await api.get('/api/shared/chat/${widget.sessionId}/transcript');
final data = response['data'] as Map<String, dynamic>;
setState(() {
_messages = (data['messages'] as List<dynamic>).cast<Map<String, dynamic>>();
_closures = (data['closures'] as List<dynamic>).cast<Map<String, dynamic>>();
_loading = false;
});
} catch (_) {
setState(() => _loading = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Transkrip Chat')),
body: _loading
? const Center(child: CircularProgressIndicator())
: ListView(
padding: const EdgeInsets.all(16),
children: [
..._messages.map((m) {
final isMe = m['sender_type'] == 'customer';
final time = DateTime.parse(m['created_at'] as String).toLocal();
return Align(
alignment: isMe ? Alignment.centerRight : Alignment.centerLeft,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 4),
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.75),
decoration: BoxDecoration(
color: isMe ? Colors.blue.shade100 : Colors.grey.shade200,
borderRadius: BorderRadius.circular(16),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(m['content'] as String, style: const TextStyle(fontSize: 15)),
const SizedBox(height: 4),
Text(
'${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}',
style: const TextStyle(fontSize: 10, color: Colors.grey),
),
],
),
),
);
}),
if (_closures.isNotEmpty) ...[
const Divider(height: 32),
const Text('Pesan Penutup', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
const SizedBox(height: 8),
..._closures.map((c) => Card(
child: ListTile(
title: Text(c['user_type'] == 'customer' ? 'Kamu' : 'Bestie'),
subtitle: Text(c['message'] as String),
),
)),
],
],
),
);
}
}

View File

@@ -0,0 +1,119 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../core/api/api_client.dart';
import '../../../core/chat/chat_opening_bloc.dart';
import '../../../core/pairing/pairing_bloc.dart';
class PricingBottomSheet extends StatelessWidget {
const PricingBottomSheet({super.key});
static Future<void> show(BuildContext context) {
return showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (_) => BlocProvider(
create: (ctx) => ChatOpeningBloc(apiClient: ctx.read<ApiClient>())..add(LoadPricing()),
child: const PricingBottomSheet(),
),
);
}
String _formatPrice(int price) {
final str = price.toString();
final buffer = StringBuffer();
for (var i = 0; i < str.length; i++) {
if (i > 0 && (str.length - i) % 3 == 0) buffer.write('.');
buffer.write(str[i]);
}
return 'Rp $buffer';
}
@override
Widget build(BuildContext context) {
return BlocBuilder<ChatOpeningBloc, ChatOpeningState>(
builder: (context, state) {
if (state is PricingLoading || state is PricingInitial) {
return const SizedBox(
height: 200,
child: Center(child: CircularProgressIndicator()),
);
}
if (state is PricingError) {
return SizedBox(
height: 200,
child: Center(child: Text(state.message)),
);
}
if (state is PricingLoaded) {
return DraggableScrollableSheet(
initialChildSize: 0.6,
minChildSize: 0.4,
maxChildSize: 0.8,
expand: false,
builder: (_, scrollController) {
return Padding(
padding: const EdgeInsets.all(24),
child: ListView(
controller: scrollController,
children: [
const Text(
'Pilih Durasi Curhat',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
if (state.freeTrialEligible) ...[
Card(
color: Colors.green.shade50,
child: ListTile(
leading: const Icon(Icons.card_giftcard, color: Colors.green),
title: Text('Free Trial (${state.freeTrialDurationMinutes} Menit)'),
subtitle: const Text('Gratis untuk pertama kali!'),
trailing: const Icon(Icons.arrow_forward_ios, size: 16),
onTap: () {
Navigator.of(context).pop();
_startPairing(context, isFreeTrial: true);
},
),
),
const Divider(height: 24),
],
...state.tiers.map((tier) => Card(
child: ListTile(
title: Text(tier.label),
trailing: Text(
_formatPrice(tier.price),
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
),
onTap: () {
Navigator.of(context).pop();
_startPairing(
context,
durationMinutes: tier.durationMinutes,
price: tier.price,
);
},
),
)),
],
),
);
},
);
}
return const SizedBox.shrink();
},
);
}
void _startPairing(BuildContext context, {bool isFreeTrial = false, int? durationMinutes, int? price}) {
context.read<PairingBloc>().add(RequestPairingWithTier(
durationMinutes: durationMinutes,
price: price,
isFreeTrial: isFreeTrial,
));
}
}