This commit is contained in:
NotII
2025-03-23 23:08:09 +00:00
parent 259898cef0
commit 64ee9b842e
4 changed files with 46 additions and 71 deletions

View File

@@ -11,8 +11,7 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import axios from "axios";
import { getCookie } from "@/lib/client-utils";
import { clientFetch } from "@/lib/client-utils";
interface UnreadCounts {
totalUnread: number;
@@ -81,54 +80,45 @@ export default function ChatNotifications() {
useEffect(() => {
const fetchUnreadCounts = async () => {
try {
const authToken = getCookie("Authorization");
// Use clientFetch instead of direct API calls to leverage the Next.js API rewrite rules
if (!authToken) return;
const authAxios = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
headers: {
Authorization: `Bearer ${authToken}`
}
});
// Get vendor info from profile endpoint - removing /api prefix
const vendorResponse = await authAxios.get('/auth/me');
// Get vendor info from profile endpoint
const vendorData = await clientFetch('/auth/me');
// Access correct property - the vendor ID is in vendor._id
const vendorId = vendorResponse.data.vendor?._id;
const vendorId = vendorData.vendor?._id;
if (!vendorId) {
console.error("Vendor ID not found in profile response:", vendorResponse.data);
console.error("Vendor ID not found in profile response:", vendorData);
return;
}
const response = await authAxios.get(`/chats/vendor/${vendorId}/unread`);
const response = await clientFetch(`/chats/vendor/${vendorId}/unread`);
// Check if there are new notifications and play sound if needed
if (!loading && response.data.totalUnread > previousUnreadTotal) {
if (!loading && response.totalUnread > previousUnreadTotal) {
playNotificationSound();
}
// Update state
setUnreadCounts(response.data);
setPreviousUnreadTotal(response.data.totalUnread);
// Update state - clientFetch already parses the JSON
setUnreadCounts(response);
setPreviousUnreadTotal(response.totalUnread);
if (response.data.totalUnread > 0) {
const chatIds = Object.keys(response.data.chatCounts);
if (response.totalUnread > 0) {
const chatIds = Object.keys(response.chatCounts);
if (chatIds.length > 0) {
// Create a simplified metadata object with just needed info
const metadata: Record<string, { buyerId: string }> = {};
// Fetch each chat to get buyer IDs - removing /api prefix
// Fetch each chat to get buyer IDs
await Promise.all(
chatIds.map(async (chatId) => {
try {
// Use markAsRead=false to ensure we don't mark messages as read
const chatResponse = await authAxios.get(`/chats/${chatId}?markAsRead=false`);
const chatResponse = await clientFetch(`/chats/${chatId}?markAsRead=false`);
metadata[chatId] = {
buyerId: chatResponse.data.buyerId,
buyerId: chatResponse.buyerId,
};
} catch (error) {
console.error(`Error fetching chat ${chatId}:`, error);