i hope this fixed it
This commit is contained in:
@@ -12,6 +12,7 @@ import axios from "axios";
|
||||
import { toast } from "sonner";
|
||||
import { getCookie } from "@/lib/client-utils";
|
||||
import debounce from "lodash/debounce";
|
||||
import { clientFetch } from "@/lib/client-utils";
|
||||
|
||||
interface User {
|
||||
telegramUserId: string;
|
||||
@@ -32,6 +33,7 @@ export default function NewChatForm() {
|
||||
const [vendorStores, setVendorStores] = useState<{ _id: string, name: string }[]>([]);
|
||||
const [selectedStore, setSelectedStore] = useState<string>("");
|
||||
const [selectedUser, setSelectedUser] = useState<User | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
// Create an axios instance with auth
|
||||
const getAuthAxios = () => {
|
||||
@@ -81,24 +83,47 @@ export default function NewChatForm() {
|
||||
}
|
||||
};
|
||||
|
||||
// Debounced search function
|
||||
const searchUsers = debounce(async (query: string) => {
|
||||
if (!query.trim() || !vendorStores[0]?._id) return;
|
||||
|
||||
const authAxios = getAuthAxios();
|
||||
if (!authAxios) return;
|
||||
|
||||
// Check if a chat already exists with this user
|
||||
const checkExistingChat = async (userId: string) => {
|
||||
try {
|
||||
setSearching(true);
|
||||
const response = await authAxios.get(`/chats/search/users?query=${encodeURIComponent(query)}&storeId=${vendorStores[0]._id}`);
|
||||
setSearchResults(response.data);
|
||||
// Use clientFetch instead of direct axios calls
|
||||
const response = await clientFetch(`/chats/user/${userId}`);
|
||||
|
||||
// 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) {
|
||||
console.error("Error searching users:", error);
|
||||
toast.error("Failed to search users");
|
||||
toast.error("Failed to search for users");
|
||||
setSearchResults([]);
|
||||
} finally {
|
||||
setSearching(false);
|
||||
}
|
||||
}, 300);
|
||||
};
|
||||
|
||||
// Handle search input change
|
||||
const handleSearchChange = (value: string) => {
|
||||
@@ -176,54 +201,71 @@ export default function NewChatForm() {
|
||||
router.push("/dashboard/chats");
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
// Create a new chat with the selected user
|
||||
const createChat = async (e?: React.FormEvent) => {
|
||||
if (e) e.preventDefault();
|
||||
|
||||
if (!buyerId) {
|
||||
toast.error("Please select a customer");
|
||||
if (!selectedUser) {
|
||||
toast.error("Please select a user first");
|
||||
return;
|
||||
}
|
||||
|
||||
if (vendorStores.length === 0) {
|
||||
toast.error("No store available. Please create a store first.");
|
||||
return;
|
||||
}
|
||||
setIsSubmitting(true);
|
||||
|
||||
const storeId = vendorStores[0]._id;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const authAxios = getAuthAxios();
|
||||
if (!authAxios) {
|
||||
toast.error("You need to be logged in");
|
||||
router.push("/auth/login");
|
||||
// Check for existing chat first
|
||||
const chatExists = await checkExistingChat(selectedUser.telegramUserId);
|
||||
if (chatExists) {
|
||||
setIsSubmitting(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await authAxios.post("/chats/create", {
|
||||
buyerId,
|
||||
storeId: storeId,
|
||||
initialMessage: initialMessage.trim() || undefined
|
||||
// Get current vendor info
|
||||
// Use clientFetch instead of direct axios calls
|
||||
const vendorResponse = await clientFetch('/auth/me');
|
||||
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) {
|
||||
toast.success("Chat created successfully!");
|
||||
router.push(`/dashboard/chats/${response.data.chatId}`);
|
||||
} 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}`);
|
||||
if (response && response._id) {
|
||||
toast.success("Chat created successfully");
|
||||
router.push(`/dashboard/chats/${response._id}`);
|
||||
} else {
|
||||
toast.error("Failed to create chat");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error creating chat:", error);
|
||||
toast.error("Failed to create chat");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -242,7 +284,7 @@ export default function NewChatForm() {
|
||||
</CardHeader>
|
||||
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<form onSubmit={(e) => createChat(e)} className="space-y-6">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="buyerId">Customer Telegram ID or Username</Label>
|
||||
<div className="relative">
|
||||
|
||||
Reference in New Issue
Block a user