chat update

This commit is contained in:
Abhishek Mali
2026-02-27 10:12:51 +05:30
parent 0c1d3b8cb2
commit 98d184d901
7 changed files with 237 additions and 150 deletions

File diff suppressed because one or more lines are too long

View File

@@ -3,6 +3,6 @@
// static const String fileBaseUrl = "http://103.248.30.24:3030/"; // static const String fileBaseUrl = "http://103.248.30.24:3030/";
// } // }
class ApiConfig { class ApiConfig {
static const String baseUrl = "http://10.202.215.164:8000/api"; static const String baseUrl = "http://10.119.0.74:8000/api";
static const String fileBaseUrl = "http://10.202.215.164:8000/"; static const String fileBaseUrl = "http://10.119.0.74:8000/";
} }

View File

@@ -6,7 +6,7 @@ class AppConfig {
static const String logoUrlEmulator = "http://10.0.2.2:8000/images/kent_logo2.png"; static const String logoUrlEmulator = "http://10.0.2.2:8000/images/kent_logo2.png";
// For Physical Device (Replace with your actual PC local IP) // For Physical Device (Replace with your actual PC local IP)
static const String logoUrlDevice = "http://10.202.215.164:8000/images/kent_logo2.png"; static const String logoUrlDevice = "http://103.248.30.24:8000/images/kent_logo2.png";
// Which one to use? // Which one to use?
static const String logoUrl = logoUrlDevice; // CHANGE THIS WHEN TESTING ON REAL DEVICE static const String logoUrl = logoUrlDevice; // CHANGE THIS WHEN TESTING ON REAL DEVICE

View File

@@ -1,14 +1,16 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'dart:io';
import 'package:file_selector/file_selector.dart';
import '../services/chat_service.dart'; import '../services/chat_service.dart';
import '../services/reverb_socket_service.dart'; import '../services/reverb_socket_service.dart';
import '../services/dio_client.dart'; import '../services/dio_client.dart';
import '../providers/chat_unread_provider.dart'; import '../providers/chat_unread_provider.dart';
import '../widgets/chat_file_preview.dart'; import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
import 'package:file_selector/file_selector.dart';
import 'chat_file_viewer.dart'; import 'chat_file_viewer.dart';
import '../widgets/chat_file_preview.dart';
class ChatScreen extends StatefulWidget { class ChatScreen extends StatefulWidget {
const ChatScreen({super.key}); const ChatScreen({super.key});
@@ -20,7 +22,6 @@ class ChatScreen extends StatefulWidget {
class _ChatScreenState extends State<ChatScreen> { class _ChatScreenState extends State<ChatScreen> {
final TextEditingController _messageCtrl = TextEditingController(); final TextEditingController _messageCtrl = TextEditingController();
final ScrollController _scrollCtrl = ScrollController(); final ScrollController _scrollCtrl = ScrollController();
Map<String, dynamic>? uploadingMessage; Map<String, dynamic>? uploadingMessage;
late ChatService _chatService; late ChatService _chatService;
@@ -30,18 +31,22 @@ class _ChatScreenState extends State<ChatScreen> {
List<Map<String, dynamic>> messages = []; List<Map<String, dynamic>> messages = [];
bool isLoading = true; bool isLoading = true;
// ============================
// INIT STATE
// ============================
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_chatService = ChatService(DioClient.getInstance(context)); _chatService = ChatService(DioClient.getInstance(context));
// 🔔 Mark chat as OPEN (important)
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
context.read<ChatUnreadProvider>().setChatOpen(true); context.read<ChatUnreadProvider>().setChatOpen(true);
}); });
_initChat(); _initChat();
} }
String _guessMimeType(String path) { String _guessMimeType(String path) {
final lower = path.toLowerCase(); final lower = path.toLowerCase();
if (lower.endsWith('.jpg') || lower.endsWith('.png')) return 'image/*'; if (lower.endsWith('.jpg') || lower.endsWith('.png')) return 'image/*';
@@ -56,6 +61,7 @@ class _ChatScreenState extends State<ChatScreen> {
final file = File(picked.path); final file = File(picked.path);
// 1⃣ Show uploading UI
setState(() { setState(() {
uploadingMessage = { uploadingMessage = {
'local_file': file, 'local_file': file,
@@ -64,26 +70,41 @@ class _ChatScreenState extends State<ChatScreen> {
}; };
}); });
// 2⃣ Upload (NO adding message)
await _chatService.sendFile( await _chatService.sendFile(
ticketId!, ticketId!,
file, file,
onProgress: (progress) { onProgress: (progress) {
if (!mounted) return; if (!mounted) return;
setState(() => uploadingMessage!['progress'] = progress); setState(() {
uploadingMessage!['progress'] = progress;
});
}, },
); );
// 3⃣ Remove sending bubble ONLY
if (!mounted) return; if (!mounted) return;
setState(() => uploadingMessage = null); setState(() {
uploadingMessage = null;
});
// 🚫 DO NOT add message here
// WebSocket will handle it
} }
// ============================
// INIT CHAT
// ============================
Future<void> _initChat() async { Future<void> _initChat() async {
// 1⃣ Start chat
final ticketRes = await _chatService.startChat(); final ticketRes = await _chatService.startChat();
ticketId = ticketRes['ticket']['id']; ticketId = ticketRes['ticket']['id'];
// 2⃣ Load messages
final msgs = await _chatService.getMessages(ticketId!); final msgs = await _chatService.getMessages(ticketId!);
messages = List<Map<String, dynamic>>.from(msgs); messages = List<Map<String, dynamic>>.from(msgs);
// 3⃣ Realtime socket
await _socket.connect( await _socket.connect(
context: context, context: context,
ticketId: ticketId!, ticketId: ticketId!,
@@ -91,12 +112,19 @@ class _ChatScreenState extends State<ChatScreen> {
final incomingClientId = msg['client_id']; final incomingClientId = msg['client_id'];
setState(() { setState(() {
messages.removeWhere((m) => m['client_id'] == incomingClientId); // 🧹 Remove local temp message with same client_id
messages.removeWhere(
(m) => m['client_id'] != null &&
m['client_id'] == incomingClientId,
);
// ✅ Add confirmed socket message
messages.add(msg); messages.add(msg);
}); });
_scrollToBottom(); _scrollToBottom();
}, },
onAdminMessage: () { onAdminMessage: () {
if (!mounted) { if (!mounted) {
context.read<ChatUnreadProvider>().increment(); context.read<ChatUnreadProvider>().increment();
@@ -109,25 +137,29 @@ class _ChatScreenState extends State<ChatScreen> {
_scrollToBottom(); _scrollToBottom();
} }
// ============================
// SCROLL
// ============================
void _scrollToBottom() { void _scrollToBottom() {
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
if (_scrollCtrl.hasClients) { if (_scrollCtrl.hasClients) {
_scrollCtrl.animateTo( _scrollCtrl.jumpTo(_scrollCtrl.position.maxScrollExtent);
_scrollCtrl.position.maxScrollExtent,
duration: const Duration(milliseconds: 250),
curve: Curves.easeOut,
);
} }
}); });
} }
// ============================
// SEND MESSAGE
// ============================
Future<void> _sendMessage() async { Future<void> _sendMessage() async {
final text = _messageCtrl.text.trim(); final text = _messageCtrl.text.trim();
if (text.isEmpty || ticketId == null) return; if (text.isEmpty || ticketId == null) return;
_messageCtrl.clear(); _messageCtrl.clear();
final clientId = DateTime.now().millisecondsSinceEpoch.toString(); final clientId = DateTime.now().millisecondsSinceEpoch.toString();
// 1⃣ ADD LOCAL MESSAGE IMMEDIATELY
setState(() { setState(() {
messages.add({ messages.add({
'client_id': clientId, 'client_id': clientId,
@@ -141,6 +173,7 @@ class _ChatScreenState extends State<ChatScreen> {
_scrollToBottom(); _scrollToBottom();
// 2⃣ SEND TO SERVER
await _chatService.sendMessage( await _chatService.sendMessage(
ticketId!, ticketId!,
message: text, message: text,
@@ -148,68 +181,27 @@ class _ChatScreenState extends State<ChatScreen> {
); );
} }
// ============================
// DISPOSE
// ============================
@override @override
void dispose() { void dispose() {
// 🔕 Mark chat CLOSED
context.read<ChatUnreadProvider>().setChatOpen(false); context.read<ChatUnreadProvider>().setChatOpen(false);
_socket.disconnect(); _socket.disconnect();
_messageCtrl.dispose(); _messageCtrl.dispose();
_scrollCtrl.dispose(); _scrollCtrl.dispose();
super.dispose(); super.dispose();
} }
// ============================
// UI
// ============================
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: PreferredSize( appBar: AppBar(title: const Text("Support Chat")),
preferredSize: const Size.fromHeight(56),
child: AnimatedContainer(
duration: const Duration(milliseconds: 300),
curve: Curves.easeInOut,
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Color(0xFF2196F3),
Color(0xFF1565C0),
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 10,
offset: Offset(0, 3),
),
],
),
child: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: Padding(
padding: const EdgeInsets.only(left: 12),
child: CircleAvatar(
radius: 18,
backgroundColor: Colors.white,
child: Icon(
Icons.support_agent,
color: Colors.blue,
size: 20,
),
),
),
title: const Text(
"Support Chat",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
fontSize: 18,
),
),
centerTitle: false,
iconTheme: const IconThemeData(color: Colors.white),
),
),
),
body: isLoading body: isLoading
? const Center(child: CircularProgressIndicator()) ? const Center(child: CircularProgressIndicator())
: Column( : Column(
@@ -221,54 +213,81 @@ class _ChatScreenState extends State<ChatScreen> {
); );
} }
Widget _buildMessageContent({
String? message,
String? filePath,
String? fileType,
required bool isUser,
}) {
final textColor = isUser ? Colors.white : Colors.black;
if (filePath == null) {
return Text(message ?? '', style: TextStyle(color: textColor));
}
final url = "${DioClient.baseUrl}/storage/$filePath";
return GestureDetector(
onTap: () {
ChatFileViewer.open(
context,
url: url,
fileType: fileType ?? '',
);
},
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(_iconForFile(fileType), color: textColor),
const SizedBox(width: 8),
Text(
_labelForFile(fileType),
style: TextStyle(color: textColor),
),
],
),
);
}
IconData _iconForFile(String? type) {
if (type == null) return Icons.insert_drive_file;
if (type.startsWith('image/')) return Icons.image;
if (type.startsWith('video/')) return Icons.play_circle_fill;
if (type == 'application/pdf') return Icons.picture_as_pdf;
return Icons.insert_drive_file;
}
String _labelForFile(String? type) {
if (type == null) return "File";
if (type.startsWith('image/')) return "Image";
if (type.startsWith('video/')) return "Video";
if (type == 'application/pdf') return "PDF";
return "Download file";
}
Widget _buildMessages() { Widget _buildMessages() {
return ListView( return ListView(
controller: _scrollCtrl, controller: _scrollCtrl,
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), padding: const EdgeInsets.all(12),
children: [ children: [
// EXISTING MESSAGES
...messages.map((msg) { ...messages.map((msg) {
final isUser = msg['sender_type'] == 'App\\Models\\User'; final isUser = msg['sender_type'] == 'App\\Models\\User';
return Align( return Align(
alignment: alignment: isUser ? Alignment.centerRight : Alignment.centerLeft,
isUser ? Alignment.centerRight : Alignment.centerLeft,
child: Container( child: Container(
constraints: const BoxConstraints(maxWidth: 280),
margin: const EdgeInsets.symmetric(vertical: 6), margin: const EdgeInsets.symmetric(vertical: 6),
padding: const EdgeInsets.all(12), padding: const EdgeInsets.all(10),
decoration: BoxDecoration( decoration: BoxDecoration(
color: isUser ? null : Colors.white, color: isUser ? Colors.blue : Colors.grey.shade300,
gradient: isUser borderRadius: BorderRadius.circular(12),
? LinearGradient(
colors: [
Colors.lightBlueAccent,
Colors.blue.shade700,
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
)
: null,
borderRadius: BorderRadius.only(
topLeft: const Radius.circular(16),
topRight: const Radius.circular(16),
bottomLeft:
isUser ? const Radius.circular(16) : Radius.zero,
bottomRight:
isUser ? Radius.zero : const Radius.circular(16),
),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 6,
),
],
), ),
child: msg['file_path'] == null child: msg['file_path'] == null
? Text( ? Text(
msg['message'] ?? '', msg['message'] ?? '',
style: TextStyle( style: TextStyle(
color: isUser ? Colors.white : Colors.blue, color: isUser ? Colors.white : Colors.black,
fontSize: 15,
), ),
) )
: ChatFilePreview( : ChatFilePreview(
@@ -279,48 +298,88 @@ class _ChatScreenState extends State<ChatScreen> {
), ),
); );
}), }),
// ⏳ UPLOADING MESSAGE
// ⏳ UPLOADING MESSAGE (SAFE & NO DUPLICATE)
if (uploadingMessage != null)
Align(
alignment: Alignment.centerRight,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 6),
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(12),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// ✅ SHOW PREVIEW ONLY FOR IMAGE / VIDEO
if (uploadingMessage!['file_type'].startsWith('image/') ||
uploadingMessage!['file_type'].startsWith('video/'))
ChatFilePreview(
filePath: uploadingMessage!['local_file'].path,
fileType: uploadingMessage!['file_type'],
isUser: true,
isLocal: true,
)
else
// 📄 DOCUMENT PLACEHOLDER
const Icon(
Icons.insert_drive_file,
color: Colors.white,
size: 40,
),
const SizedBox(height: 8),
LinearProgressIndicator(
value: uploadingMessage!['progress'],
backgroundColor: Colors.white24,
valueColor:
const AlwaysStoppedAnimation<Color>(Colors.white),
),
const SizedBox(height: 4),
const Text(
"Sending…",
style: TextStyle(
color: Colors.white,
fontSize: 12,
),
),
],
),
),
),
], ],
); );
} }
Widget _buildInput() { Widget _buildInput() {
return SafeArea( return SafeArea(
child: Padding( child: Row(
padding: const EdgeInsets.all(8), children: [
child: Container( IconButton(
padding: const EdgeInsets.symmetric(horizontal: 12), icon: const Icon(Icons.attach_file),
decoration: BoxDecoration( onPressed: _pickAndSendFile,
color: Colors.white,
borderRadius: BorderRadius.circular(24),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 6,
),
],
), ),
child: Row( Expanded(
children: [ child: TextField(
IconButton( controller: _messageCtrl,
icon: const Icon(Icons.attach_file), decoration: const InputDecoration(
onPressed: _pickAndSendFile, hintText: "Type message",
border: InputBorder.none,
), ),
Expanded( ),
child: TextField(
controller: _messageCtrl,
decoration: const InputDecoration(
hintText: "Type a message…",
border: InputBorder.none,
),
),
),
IconButton(
icon: const Icon(Icons.send, color: Colors.blue),
onPressed: _sendMessage,
),
],
), ),
), IconButton(
icon: const Icon(Icons.send),
onPressed: _sendMessage,
),
],
), ),
); );
} }

View File

@@ -248,7 +248,7 @@ class _OrdersScreenState extends State<OrdersScreen> {
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
), ),
child: Text( child: Text(
isDomestic ? "Domestic\nDistribution" : (status ?? "Unknown"), isDomestic ? "Domestic\nDistribution" : formatStatusLabel(status),
textAlign: TextAlign.center, textAlign: TextAlign.center,
maxLines: isDomestic ? 2 : 1, maxLines: isDomestic ? 2 : 1,
style: TextStyle( style: TextStyle(
@@ -366,3 +366,24 @@ class _StatusConfig {
final Color bg; final Color bg;
_StatusConfig(this.fg, this.bg); _StatusConfig(this.fg, this.bg);
} }
// ================= STATUS LABEL MAP =================
const Map<String, String> statusLabelMap = {
'shipment_ready': 'Shipment Ready',
'export_custom': 'Export Custom',
'international_transit': 'International Transit',
'arrived_at_port': 'Arrived At Port',
'import_custom': 'Import Custom',
'warehouse': 'Warehouse Processing',
'domestic_distribution': 'Domestic Distribution',
'out_for_delivery': 'Out For Delivery',
'delivered': 'Delivered',
};
String formatStatusLabel(String? status) {
if (status == null || status.isEmpty) return "Unknown";
return statusLabelMap[status.toLowerCase()] ??
status.replaceAll('_', ' ').toUpperCase();
}

View File

@@ -3,6 +3,7 @@ import 'dart:math';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../services/dio_client.dart'; import '../services/dio_client.dart';
import '../services/order_service.dart'; import '../services/order_service.dart';
import 'order_screen.dart';
class OrderTrackScreen extends StatefulWidget { class OrderTrackScreen extends StatefulWidget {
final String orderId; final String orderId;
@@ -314,7 +315,12 @@ class _OrderTrackScreenState extends State<OrderTrackScreen>
), ),
SizedBox(height: 14 * scale), SizedBox(height: 14 * scale),
_twoCol("Status", shipment!['status'], scale), _twoCol(
"Status",
formatStatusLabel(shipment!['status']),
scale,
),
_twoCol("Shipment Date", _fmt(shipment!['shipment_date']), scale), _twoCol("Shipment Date", _fmt(shipment!['shipment_date']), scale),
_twoCol("Origin", shipment!['origin'], scale), _twoCol("Origin", shipment!['origin'], scale),
_twoCol("Destination", shipment!['destination'], scale), _twoCol("Destination", shipment!['destination'], scale),
@@ -377,11 +383,12 @@ class _OrderTrackScreenState extends State<OrderTrackScreen>
), ),
SizedBox(width: 8 * scale), SizedBox(width: 8 * scale),
Text( Text(
(trackData["shipment_status"] ?? "-").toString().toUpperCase(), formatStatusLabel(trackData["shipment_status"]),
style: TextStyle( style: TextStyle(
color: Colors.white, color: Colors.white,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
fontSize: 13 * scale), fontSize: 13 * scale,
),
), ),
], ],
), ),

View File

@@ -388,26 +388,26 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: leak_tracker name: leak_tracker
sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" sha256: "6bb818ecbdffe216e81182c2f0714a2e62b593f4a4f13098713ff1685dfb6ab0"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "11.0.2" version: "10.0.9"
leak_tracker_flutter_testing: leak_tracker_flutter_testing:
dependency: transitive dependency: transitive
description: description:
name: leak_tracker_flutter_testing name: leak_tracker_flutter_testing
sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.10" version: "3.0.9"
leak_tracker_testing: leak_tracker_testing:
dependency: transitive dependency: transitive
description: description:
name: leak_tracker_testing name: leak_tracker_testing
sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.0.2" version: "3.0.1"
lints: lints:
dependency: transitive dependency: transitive
description: description:
@@ -436,10 +436,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: meta name: meta
sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.17.0" version: "1.16.0"
mime: mime:
dependency: transitive dependency: transitive
description: description:
@@ -777,10 +777,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: test_api name: test_api
sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.7.7" version: "0.7.4"
typed_data: typed_data:
dependency: transitive dependency: transitive
description: description:
@@ -865,10 +865,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: vector_math name: vector_math
sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.2.0" version: "2.1.4"
video_player: video_player:
dependency: "direct main" dependency: "direct main"
description: description: