chat support
This commit is contained in:
@@ -1,3 +1,3 @@
|
||||
class ApiConfig {
|
||||
static const String baseUrl = "http://192.168.0.100:8000/api";
|
||||
static const String baseUrl = "http://10.11.236.74:8000/api";
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ class AppConfig {
|
||||
static const String logoUrlEmulator = "http://10.0.2.2:8000/images/kent_logo2.png";
|
||||
|
||||
// For Physical Device (Replace with your actual PC local IP)
|
||||
static const String logoUrlDevice = "http://10.207.50.74:8000/images/kent_logo2.png";
|
||||
static const String logoUrlDevice = "http://10.11.236.74:8000/images/kent_logo2.png";
|
||||
|
||||
// Which one to use?
|
||||
static const String logoUrl = logoUrlDevice; // CHANGE THIS WHEN TESTING ON REAL DEVICE
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:kent_logistics_app/providers/chat_unread_provider.dart';
|
||||
import 'package:kent_logistics_app/providers/dashboard_provider.dart';
|
||||
import 'package:kent_logistics_app/providers/invoice_provider.dart';
|
||||
import 'package:kent_logistics_app/providers/mark_list_provider.dart';
|
||||
@@ -30,6 +31,7 @@ void main() async {
|
||||
|
||||
),
|
||||
ChangeNotifierProvider(create: (_) => InvoiceProvider()),
|
||||
ChangeNotifierProvider(create: (_) => ChatUnreadProvider()),
|
||||
],
|
||||
child: const KentApp(),
|
||||
));
|
||||
@@ -54,7 +56,7 @@ class KentApp extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
ChangeNotifierProvider(create: (_) => InvoiceProvider()),
|
||||
|
||||
ChangeNotifierProvider(create: (_) => ChatUnreadProvider()),
|
||||
|
||||
],
|
||||
child: MaterialApp(
|
||||
|
||||
34
lib/providers/chat_unread_provider.dart
Normal file
34
lib/providers/chat_unread_provider.dart
Normal file
@@ -0,0 +1,34 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ChatUnreadProvider extends ChangeNotifier {
|
||||
int _unreadCount = 0;
|
||||
bool _chatOpen = false;
|
||||
|
||||
int get unreadCount => _unreadCount;
|
||||
bool get isChatOpen => _chatOpen;
|
||||
|
||||
/// 📩 Called when ADMIN sends message
|
||||
void increment() {
|
||||
if (!_chatOpen) {
|
||||
_unreadCount++;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// 👁 Called when chat screen is opened
|
||||
void setChatOpen(bool open) {
|
||||
_chatOpen = open;
|
||||
|
||||
if (open) {
|
||||
_unreadCount = 0; // reset badge when user opens chat
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 🔁 Manual reset (optional)
|
||||
void reset() {
|
||||
_unreadCount = 0;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,188 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
class ChatScreen extends StatelessWidget {
|
||||
import '../services/chat_service.dart';
|
||||
import '../services/reverb_socket_service.dart';
|
||||
import '../services/dio_client.dart';
|
||||
import '../providers/chat_unread_provider.dart';
|
||||
|
||||
class ChatScreen extends StatefulWidget {
|
||||
const ChatScreen({super.key});
|
||||
|
||||
@override
|
||||
State<ChatScreen> createState() => _ChatScreenState();
|
||||
}
|
||||
|
||||
class _ChatScreenState extends State<ChatScreen> {
|
||||
final TextEditingController _messageCtrl = TextEditingController();
|
||||
final ScrollController _scrollCtrl = ScrollController();
|
||||
|
||||
late ChatService _chatService;
|
||||
final ReverbSocketService _socket = ReverbSocketService();
|
||||
|
||||
int? ticketId;
|
||||
List<Map<String, dynamic>> messages = [];
|
||||
bool isLoading = true;
|
||||
|
||||
// ============================
|
||||
// INIT STATE
|
||||
// ============================
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
_chatService = ChatService(DioClient.getInstance(context));
|
||||
|
||||
// 🔔 Mark chat as OPEN (important)
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
context.read<ChatUnreadProvider>().setChatOpen(true);
|
||||
});
|
||||
|
||||
_initChat();
|
||||
}
|
||||
|
||||
// ============================
|
||||
// INIT CHAT
|
||||
// ============================
|
||||
Future<void> _initChat() async {
|
||||
// 1️⃣ Start chat
|
||||
final ticketRes = await _chatService.startChat();
|
||||
ticketId = ticketRes['ticket']['id'];
|
||||
|
||||
// 2️⃣ Load messages
|
||||
final msgs = await _chatService.getMessages(ticketId!);
|
||||
messages = List<Map<String, dynamic>>.from(msgs);
|
||||
|
||||
// 3️⃣ Realtime socket
|
||||
await _socket.connect(
|
||||
context: context,
|
||||
ticketId: ticketId!,
|
||||
onMessage: (msg) {
|
||||
if (!mounted) return;
|
||||
setState(() => messages.add(msg));
|
||||
_scrollToBottom();
|
||||
},
|
||||
onAdminMessage: () {
|
||||
if (!mounted) {
|
||||
context.read<ChatUnreadProvider>().increment();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
|
||||
|
||||
if (!mounted) return;
|
||||
setState(() => isLoading = false);
|
||||
_scrollToBottom();
|
||||
}
|
||||
|
||||
// ============================
|
||||
// SCROLL
|
||||
// ============================
|
||||
void _scrollToBottom() {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (_scrollCtrl.hasClients) {
|
||||
_scrollCtrl.jumpTo(_scrollCtrl.position.maxScrollExtent);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ============================
|
||||
// SEND MESSAGE
|
||||
// ============================
|
||||
Future<void> _sendMessage() async {
|
||||
final text = _messageCtrl.text.trim();
|
||||
if (text.isEmpty) return;
|
||||
|
||||
_messageCtrl.clear();
|
||||
|
||||
await _chatService.sendMessage(
|
||||
ticketId!,
|
||||
message: text,
|
||||
);
|
||||
}
|
||||
|
||||
// ============================
|
||||
// DISPOSE
|
||||
// ============================
|
||||
@override
|
||||
void dispose() {
|
||||
// 🔕 Mark chat CLOSED
|
||||
context.read<ChatUnreadProvider>().setChatOpen(false);
|
||||
|
||||
_socket.disconnect();
|
||||
_messageCtrl.dispose();
|
||||
_scrollCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// ============================
|
||||
// UI
|
||||
// ============================
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return const Center(
|
||||
child: Text("Invoice Content He", style: TextStyle(fontSize: 18)),
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text("Support Chat")),
|
||||
body: isLoading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: Column(
|
||||
children: [
|
||||
Expanded(child: _buildMessages()),
|
||||
_buildInput(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMessages() {
|
||||
return ListView.builder(
|
||||
controller: _scrollCtrl,
|
||||
padding: const EdgeInsets.all(12),
|
||||
itemCount: messages.length,
|
||||
itemBuilder: (_, index) {
|
||||
final msg = messages[index];
|
||||
final isUser = msg['sender_type'] == 'App\\Models\\User';
|
||||
|
||||
return Align(
|
||||
alignment:
|
||||
isUser ? Alignment.centerRight : Alignment.centerLeft,
|
||||
child: Container(
|
||||
margin: const EdgeInsets.symmetric(vertical: 4),
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: isUser ? Colors.blue : Colors.grey.shade300,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Text(
|
||||
msg['message'] ?? '',
|
||||
style: TextStyle(
|
||||
color: isUser ? Colors.white : Colors.black,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildInput() {
|
||||
return SafeArea(
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _messageCtrl,
|
||||
decoration:
|
||||
const InputDecoration(hintText: "Type message"),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.send),
|
||||
onPressed: _sendMessage,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@ import 'order_screen.dart';
|
||||
import 'invoice_screen.dart';
|
||||
import 'chat_screen.dart';
|
||||
import 'settings_screen.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../providers/chat_unread_provider.dart';
|
||||
|
||||
|
||||
class MainBottomNav extends StatefulWidget {
|
||||
const MainBottomNav({super.key});
|
||||
@@ -20,7 +23,7 @@ class MainBottomNavState extends State<MainBottomNav> {
|
||||
setState(() => _currentIndex = index);
|
||||
}
|
||||
|
||||
final List<Widget> _screens = const [
|
||||
final List<Widget> _screens = [
|
||||
DashboardScreen(),
|
||||
OrdersScreen(),
|
||||
InvoiceScreen(),
|
||||
@@ -161,11 +164,54 @@ class MainBottomNavState extends State<MainBottomNav> {
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
index == 3
|
||||
? Consumer<ChatUnreadProvider>(
|
||||
builder: (_, chat, __) {
|
||||
return Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
Icon(
|
||||
_icons[index],
|
||||
size: 22 * scale,
|
||||
color: Colors.black87,
|
||||
),
|
||||
|
||||
if (chat.unreadCount > 0)
|
||||
Positioned(
|
||||
right: -6,
|
||||
top: -6,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(4),
|
||||
decoration: const BoxDecoration(
|
||||
color: Colors.red,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
constraints: const BoxConstraints(
|
||||
minWidth: 20,
|
||||
minHeight: 20,
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
chat.unreadCount.toString(),
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
)
|
||||
: Icon(
|
||||
_icons[index],
|
||||
size: 22 * scale,
|
||||
color: Colors.black87,
|
||||
),
|
||||
|
||||
SizedBox(height: 4 * scale),
|
||||
Text(
|
||||
_labels[index],
|
||||
|
||||
62
lib/services/chat_realtime_service.dart
Normal file
62
lib/services/chat_realtime_service.dart
Normal file
@@ -0,0 +1,62 @@
|
||||
import 'dart:convert';
|
||||
import 'package:pusher_channels_flutter/pusher_channels_flutter.dart';
|
||||
import '../services/dio_client.dart';
|
||||
|
||||
class ChatRealtimeService {
|
||||
static final PusherChannelsFlutter _pusher =
|
||||
PusherChannelsFlutter.getInstance();
|
||||
|
||||
static Future<void> connect({
|
||||
required int ticketId,
|
||||
required Function(Map<String, dynamic>) onMessage,
|
||||
}) async {
|
||||
|
||||
print(" 🧪🧪🧪🧪🧪🧪🧪🧪🧪SUBSCRIBING TO: private-ticket.$ticketId");
|
||||
|
||||
await _pusher.init(
|
||||
apiKey: "q5fkk5rvcnatvbgadwvl",
|
||||
cluster: "mt1",
|
||||
|
||||
onAuthorizer: (channelName, socketId, options) async {
|
||||
print("🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪AUTHORIZING CHANNEL: $channelName");
|
||||
|
||||
final dio = DioClient.getInstance(options);
|
||||
|
||||
final res = await dio.post(
|
||||
'/broadcasting/auth',
|
||||
data: {
|
||||
'socket_id': socketId,
|
||||
'channel_name': channelName,
|
||||
},
|
||||
);
|
||||
|
||||
return res.data;
|
||||
},
|
||||
|
||||
onEvent: (event) {
|
||||
if (event.eventName == "NewChatMessage") {
|
||||
final data = jsonDecode(event.data);
|
||||
onMessage(Map<String, dynamic>.from(data));
|
||||
}
|
||||
},
|
||||
|
||||
onConnectionStateChange: (current, previous) {
|
||||
print("PUSHER STATE: $current");
|
||||
},
|
||||
|
||||
onError: (message, code, error) {
|
||||
print("PUSHER ERROR: $message");
|
||||
},
|
||||
);
|
||||
|
||||
await _pusher.subscribe(
|
||||
channelName: "private-ticket.$ticketId",
|
||||
);
|
||||
|
||||
await _pusher.connect();
|
||||
}
|
||||
|
||||
static Future<void> disconnect() async {
|
||||
await _pusher.disconnect();
|
||||
}
|
||||
}
|
||||
41
lib/services/chat_service.dart
Normal file
41
lib/services/chat_service.dart
Normal file
@@ -0,0 +1,41 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import '../config/api_config.dart';
|
||||
|
||||
class ChatService {
|
||||
final Dio dio;
|
||||
|
||||
ChatService(this.dio);
|
||||
|
||||
/// Start chat / get ticket
|
||||
Future<Map<String, dynamic>> startChat() async {
|
||||
final res = await dio.get('/user/chat/start');
|
||||
return Map<String, dynamic>.from(res.data);
|
||||
}
|
||||
|
||||
/// Get all messages
|
||||
Future<List<dynamic>> getMessages(int ticketId) async {
|
||||
final res = await dio.get('/user/chat/messages/$ticketId');
|
||||
return res.data['messages'];
|
||||
}
|
||||
|
||||
/// Send message (text or file)
|
||||
Future<void> sendMessage(
|
||||
int ticketId, {
|
||||
String? message,
|
||||
String? filePath,
|
||||
}) async {
|
||||
final form = FormData();
|
||||
|
||||
if (message != null) form.fields.add(MapEntry('message', message));
|
||||
if (filePath != null) {
|
||||
form.files.add(
|
||||
MapEntry(
|
||||
'file',
|
||||
await MultipartFile.fromFile(filePath),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
await dio.post('/user/chat/send/$ticketId', data: form);
|
||||
}
|
||||
}
|
||||
204
lib/services/reverb_socket_service.dart
Normal file
204
lib/services/reverb_socket_service.dart
Normal file
@@ -0,0 +1,204 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../services/dio_client.dart';
|
||||
|
||||
class ReverbSocketService {
|
||||
WebSocketChannel? _channel;
|
||||
Timer? _pingTimer;
|
||||
bool _connected = false;
|
||||
|
||||
late BuildContext _context;
|
||||
late int _ticketId;
|
||||
late Function(Map<String, dynamic>) _onMessage;
|
||||
late VoidCallback _onBackgroundMessage;
|
||||
late VoidCallback _onAdminMessage;
|
||||
|
||||
|
||||
/// Prevent duplicate messages on reconnect
|
||||
final Set<int> _receivedIds = {};
|
||||
|
||||
// ============================
|
||||
// CONNECT
|
||||
// ============================
|
||||
Future<void> connect({
|
||||
required BuildContext context,
|
||||
required int ticketId,
|
||||
required Function(Map<String, dynamic>) onMessage,
|
||||
//required VoidCallback onBackgroundMessage,
|
||||
required VoidCallback onAdminMessage, // 👈 ADD
|
||||
}) async {
|
||||
_context = context;
|
||||
_ticketId = ticketId;
|
||||
_onMessage = onMessage;
|
||||
//_onBackgroundMessage = onBackgroundMessage;
|
||||
_onAdminMessage = onAdminMessage; // 👈 SAVE
|
||||
|
||||
final uri = Uri.parse(
|
||||
'ws://10.11.236.74:8080/app/q5fkk5rvcnatvbgadwvl'
|
||||
'?protocol=7&client=flutter&version=1.0',
|
||||
);
|
||||
|
||||
debugPrint("🔌 CONNECTING SOCKET → $uri");
|
||||
|
||||
_channel = WebSocketChannel.connect(uri);
|
||||
|
||||
_channel!.stream.listen(
|
||||
_handleMessage,
|
||||
onDone: _handleDisconnect,
|
||||
onError: (e) {
|
||||
debugPrint("❌ SOCKET ERROR: $e");
|
||||
_handleDisconnect();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ============================
|
||||
// HANDLE SOCKET MESSAGE
|
||||
// ============================
|
||||
Future<void> _handleMessage(dynamic raw) async {
|
||||
debugPrint("📥 RAW: $raw");
|
||||
|
||||
final payload = jsonDecode(raw);
|
||||
final event = payload['event']?.toString() ?? '';
|
||||
|
||||
// --------------------------------
|
||||
// CONNECTED
|
||||
// --------------------------------
|
||||
if (event == 'pusher:connection_established') {
|
||||
final socketId = jsonDecode(payload['data'])['socket_id'];
|
||||
debugPrint("✅ CONNECTED | socket_id=$socketId");
|
||||
|
||||
await _subscribe(socketId);
|
||||
_startHeartbeat();
|
||||
_connected = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// --------------------------------
|
||||
// HEARTBEAT
|
||||
// --------------------------------
|
||||
if (event == 'pusher:pong') {
|
||||
debugPrint("💓 PONG");
|
||||
return;
|
||||
}
|
||||
|
||||
// --------------------------------
|
||||
// CHAT MESSAGE
|
||||
// --------------------------------
|
||||
if (
|
||||
event == 'NewChatMessage' ||
|
||||
event.endsWith('.NewChatMessage') ||
|
||||
event.contains('NewChatMessage')) {
|
||||
dynamic data = payload['data'];
|
||||
if (data is String) data = jsonDecode(data);
|
||||
|
||||
final int msgId = data['id'];
|
||||
final String senderType = data['sender_type'] ?? '';
|
||||
|
||||
// 🔁 Prevent duplicates
|
||||
if (_receivedIds.contains(msgId)) {
|
||||
debugPrint("🔁 DUPLICATE MESSAGE IGNORED: $msgId");
|
||||
return;
|
||||
}
|
||||
_receivedIds.add(msgId);
|
||||
|
||||
debugPrint("📩 NEW MESSAGE");
|
||||
debugPrint("🆔 id=$msgId");
|
||||
debugPrint("👤 sender=$senderType");
|
||||
debugPrint("💬 text=${data['message']}");
|
||||
|
||||
// Always push message to UI
|
||||
_onMessage(Map<String, dynamic>.from(data));
|
||||
|
||||
// 🔔 Increment unread ONLY if ADMIN sent message
|
||||
// 🔔 Increment unread ONLY if ADMIN sent message
|
||||
if (senderType == 'App\\Models\\Admin') {
|
||||
debugPrint("🔔 ADMIN MESSAGE → UNREAD +1");
|
||||
_onAdminMessage(); // ✅ ACTUAL INCREMENT
|
||||
}
|
||||
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// ============================
|
||||
// SUBSCRIBE PRIVATE CHANNEL
|
||||
// ============================
|
||||
Future<void> _subscribe(String socketId) async {
|
||||
debugPrint("📡 SUBSCRIBING private-ticket.$_ticketId");
|
||||
|
||||
final dio = DioClient.getInstance(_context);
|
||||
|
||||
final res = await dio.post(
|
||||
'/broadcasting/auth',
|
||||
data: {
|
||||
'socket_id': socketId,
|
||||
'channel_name': 'private-ticket.$_ticketId',
|
||||
},
|
||||
);
|
||||
|
||||
_channel!.sink.add(jsonEncode({
|
||||
'event': 'pusher:subscribe',
|
||||
'data': {
|
||||
'channel': 'private-ticket.$_ticketId',
|
||||
'auth': res.data['auth'],
|
||||
},
|
||||
}));
|
||||
|
||||
debugPrint("✅ SUBSCRIBED private-ticket.$_ticketId");
|
||||
}
|
||||
|
||||
// ============================
|
||||
// HEARTBEAT
|
||||
// ============================
|
||||
void _startHeartbeat() {
|
||||
_pingTimer?.cancel();
|
||||
|
||||
_pingTimer = Timer.periodic(
|
||||
const Duration(seconds: 30),
|
||||
(_) {
|
||||
if (_connected) {
|
||||
debugPrint("💓 SENDING PING");
|
||||
_channel?.sink.add(jsonEncode({
|
||||
'event': 'pusher:ping',
|
||||
'data': {}
|
||||
}));
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ============================
|
||||
// HANDLE DISCONNECT
|
||||
// ============================
|
||||
void _handleDisconnect() {
|
||||
debugPrint("⚠️ SOCKET DISCONNECTED → RECONNECTING");
|
||||
|
||||
_connected = false;
|
||||
_pingTimer?.cancel();
|
||||
_channel?.sink.close();
|
||||
|
||||
Future.delayed(const Duration(seconds: 2), () {
|
||||
connect(
|
||||
context: _context,
|
||||
ticketId: _ticketId,
|
||||
onMessage: _onMessage,
|
||||
// onBackgroundMessage: _onBackgroundMessage,
|
||||
onAdminMessage: _onAdminMessage, // 👈 ADD
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// ============================
|
||||
// MANUAL DISCONNECT
|
||||
// ============================
|
||||
void disconnect() {
|
||||
debugPrint("❌ SOCKET CLOSED MANUALLY");
|
||||
_connected = false;
|
||||
_pingTimer?.cancel();
|
||||
_channel?.sink.close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user