i hope this fixed it
This commit is contained in:
@@ -11,7 +11,7 @@ import {
|
|||||||
TooltipTrigger,
|
TooltipTrigger,
|
||||||
} from "@/components/ui/tooltip";
|
} from "@/components/ui/tooltip";
|
||||||
import { getCookie } from "@/lib/client-utils";
|
import { getCookie } from "@/lib/client-utils";
|
||||||
import axios from "axios";
|
import { clientFetch } from "@/lib/client-utils";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
|
|
||||||
interface Order {
|
interface Order {
|
||||||
@@ -62,27 +62,13 @@ export default function BuyerOrderInfo({ buyerId, chatId }: BuyerOrderInfoProps)
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const authToken = getCookie("Authorization");
|
// Use clientFetch instead of direct axios calls
|
||||||
|
// This ensures the request goes through Next.js API rewrites
|
||||||
|
const response = await clientFetch(`/chats/${chatId}/orders?limit=10`);
|
||||||
|
|
||||||
if (!authToken) {
|
if (response && response.orders) {
|
||||||
isFetchingRef.current = false;
|
setOrders(response.orders);
|
||||||
setLoading(false);
|
setHasOrders(response.orders.length > 0);
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const authAxios = axios.create({
|
|
||||||
baseURL: process.env.NEXT_PUBLIC_API_URL,
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${authToken}`
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Use the new endpoint that works with sub-users
|
|
||||||
const response = await authAxios.get(`/chats/${chatId}/orders?limit=10`); // Limit to fewer orders for faster response
|
|
||||||
|
|
||||||
if (response.data && response.data.orders) {
|
|
||||||
setOrders(response.data.orders);
|
|
||||||
setHasOrders(response.data.orders.length > 0);
|
|
||||||
} else {
|
} else {
|
||||||
setHasOrders(false);
|
setHasOrders(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { formatDistanceToNow } from "date-fns";
|
|||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { ArrowLeft, Send, RefreshCw, File, FileText, Image as ImageIcon, Download } from "lucide-react";
|
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 { ImageViewerModal } from "@/components/modals/image-viewer-modal";
|
||||||
import BuyerOrderInfo from "./BuyerOrderInfo";
|
import BuyerOrderInfo from "./BuyerOrderInfo";
|
||||||
|
|
||||||
@@ -174,121 +174,132 @@ export default function ChatDetail({ chatId }: { chatId: string }) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Fetch chat data
|
// Loading effect
|
||||||
const fetchChat = async () => {
|
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 {
|
try {
|
||||||
// Get auth token from cookies
|
setLoading(true);
|
||||||
const authToken = getCookie("Authorization");
|
|
||||||
|
|
||||||
if (!authToken) {
|
// Use clientFetch instead of direct axios calls
|
||||||
toast.error("You need to be logged in");
|
const response = await clientFetch(`/chats/${chatId}`);
|
||||||
router.push("/auth/login");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set up axios with the auth token
|
setChatData(response);
|
||||||
const authAxios = axios.create({
|
setMessages(Array.isArray(response.messages) ? response.messages : []);
|
||||||
baseURL: process.env.NEXT_PUBLIC_API_URL,
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${authToken}`
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Always fetch messages without marking as read
|
// Scroll to bottom on initial load
|
||||||
const response = await authAxios.get(`/chats/${chatId}?markAsRead=false`);
|
setTimeout(() => {
|
||||||
|
scrollToBottom();
|
||||||
// Check if there are new messages
|
}, 100);
|
||||||
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);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error fetching chat:", error);
|
console.error("Error fetching chat data:", error);
|
||||||
toast.error("Failed to load conversation");
|
toast.error("Failed to load chat");
|
||||||
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Fetch new messages periodically
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchChat();
|
if (!chatId || !chatData) return;
|
||||||
|
|
||||||
// Poll for updates every 10 seconds
|
const checkForNewMessages = async () => {
|
||||||
const intervalId = setInterval(fetchChat, 10000);
|
if (isPollingRef.current) return;
|
||||||
|
|
||||||
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");
|
|
||||||
|
|
||||||
if (!authToken) {
|
isPollingRef.current = true;
|
||||||
toast.error("You need to be logged in");
|
|
||||||
router.push("/auth/login");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set up axios with the auth token
|
try {
|
||||||
const authAxios = axios.create({
|
// Use clientFetch instead of direct axios calls
|
||||||
baseURL: process.env.NEXT_PUBLIC_API_URL,
|
const response = await clientFetch(`/chats/${chatId}?markAsRead=true`);
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${authToken}`
|
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`, {
|
// Replace temp message with real one from server
|
||||||
content: message
|
setMessages(prev =>
|
||||||
});
|
prev.filter(m => m._id !== tempId)
|
||||||
|
.concat(response)
|
||||||
setMessage("");
|
);
|
||||||
await fetchChat(); // Refresh chat after sending
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error sending message:", error);
|
console.error("Error sending message:", error);
|
||||||
toast.error("Failed to send message");
|
toast.error("Failed to send message");
|
||||||
} finally {
|
|
||||||
setSending(false);
|
// Remove temp message on error
|
||||||
|
setMessages(prev => prev.filter(m => m._id !== tempId));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import axios from "axios";
|
|||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import { getCookie } from "@/lib/client-utils";
|
import { getCookie } from "@/lib/client-utils";
|
||||||
import debounce from "lodash/debounce";
|
import debounce from "lodash/debounce";
|
||||||
|
import { clientFetch } from "@/lib/client-utils";
|
||||||
|
|
||||||
interface User {
|
interface User {
|
||||||
telegramUserId: string;
|
telegramUserId: string;
|
||||||
@@ -32,6 +33,7 @@ export default function NewChatForm() {
|
|||||||
const [vendorStores, setVendorStores] = useState<{ _id: string, name: string }[]>([]);
|
const [vendorStores, setVendorStores] = useState<{ _id: string, name: string }[]>([]);
|
||||||
const [selectedStore, setSelectedStore] = useState<string>("");
|
const [selectedStore, setSelectedStore] = useState<string>("");
|
||||||
const [selectedUser, setSelectedUser] = useState<User | null>(null);
|
const [selectedUser, setSelectedUser] = useState<User | null>(null);
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
|
||||||
// Create an axios instance with auth
|
// Create an axios instance with auth
|
||||||
const getAuthAxios = () => {
|
const getAuthAxios = () => {
|
||||||
@@ -81,24 +83,47 @@ export default function NewChatForm() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Debounced search function
|
// Check if a chat already exists with this user
|
||||||
const searchUsers = debounce(async (query: string) => {
|
const checkExistingChat = async (userId: string) => {
|
||||||
if (!query.trim() || !vendorStores[0]?._id) return;
|
|
||||||
|
|
||||||
const authAxios = getAuthAxios();
|
|
||||||
if (!authAxios) return;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
setSearching(true);
|
// Use clientFetch instead of direct axios calls
|
||||||
const response = await authAxios.get(`/chats/search/users?query=${encodeURIComponent(query)}&storeId=${vendorStores[0]._id}`);
|
const response = await clientFetch(`/chats/user/${userId}`);
|
||||||
setSearchResults(response.data);
|
|
||||||
|
// If a chat is found, redirect to it
|
||||||
|
if (response && Array.isArray(response) && response.length > 0) {
|
||||||
|
toast.info("Chat already exists, redirecting...");
|
||||||
|
router.push(`/dashboard/chats/${response[0]._id}`);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error checking existing chat:", error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Search for users by Telegram username or ID
|
||||||
|
const searchUsers = async (query: string) => {
|
||||||
|
setSearching(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!query || query.length < 2) {
|
||||||
|
setSearchResults([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use clientFetch instead of direct axios calls
|
||||||
|
const response = await clientFetch(`/chats/search/users?query=${encodeURIComponent(query)}&storeId=${vendorStores[0]._id}`);
|
||||||
|
|
||||||
|
setSearchResults(response || []);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error searching users:", error);
|
console.error("Error searching users:", error);
|
||||||
toast.error("Failed to search users");
|
toast.error("Failed to search for users");
|
||||||
|
setSearchResults([]);
|
||||||
} finally {
|
} finally {
|
||||||
setSearching(false);
|
setSearching(false);
|
||||||
}
|
}
|
||||||
}, 300);
|
};
|
||||||
|
|
||||||
// Handle search input change
|
// Handle search input change
|
||||||
const handleSearchChange = (value: string) => {
|
const handleSearchChange = (value: string) => {
|
||||||
@@ -176,54 +201,71 @@ export default function NewChatForm() {
|
|||||||
router.push("/dashboard/chats");
|
router.push("/dashboard/chats");
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSubmit = async (e: React.FormEvent) => {
|
// Create a new chat with the selected user
|
||||||
e.preventDefault();
|
const createChat = async (e?: React.FormEvent) => {
|
||||||
|
if (e) e.preventDefault();
|
||||||
|
|
||||||
if (!buyerId) {
|
if (!selectedUser) {
|
||||||
toast.error("Please select a customer");
|
toast.error("Please select a user first");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (vendorStores.length === 0) {
|
setIsSubmitting(true);
|
||||||
toast.error("No store available. Please create a store first.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const storeId = vendorStores[0]._id;
|
|
||||||
|
|
||||||
setLoading(true);
|
|
||||||
try {
|
try {
|
||||||
const authAxios = getAuthAxios();
|
// Check for existing chat first
|
||||||
if (!authAxios) {
|
const chatExists = await checkExistingChat(selectedUser.telegramUserId);
|
||||||
toast.error("You need to be logged in");
|
if (chatExists) {
|
||||||
router.push("/auth/login");
|
setIsSubmitting(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await authAxios.post("/chats/create", {
|
// Get current vendor info
|
||||||
buyerId,
|
// Use clientFetch instead of direct axios calls
|
||||||
storeId: storeId,
|
const vendorResponse = await clientFetch('/auth/me');
|
||||||
initialMessage: initialMessage.trim() || undefined
|
const vendorId = vendorResponse.vendor?._id;
|
||||||
|
|
||||||
|
if (!vendorId) {
|
||||||
|
toast.error("Vendor ID not found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get store ID from the current vendor
|
||||||
|
// Use clientFetch instead of direct axios calls
|
||||||
|
const storeResponse = await clientFetch(`/storefront`);
|
||||||
|
const storeId = storeResponse?.store?._id;
|
||||||
|
|
||||||
|
if (!storeId) {
|
||||||
|
toast.error("Store ID not found");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create chat data object
|
||||||
|
const chatData = {
|
||||||
|
buyerId: selectedUser.telegramUserId,
|
||||||
|
vendorId,
|
||||||
|
storeId,
|
||||||
|
initialMessage: initialMessage.trim() || "Hello! How can I help you today?",
|
||||||
|
};
|
||||||
|
|
||||||
|
// Create the chat
|
||||||
|
// Use clientFetch instead of direct axios calls
|
||||||
|
const response = await clientFetch('/chats', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(chatData),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.data.chatId) {
|
if (response && response._id) {
|
||||||
toast.success("Chat created successfully!");
|
toast.success("Chat created successfully");
|
||||||
router.push(`/dashboard/chats/${response.data.chatId}`);
|
router.push(`/dashboard/chats/${response._id}`);
|
||||||
} else if (response.data.error === "Chat already exists") {
|
|
||||||
toast.info("Chat already exists, redirecting...");
|
|
||||||
router.push(`/dashboard/chats/${response.data.chatId}`);
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
console.error("Error creating chat:", error);
|
|
||||||
|
|
||||||
if (error.response?.status === 409) {
|
|
||||||
toast.info("Chat already exists, redirecting...");
|
|
||||||
router.push(`/dashboard/chats/${error.response.data.chatId}`);
|
|
||||||
} else {
|
} else {
|
||||||
toast.error("Failed to create chat");
|
toast.error("Failed to create chat");
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error creating chat:", error);
|
||||||
|
toast.error("Failed to create chat");
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setIsSubmitting(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -242,7 +284,7 @@ export default function NewChatForm() {
|
|||||||
</CardHeader>
|
</CardHeader>
|
||||||
|
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<form onSubmit={handleSubmit} className="space-y-6">
|
<form onSubmit={(e) => createChat(e)} className="space-y-6">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="buyerId">Customer Telegram ID or Username</Label>
|
<Label htmlFor="buyerId">Customer Telegram ID or Username</Label>
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
|
|||||||
@@ -16,13 +16,18 @@ export async function clientFetch(url: string, options: RequestInit = {}): Promi
|
|||||||
|
|
||||||
// Ensure the url doesn't start with a slash if it's going to be appended to a URL that ends with one
|
// Ensure the url doesn't start with a slash if it's going to be appended to a URL that ends with one
|
||||||
const cleanUrl = url.startsWith('/') ? url.substring(1) : url;
|
const cleanUrl = url.startsWith('/') ? url.substring(1) : url;
|
||||||
const baseUrl = process.env.NEXT_PUBLIC_API_URL || '/api';
|
|
||||||
|
// IMPORTANT: Always use /api as the base URL for client-side requests
|
||||||
|
// This ensures all requests go through Next.js API rewrite rules
|
||||||
|
const baseUrl = '/api';
|
||||||
|
|
||||||
// Ensure there's only one slash between the base URL and endpoint
|
// Ensure there's only one slash between the base URL and endpoint
|
||||||
const fullUrl = baseUrl.endsWith('/')
|
const fullUrl = baseUrl.endsWith('/')
|
||||||
? `${baseUrl}${cleanUrl}`
|
? `${baseUrl}${cleanUrl}`
|
||||||
: `${baseUrl}/${cleanUrl}`;
|
: `${baseUrl}/${cleanUrl}`;
|
||||||
|
|
||||||
|
console.log(`[clientFetch] Requesting: ${fullUrl}`);
|
||||||
|
|
||||||
const res = await fetch(fullUrl, {
|
const res = await fetch(fullUrl, {
|
||||||
...options,
|
...options,
|
||||||
headers,
|
headers,
|
||||||
|
|||||||
Reference in New Issue
Block a user