This commit is contained in:
NotII
2025-03-24 01:46:11 +00:00
parent 1e395b8684
commit 39c349509c
19 changed files with 477 additions and 427 deletions

View File

@@ -10,23 +10,22 @@ import {
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { clientFetch } from "@/lib/client-utils";
import { getCookie } from "@/lib/client-utils";
import axios from "axios";
import { useRouter } from "next/navigation";
interface OrderProduct {
productId: string;
quantity: number;
pricePerUnit: number;
totalItemPrice: number;
}
interface Order {
_id: string;
orderId: number;
status: string;
totalPrice: number;
orderDate: string;
products: OrderProduct[];
products: Array<{
productId: string;
quantity: number;
pricePerUnit: number;
totalItemPrice: number;
}>;
}
interface BuyerOrderInfoProps {
@@ -34,26 +33,17 @@ interface BuyerOrderInfoProps {
chatId: string;
}
/**
* Component that displays order information for a buyer in a chat
* Shows a tooltip with recent orders and allows navigation to order details
*/
export default function BuyerOrderInfo({ buyerId, chatId }: BuyerOrderInfoProps) {
const router = useRouter();
// State
const [loading, setLoading] = useState(false);
const [orders, setOrders] = useState<Order[]>([]);
const [hasOrders, setHasOrders] = useState<boolean | null>(null);
const [isTooltipOpen, setIsTooltipOpen] = useState(false);
// Refs to prevent unnecessary re-renders and API calls
const lastFetchedRef = useRef<number>(0);
const isFetchingRef = useRef<boolean>(false);
const tooltipDelayRef = useRef<NodeJS.Timeout | null>(null);
/**
* Fetch buyer orders from the API
*/
// Fetch data without unnecessary dependencies to reduce render cycles
const fetchBuyerOrders = useCallback(async (force = false) => {
// Prevent multiple simultaneous fetches
if (isFetchingRef.current) return;
@@ -72,12 +62,27 @@ export default function BuyerOrderInfo({ buyerId, chatId }: BuyerOrderInfoProps)
setLoading(true);
try {
// Use clientFetch to handle auth and API routing automatically
const response = await clientFetch(`/chats/${chatId}/orders?limit=10`);
const authToken = getCookie("Authorization");
if (response && response.orders) {
setOrders(response.orders);
setHasOrders(response.orders.length > 0);
if (!authToken) {
isFetchingRef.current = false;
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 {
setHasOrders(false);
}
@@ -90,44 +95,48 @@ export default function BuyerOrderInfo({ buyerId, chatId }: BuyerOrderInfoProps)
setLoading(false);
isFetchingRef.current = false;
}
}, [chatId, orders.length, hasOrders]);
}, [chatId]); // Minimize dependencies even further
// Fetch orders when component mounts
// Start fetching immediately when component mounts
useEffect(() => {
if (chatId) {
// Immediately attempt to fetch in the background
fetchBuyerOrders();
}
return () => {
// Clean up any pending timeouts
if (tooltipDelayRef.current) {
clearTimeout(tooltipDelayRef.current);
}
};
}, [chatId, fetchBuyerOrders]);
/**
* Navigate to order details page
*/
const handleViewOrder = (orderId: string) => {
router.push(`/dashboard/orders/${orderId}`);
};
/**
* Handle mouse enter on the button to start loading data
*/
// Handle hover with immediate tooltip opening
const handleButtonMouseEnter = () => {
// Start fetching data, but don't wait for it to complete
if (!isFetchingRef.current) {
queueMicrotask(() => fetchBuyerOrders());
queueMicrotask(() => {
fetchBuyerOrders();
});
}
};
/**
* Handle tooltip state change, load data if opening
*/
// Handle tooltip state change
const handleTooltipOpenChange = (open: boolean) => {
setIsTooltipOpen(open);
if (open && !isFetchingRef.current) {
queueMicrotask(() => fetchBuyerOrders());
queueMicrotask(() => {
fetchBuyerOrders();
});
}
};
/**
* Format price as currency
*/
// Format the price as currency
const formatPrice = (price: number) => {
return `£${price.toFixed(2)}`;
};
@@ -137,26 +146,13 @@ export default function BuyerOrderInfo({ buyerId, chatId }: BuyerOrderInfoProps)
return null;
}
// Calculate total products across all orders
// Precompute product count for button display (only if we have orders)
const productCount = orders.length > 0
? orders.reduce((total, order) => {
return total + order.products.reduce((sum, product) => sum + product.quantity, 0);
}, 0)
: 0;
/**
* Get badge variant based on order status
*/
const getStatusBadgeVariant = (status: string) => {
switch (status) {
case "paid": return "paid";
case "unpaid": return "unpaid";
case "shipped": return "shipped";
case "completed": return "completed";
default: return "secondary";
}
};
return (
<TooltipProvider>
<Tooltip onOpenChange={handleTooltipOpenChange}>
@@ -215,10 +211,13 @@ export default function BuyerOrderInfo({ buyerId, chatId }: BuyerOrderInfoProps)
<Package className="h-3.5 w-3.5" />
<span className="text-xs font-medium">Order #{order.orderId}</span>
</div>
<Badge
variant={getStatusBadgeVariant(order.status)}
className="text-[10px] h-5 px-1.5"
>
<Badge variant={
order.status === "paid" ? "paid" :
order.status === "unpaid" ? "unpaid" :
order.status === "shipped" ? "shipped" :
order.status === "completed" ? "completed" :
"secondary"
} className="text-[10px] h-5 px-1.5">
{order.status.toUpperCase()}
</Badge>
</div>

View File

@@ -8,8 +8,9 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { ArrowLeft, Send, RefreshCw, Search, User } from "lucide-react";
import axios from "axios";
import { toast } from "sonner";
import { clientFetch } from "@/lib/client-utils";
import { getCookie } from "@/lib/client-utils";
import debounce from "lodash/debounce";
interface User {
@@ -17,63 +18,60 @@ interface User {
telegramUsername: string | null;
}
interface Store {
_id: string;
name: string;
}
export default function NewChatForm() {
const router = useRouter();
const searchParams = useSearchParams();
// State management
const [buyerId, setBuyerId] = useState("");
const [searchQuery, setSearchQuery] = useState("");
const [searchResults, setSearchResults] = useState<User[]>([]);
const [searching, setSearching] = useState(false);
const [open, setOpen] = useState(false);
const [initialMessage, setInitialMessage] = useState("");
const [vendorStores, setVendorStores] = useState<Store[]>([]);
const [loading, setLoading] = useState(false);
const [loadingUser, setLoadingUser] = useState(false);
const [vendorStores, setVendorStores] = useState<{ _id: string, name: string }[]>([]);
const [selectedStore, setSelectedStore] = useState<string>("");
const [selectedUser, setSelectedUser] = useState<User | null>(null);
// Loading states
const [searching, setSearching] = useState(false);
const [loading, setLoading] = useState(false);
const [loadingUser, setLoadingUser] = useState(false);
const [loadingStores, setLoadingStores] = useState(false);
// UI state
const [open, setOpen] = useState(false);
// Create an axios instance with auth
const getAuthAxios = () => {
const authToken = getCookie("Authorization");
if (!authToken) return null;
return axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL,
headers: { Authorization: `Bearer ${authToken}` }
});
};
// Parse URL parameters for buyerId and fetch user details if present
useEffect(() => {
const buyerIdParam = searchParams.get('buyerId');
if (buyerIdParam) {
setBuyerId(buyerIdParam);
// We'll fetch user details after stores are loaded
}
}, [searchParams]);
// Fetch vendor stores on component mount
useEffect(() => {
fetchVendorStores();
}, []);
// Fetch user information if buyer ID changes
useEffect(() => {
if (buyerId && vendorStores.length > 0) {
fetchUserById(buyerId);
}
}, [buyerId, vendorStores]);
// Fetch user information by ID
const fetchUserById = async (userId: string) => {
if (!userId || !vendorStores[0]?._id) return;
const authAxios = getAuthAxios();
if (!authAxios) {
toast.error("You need to be logged in");
router.push("/auth/login");
return;
}
setLoadingUser(true);
try {
const userData = await clientFetch(`/chats/user/${userId}`);
if (userData) {
setSelectedUser(userData);
setSearchQuery(userData.telegramUsername || `User ${userId}`);
const response = await authAxios.get(`/chats/user/${userId}`);
if (response.data) {
setSelectedUser(response.data);
setSearchQuery(response.data.telegramUsername || `User ${userId}`);
} else {
// Just leave the buyerId as is without username display
}
} catch (error) {
console.error("Error fetching user:", error);
@@ -83,47 +81,17 @@ export default function NewChatForm() {
}
};
// Fetch vendor stores
const fetchVendorStores = async () => {
setLoadingStores(true);
try {
// Get stores
const stores = await clientFetch('/storefront');
// Handle both array and single object responses
if (Array.isArray(stores)) {
setVendorStores(stores);
if (stores.length > 0) {
setSelectedStore(stores[0]._id);
}
} else if (stores && typeof stores === 'object' && stores._id) {
const singleStore = [stores];
setVendorStores(singleStore);
setSelectedStore(stores._id);
}
} catch (error) {
console.error("Error fetching stores:", error);
toast.error("Failed to load your stores");
// Redirect if there's a login issue
if (error instanceof Error && error.message.includes('logged in')) {
router.push("/auth/login");
}
} finally {
setLoadingStores(false);
}
};
// Debounced search function
const searchUsers = debounce(async (query: string) => {
if (!query.trim() || !selectedStore) return;
if (!query.trim() || !vendorStores[0]?._id) return;
const authAxios = getAuthAxios();
if (!authAxios) return;
setSearching(true);
try {
const results = await clientFetch(
`/chats/search/users?query=${encodeURIComponent(query)}&storeId=${selectedStore}`
);
setSearchResults(results);
setSearching(true);
const response = await authAxios.get(`/chats/search/users?query=${encodeURIComponent(query)}&storeId=${vendorStores[0]._id}`);
setSearchResults(response.data);
} catch (error) {
console.error("Error searching users:", error);
toast.error("Failed to search users");
@@ -147,40 +115,113 @@ export default function NewChatForm() {
setOpen(false);
};
// Navigation handlers
// Fetch vendor stores
useEffect(() => {
const fetchVendorStores = async () => {
const authAxios = getAuthAxios();
if (!authAxios) {
toast.error("You must be logged in to start a chat");
router.push("/auth/login");
return;
}
try {
// Get vendor profile first
const vendorResponse = await authAxios.get('/auth/me');
// Extract vendor ID properly
const vendorId = vendorResponse.data.vendor?._id;
if (!vendorId) {
console.error("Vendor ID not found in profile response:", vendorResponse.data);
toast.error("Could not retrieve vendor information");
return;
}
// Fetch store
const storeResponse = await authAxios.get(`/storefront`);
// Handle both array and single object responses
if (Array.isArray(storeResponse.data)) {
setVendorStores(storeResponse.data);
if (storeResponse.data.length > 0) {
setSelectedStore(storeResponse.data[0]._id);
}
} else if (storeResponse.data && typeof storeResponse.data === 'object' && storeResponse.data._id) {
const singleStore = [storeResponse.data];
setVendorStores(singleStore);
setSelectedStore(storeResponse.data._id);
} else {
console.error("Expected store data but received:", storeResponse.data);
setVendorStores([]);
toast.error("Failed to load store data in expected format");
}
// Now that we have the store, fetch user details if buyerId was set
const buyerIdParam = searchParams.get('buyerId');
if (buyerIdParam) {
fetchUserById(buyerIdParam);
}
} catch (error) {
console.error("Error fetching store:", error);
toast.error("Failed to load store");
setVendorStores([]);
}
};
fetchVendorStores();
}, []);
const handleBackClick = () => {
router.push("/dashboard/chats");
};
// Start new chat
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!buyerId || !initialMessage.trim() || !selectedStore) {
toast.error("Please fill in all required fields");
if (!buyerId) {
toast.error("Please select a customer");
return;
}
if (vendorStores.length === 0) {
toast.error("No store available. Please create a store first.");
return;
}
const storeId = vendorStores[0]._id;
setLoading(true);
try {
const response = await clientFetch('/chats', {
method: 'POST',
body: JSON.stringify({
buyerId,
storeId: selectedStore,
initialMessage: initialMessage.trim()
}),
headers: {
'Content-Type': 'application/json'
}
const authAxios = getAuthAxios();
if (!authAxios) {
toast.error("You need to be logged in");
router.push("/auth/login");
return;
}
const response = await authAxios.post("/chats/create", {
buyerId,
storeId: storeId,
initialMessage: initialMessage.trim() || undefined
});
// Navigate to the new chat
toast.success("Chat created successfully");
router.push(`/dashboard/chats/${response._id}`);
} catch (error) {
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);
toast.error("Failed to create chat. Please try again.");
if (error.response?.status === 409) {
toast.info("Chat already exists, redirecting...");
router.push(`/dashboard/chats/${error.response.data.chatId}`);
} else {
toast.error("Failed to create chat");
}
} finally {
setLoading(false);
}