i hope this fixed it

This commit is contained in:
NotII
2025-03-23 23:18:17 +00:00
parent 64ee9b842e
commit f6a2a69ac4
4 changed files with 209 additions and 165 deletions

View File

@@ -11,7 +11,7 @@ import { formatDistanceToNow } from "date-fns";
import axios from "axios";
import { toast } from "sonner";
import { ArrowLeft, Send, RefreshCw, File, FileText, Image as ImageIcon, Download } from "lucide-react";
import { getCookie } from "@/lib/client-utils";
import { getCookie, clientFetch } from "@/lib/client-utils";
import { ImageViewerModal } from "@/components/modals/image-viewer-modal";
import BuyerOrderInfo from "./BuyerOrderInfo";
@@ -174,121 +174,132 @@ export default function ChatDetail({ chatId }: { chatId: string }) {
}
};
// Fetch chat data
const fetchChat = async () => {
// Loading effect
useEffect(() => {
if (chatId) {
fetchChatData();
}
}, [chatId]);
// Get a fresh auth axios instance
const getAuthAxios = () => {
const authToken = getCookie("Authorization");
if (!authToken) return null;
return axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
}
});
};
// Fetch chat information and messages
const fetchChatData = async () => {
if (!chatId) return;
try {
// Get auth token from cookies
const authToken = getCookie("Authorization");
setLoading(true);
if (!authToken) {
toast.error("You need to be logged in");
router.push("/auth/login");
return;
}
// Use clientFetch instead of direct axios calls
const response = await clientFetch(`/chats/${chatId}`);
// Set up axios with the auth token
const authAxios = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
headers: {
Authorization: `Bearer ${authToken}`
}
});
setChatData(response);
setMessages(Array.isArray(response.messages) ? response.messages : []);
// Always fetch messages without marking as read
const response = await authAxios.get(`/chats/${chatId}?markAsRead=false`);
// Check if there are new messages
const hasNewMessages = chat && response.data.messages.length > chat.messages.length;
const unreadBuyerMessages = response.data.messages.some(
(msg: Message) => msg.sender === 'buyer' && !msg.read
);
if (hasNewMessages) {
// Don't play sound for messages we sent (vendor)
const lastMessage = response.data.messages[response.data.messages.length - 1];
if (lastMessage.sender === 'buyer') {
playNotificationSound();
}
}
setChat(response.data);
// Update the previous message count
if (response.data.messages) {
setPreviousMessageCount(response.data.messages.length);
}
setLoading(false);
// Clear any existing timeout
if (markReadTimeoutRef.current) {
clearTimeout(markReadTimeoutRef.current);
}
// Only mark as read with a delay if there are unread buyer messages
if (unreadBuyerMessages) {
// Add a 3-second delay before marking messages as read to allow notification to appear
markReadTimeoutRef.current = setTimeout(() => {
markMessagesAsRead();
}, 3000);
}
// Scroll to bottom on initial load
setTimeout(() => {
scrollToBottom();
}, 100);
} catch (error) {
console.error("Error fetching chat:", error);
toast.error("Failed to load conversation");
console.error("Error fetching chat data:", error);
toast.error("Failed to load chat");
} finally {
setLoading(false);
}
};
// Fetch new messages periodically
useEffect(() => {
fetchChat();
if (!chatId || !chatData) return;
// Poll for updates every 10 seconds
const intervalId = setInterval(fetchChat, 10000);
return () => clearInterval(intervalId);
}, [chatId]);
// Scroll to bottom when messages change
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [chat?.messages]);
// Send a message
const handleSendMessage = async (e: React.FormEvent) => {
e.preventDefault();
if (!message.trim()) return;
setSending(true);
try {
// Get auth token from cookies
const authToken = getCookie("Authorization");
const checkForNewMessages = async () => {
if (isPollingRef.current) return;
if (!authToken) {
toast.error("You need to be logged in");
router.push("/auth/login");
return;
}
isPollingRef.current = true;
// Set up axios with the auth token
const authAxios = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
headers: {
Authorization: `Bearer ${authToken}`
try {
// Use clientFetch instead of direct axios calls
const response = await clientFetch(`/chats/${chatId}?markAsRead=true`);
if (
response &&
Array.isArray(response.messages) &&
response.messages.length !== messages.length
) {
setMessages(response.messages);
// Only auto-scroll if we're already near the bottom
if (isNearBottom()) {
setTimeout(() => {
scrollToBottom();
}, 100);
}
}
} catch (error) {
console.error("Error checking for new messages:", error);
} finally {
isPollingRef.current = false;
}
};
// Check for new messages every 3 seconds
const intervalId = setInterval(checkForNewMessages, 3000);
return () => {
clearInterval(intervalId);
};
}, [chatId, chatData, messages.length]);
// Send a message
const sendMessage = async () => {
if (!chatId || !message.trim()) return;
// Optimistically add message to UI
const tempId = `temp-${Date.now()}`;
const tempMessage = {
_id: tempId,
chatId,
sender: "vendor",
message: message.trim(),
timestamp: new Date().toISOString(),
isTemp: true,
};
setMessages(prev => [...prev, tempMessage]);
scrollToBottom();
// Clear input
setMessage("");
try {
// Use clientFetch instead of direct axios calls
const response = await clientFetch(`/chats/${chatId}/messages`, {
method: 'POST',
body: JSON.stringify({ message: message.trim() }),
});
await authAxios.post(`/chats/${chatId}/message`, {
content: message
});
setMessage("");
await fetchChat(); // Refresh chat after sending
// Replace temp message with real one from server
setMessages(prev =>
prev.filter(m => m._id !== tempId)
.concat(response)
);
} catch (error) {
console.error("Error sending message:", error);
toast.error("Failed to send message");
} finally {
setSending(false);
// Remove temp message on error
setMessages(prev => prev.filter(m => m._id !== tempId));
}
};