Files
halobestie-clone/mitra_app/lib/features/chat/screens/mitra_chat_screen.dart
ramadhan sjamsani b4efcf14c2 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>
2026-04-07 23:58:11 +08:00

338 lines
12 KiB
Dart

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/mitra_chat_bloc.dart';
import '../../../core/chat/extension_bloc.dart';
class MitraChatScreen extends StatefulWidget {
final String sessionId;
final String customerName;
const MitraChatScreen({super.key, required this.sessionId, required this.customerName});
@override
State<MitraChatScreen> createState() => _MitraChatScreenState();
}
class _MitraChatScreenState extends State<MitraChatScreen> {
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<MitraChatBloc>().add(SendTyping());
_typingThrottle = Timer(const Duration(seconds: 2), () {});
}
void _sendMessage() {
final text = _messageController.text.trim();
if (text.isEmpty) return;
context.read<MitraChatBloc>().add(SendMessage(text));
_messageController.clear();
_scrollToBottom();
}
@override
Widget build(BuildContext context) {
return MultiBlocListener(
listeners: [
BlocListener<MitraChatBloc, MitraChatState>(
listener: (context, state) {
if (state is ChatConnected) {
_scrollToBottom();
final unread = state.messages
.where((m) => m.senderType == 'customer' && m.status != 'read')
.map((m) => m.id)
.toList();
if (unread.isNotEmpty) {
context.read<MitraChatBloc>().add(MarkMessagesRead(unread));
}
if (state.sessionClosing) {
// Trigger goodbye view
}
}
},
),
BlocListener<ExtensionBloc, ExtensionState>(
listener: (context, state) {
if (state is ExtensionComplete) {
context.go('/home');
}
},
),
],
child: Scaffold(
appBar: AppBar(
title: Text(widget.customerName),
actions: [
BlocBuilder<MitraChatBloc, MitraChatState>(
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<MitraChatBloc, MitraChatState>(
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) {
// Extension request from customer
if (state.extensionRequest != null) {
return _buildExtensionView(context, state.extensionRequest!);
}
// Goodbye view
final extState = context.watch<ExtensionBloc>().state;
if (state.sessionClosing || extState is ExtensionShowGoodbye || extState is ExtensionSubmitting) {
return _buildGoodbyeView(context, extState);
}
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 == 'mitra';
return _buildMessageBubble(msg, isMe);
},
),
),
if (state.isOtherTyping)
const Padding(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Align(
alignment: Alignment.centerLeft,
child: Text('Customer sedang mengetik...', style: TextStyle(color: Colors.grey, fontSize: 12)),
),
),
_buildInputBar(),
],
);
}
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.green.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() {
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.green),
onPressed: _sendMessage,
),
],
),
),
);
}
Widget _buildExtensionView(BuildContext context, Map<String, dynamic> request) {
final duration = request['duration_minutes'] as int?;
final extensionId = request['extension_id'] as String?;
return Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.timer, size: 64, color: Colors.orange),
const SizedBox(height: 16),
const Text('Permintaan Perpanjangan', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
const SizedBox(height: 8),
Text('Customer ingin perpanjang $duration menit', textAlign: TextAlign.center),
const SizedBox(height: 24),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.green),
onPressed: () => context.read<ExtensionBloc>().add(RespondToExtension(
sessionId: widget.sessionId,
extensionId: extensionId!,
accepted: true,
)),
child: const Text('Terima', style: TextStyle(color: Colors.white)),
),
const SizedBox(width: 16),
ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
onPressed: () => context.read<ExtensionBloc>().add(RespondToExtension(
sessionId: widget.sessionId,
extensionId: extensionId!,
accepted: false,
)),
child: const Text('Tolak', style: TextStyle(color: Colors.white)),
),
],
),
],
),
),
);
}
Widget _buildGoodbyeView(BuildContext context, ExtensionState extState) {
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 Customer', textAlign: TextAlign.center),
const SizedBox(height: 24),
TextField(
controller: controller,
maxLines: 3,
decoration: InputDecoration(
hintText: 'Terima kasih sudah curhat...',
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: extState is ExtensionSubmitting
? null
: () {
final text = controller.text.trim();
if (text.isNotEmpty) {
context.read<ExtensionBloc>().add(
SubmitGoodbye(sessionId: widget.sessionId, message: text),
);
}
},
child: extState is ExtensionSubmitting
? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2))
: const Text('Kirim & Selesai'),
),
],
),
),
);
}
}