This commit is contained in:
NotII
2025-03-23 23:27:49 +00:00
parent 631929f1fd
commit 2b40ee668f
4 changed files with 71 additions and 127 deletions

View File

@@ -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 { clientFetch } from "@/lib/client-utils"; import axios from "axios";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
interface Order { interface Order {
@@ -62,13 +62,27 @@ export default function BuyerOrderInfo({ buyerId, chatId }: BuyerOrderInfoProps)
setLoading(true); setLoading(true);
try { try {
// Use clientFetch instead of direct axios calls const authToken = getCookie("Authorization");
// This ensures the request goes through Next.js API rewrites
const response = await clientFetch(`/chats/${chatId}/orders?limit=10`);
if (response && response.orders) { if (!authToken) {
setOrders(response.orders); isFetchingRef.current = false;
setHasOrders(response.orders.length > 0); setLoading(false);
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);
} }

View File

@@ -12,7 +12,6 @@ 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;
@@ -33,7 +32,6 @@ 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 = () => {
@@ -83,47 +81,24 @@ export default function NewChatForm() {
} }
}; };
// Check if a chat already exists with this user // Debounced search function
const checkExistingChat = async (userId: string) => { const searchUsers = debounce(async (query: string) => {
try { if (!query.trim() || !vendorStores[0]?._id) return;
// Use clientFetch instead of direct axios calls
const response = await clientFetch(`/chats/user/${userId}`);
// If a chat is found, redirect to it const authAxios = getAuthAxios();
if (response && Array.isArray(response) && response.length > 0) { if (!authAxios) return;
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 { try {
if (!query || query.length < 2) { setSearching(true);
setSearchResults([]); const response = await authAxios.get(`/chats/search/users?query=${encodeURIComponent(query)}&storeId=${vendorStores[0]._id}`);
return; setSearchResults(response.data);
}
// 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 for users"); toast.error("Failed to search 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) => {
@@ -201,71 +176,54 @@ export default function NewChatForm() {
router.push("/dashboard/chats"); router.push("/dashboard/chats");
}; };
// Create a new chat with the selected user const handleSubmit = async (e: React.FormEvent) => {
const createChat = async (e?: React.FormEvent) => { e.preventDefault();
if (e) e.preventDefault();
if (!selectedUser) { if (!buyerId) {
toast.error("Please select a user first"); toast.error("Please select a customer");
return; return;
} }
setIsSubmitting(true); if (vendorStores.length === 0) {
toast.error("No store available. Please create a store first.");
return;
}
const storeId = vendorStores[0]._id;
setLoading(true);
try { try {
// Check for existing chat first const authAxios = getAuthAxios();
const chatExists = await checkExistingChat(selectedUser.telegramUserId); if (!authAxios) {
if (chatExists) { toast.error("You need to be logged in");
setIsSubmitting(false); router.push("/auth/login");
return; return;
} }
// Get current vendor info const response = await authAxios.post("/chats/create", {
// Use clientFetch instead of direct axios calls buyerId,
const vendorResponse = await clientFetch('/auth/me'); storeId: storeId,
const vendorId = vendorResponse.vendor?._id; initialMessage: initialMessage.trim() || undefined
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 && response._id) { if (response.data.chatId) {
toast.success("Chat created successfully"); toast.success("Chat created successfully!");
router.push(`/dashboard/chats/${response._id}`); 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}`);
} 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 {
setIsSubmitting(false); setLoading(false);
} }
}; };
@@ -284,7 +242,7 @@ export default function NewChatForm() {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<form onSubmit={(e) => createChat(e)} className="space-y-6"> <form onSubmit={handleSubmit} 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">

View File

@@ -10,6 +10,7 @@ import { ShoppingCart, RefreshCcw } from "lucide-react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { useToast } from "@/components/ui/use-toast" import { useToast } from "@/components/ui/use-toast"
import { Skeleton } from "@/components/ui/skeleton" import { Skeleton } from "@/components/ui/skeleton"
import { clientFetch } from "@/lib/client-utils"
interface ContentProps { interface ContentProps {
username: string username: string
@@ -90,35 +91,11 @@ export default function Content({ username, orderStats }: ContentProps) {
const [randomQuote, setRandomQuote] = useState(getRandomQuote()) const [randomQuote, setRandomQuote] = useState(getRandomQuote())
const fetchTopProducts = async () => { const fetchTopProducts = async () => {
setIsLoading(true)
setError(null)
try { try {
// Get the auth token from cookies setIsLoading(true)
const authToken = document.cookie
.split("; ")
.find((row) => row.startsWith("Authorization="))
?.split("=")[1];
if (!authToken) { // Use clientFetch to handle URL routing and authentication properly
throw new Error("Authentication token not found") const data = await clientFetch('/orders/top-products');
}
// Use the API URL from environment variables
const apiUrl = `${process.env.NEXT_PUBLIC_API_URL}/orders/top-products`;
const response = await fetch(apiUrl, {
headers: {
Authorization: `Bearer ${authToken}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error(`API request failed: ${response.status} ${response.statusText}`)
}
const data = await response.json();
setTopProducts(data); setTopProducts(data);
} catch (err) { } catch (err) {
console.error("Error fetching top products:", err); console.error("Error fetching top products:", err);

View File

@@ -16,18 +16,13 @@ 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,