This commit is contained in:
NotII
2025-03-08 05:30:23 +00:00
parent 5fb2575922
commit dbd65415d5
3 changed files with 296 additions and 54 deletions

View File

@@ -25,9 +25,7 @@ import {
Plus,
MessageCircle,
Loader2,
RefreshCw,
ChevronLeft,
ChevronRight
RefreshCw
} from "lucide-react";
import axios from "axios";
import { toast } from "sonner";
@@ -177,61 +175,34 @@ export default function ChatList() {
// Fetch chats and unread counts when store is selected
const fetchChats = async () => {
if (!selectedStore && vendorStores.length > 0) {
setSelectedStore("all"); // Set default "all" if we have stores but none selected
}
setLoading(true);
try {
if (!selectedStore) return;
// Get vendor ID from auth token
const authToken = getCookie("Authorization");
if (!authToken) {
console.error("No auth token found");
return;
}
// Set up axios with auth token
const authAxios = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
const endpoint = selectedStore && selectedStore !== "all"
? `/chats?storeId=${selectedStore}`
: "/chats";
const response = await axios.get(`${process.env.NEXT_PUBLIC_API_URL}/api${endpoint}`, {
headers: {
Authorization: `Bearer ${authToken}`
}
Authorization: getCookie("Authorization") || "",
"Content-Type": "application/json",
},
});
// Get vendor ID from JWT token
const tokenParts = authToken.split('.');
const payload = JSON.parse(atob(tokenParts[1]));
const vendorId = payload.id;
setChats(response.data || []);
console.log("Fetching chats for vendor:", vendorId, "store:", selectedStore);
// Fetch chats for this vendor and filter by selected store
const response = await authAxios.get(`/chats/vendor/${vendorId}`);
console.log("All chats:", response.data);
const filteredChats = response.data.filter((chat: Chat) =>
chat.storeId === selectedStore
);
console.log("Filtered chats:", filteredChats);
setChats(filteredChats);
// Fetch unread counts
const unreadResponse = await authAxios.get(`/chats/vendor/${vendorId}/unread`);
console.log("Unread counts:", unreadResponse.data);
// Check if there are new unread messages and play sound
if (!loading && unreadResponse.data.totalUnread > previousTotalUnread) {
playNotificationSound();
}
// Update states
setUnreadCounts(unreadResponse.data);
setPreviousTotalUnread(unreadResponse.data.totalUnread);
setLoading(false);
console.log("Chat loading complete");
// Fetch unread counts after loading chats
await fetchUnreadCounts();
} catch (error) {
console.error("Error fetching chats:", error);
toast.error("Failed to load chats");
console.error("Failed to fetch chats:", error);
toast.error("Failed to load chat conversations");
setChats([]);
} finally {
setLoading(false);
}
};