Update BuyerOrderInfo.tsx
This commit is contained in:
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import React, { useState, useEffect } from "react";
|
import React, { useState, useEffect, useCallback, useRef } from "react";
|
||||||
import { Package, ShoppingBag, Info, ExternalLink } from "lucide-react";
|
import { Package, ShoppingBag, Info, ExternalLink, Loader2 } from "lucide-react";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
@@ -35,18 +35,40 @@ interface BuyerOrderInfoProps {
|
|||||||
|
|
||||||
export default function BuyerOrderInfo({ buyerId, chatId }: BuyerOrderInfoProps) {
|
export default function BuyerOrderInfo({ buyerId, chatId }: BuyerOrderInfoProps) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(false);
|
||||||
const [orders, setOrders] = useState<Order[]>([]);
|
const [orders, setOrders] = useState<Order[]>([]);
|
||||||
|
const [hasOrders, setHasOrders] = useState<boolean | null>(null);
|
||||||
|
const [isTooltipOpen, setIsTooltipOpen] = useState(false);
|
||||||
|
const lastFetchedRef = useRef<number>(0);
|
||||||
|
const isFetchingRef = useRef<boolean>(false);
|
||||||
|
const tooltipDelayRef = useRef<NodeJS.Timeout | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
// Fetch data without unnecessary dependencies to reduce render cycles
|
||||||
// Only load if we have a chatId
|
const fetchBuyerOrders = useCallback(async (force = false) => {
|
||||||
|
// Prevent multiple simultaneous fetches
|
||||||
|
if (isFetchingRef.current) return;
|
||||||
|
|
||||||
|
// Don't fetch if we already know there are no orders
|
||||||
|
if (hasOrders === false && !force) return;
|
||||||
|
|
||||||
|
// Don't fetch if we already have orders and data was fetched less than 10 seconds ago
|
||||||
|
const now = Date.now();
|
||||||
|
if (!force && orders.length > 0 && now - lastFetchedRef.current < 10000) return;
|
||||||
|
|
||||||
|
// Only continue if we have a chatId
|
||||||
if (!chatId) return;
|
if (!chatId) return;
|
||||||
|
|
||||||
const fetchBuyerOrders = async () => {
|
isFetchingRef.current = true;
|
||||||
|
setLoading(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const authToken = getCookie("Authorization");
|
const authToken = getCookie("Authorization");
|
||||||
|
|
||||||
if (!authToken) return;
|
if (!authToken) {
|
||||||
|
isFetchingRef.current = false;
|
||||||
|
setLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const authAxios = axios.create({
|
const authAxios = axios.create({
|
||||||
baseURL: process.env.NEXT_PUBLIC_API_URL,
|
baseURL: process.env.NEXT_PUBLIC_API_URL,
|
||||||
@@ -56,52 +78,95 @@ export default function BuyerOrderInfo({ buyerId, chatId }: BuyerOrderInfoProps)
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Use the new endpoint that works with sub-users
|
// Use the new endpoint that works with sub-users
|
||||||
const response = await authAxios.get(`/chats/${chatId}/orders?limit=250`);
|
const response = await authAxios.get(`/chats/${chatId}/orders?limit=10`); // Limit to fewer orders for faster response
|
||||||
|
|
||||||
if (response.data && response.data.orders) {
|
if (response.data && response.data.orders) {
|
||||||
setOrders(response.data.orders);
|
setOrders(response.data.orders);
|
||||||
|
setHasOrders(response.data.orders.length > 0);
|
||||||
|
} else {
|
||||||
|
setHasOrders(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
setLoading(false);
|
lastFetchedRef.current = Date.now();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error fetching buyer orders:", error);
|
console.error("Error fetching buyer orders:", error);
|
||||||
|
setHasOrders(false);
|
||||||
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
|
isFetchingRef.current = false;
|
||||||
|
}
|
||||||
|
}, [chatId]); // Minimize dependencies even further
|
||||||
|
|
||||||
|
// 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]);
|
||||||
fetchBuyerOrders();
|
|
||||||
}, [chatId]);
|
|
||||||
|
|
||||||
const handleViewOrder = (orderId: string) => {
|
const handleViewOrder = (orderId: string) => {
|
||||||
router.push(`/dashboard/orders/${orderId}`);
|
router.push(`/dashboard/orders/${orderId}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Handle hover with immediate tooltip opening
|
||||||
|
const handleButtonMouseEnter = () => {
|
||||||
|
// Start fetching data, but don't wait for it to complete
|
||||||
|
if (!isFetchingRef.current) {
|
||||||
|
queueMicrotask(() => {
|
||||||
|
fetchBuyerOrders();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle tooltip state change
|
||||||
|
const handleTooltipOpenChange = (open: boolean) => {
|
||||||
|
setIsTooltipOpen(open);
|
||||||
|
if (open && !isFetchingRef.current) {
|
||||||
|
queueMicrotask(() => {
|
||||||
|
fetchBuyerOrders();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Format the price as currency
|
// Format the price as currency
|
||||||
const formatPrice = (price: number) => {
|
const formatPrice = (price: number) => {
|
||||||
return `£${price.toFixed(2)}`;
|
return `£${price.toFixed(2)}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Don't show anything while loading or if no orders
|
// If we know there are no orders, don't show the component at all
|
||||||
if (loading || orders.length === 0) {
|
if (hasOrders === false) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Count products across all orders
|
// Precompute product count for button display (only if we have orders)
|
||||||
const productCount = orders.reduce((total, order) => {
|
const productCount = orders.length > 0
|
||||||
|
? orders.reduce((total, order) => {
|
||||||
return total + order.products.reduce((sum, product) => sum + product.quantity, 0);
|
return total + order.products.reduce((sum, product) => sum + product.quantity, 0);
|
||||||
}, 0);
|
}, 0)
|
||||||
|
: 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<TooltipProvider>
|
<TooltipProvider>
|
||||||
<Tooltip>
|
<Tooltip onOpenChange={handleTooltipOpenChange}>
|
||||||
<TooltipTrigger asChild>
|
<TooltipTrigger asChild>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
size="sm"
|
size="sm"
|
||||||
className="ml-2 flex items-center gap-1.5"
|
className="ml-2 flex items-center gap-1.5"
|
||||||
|
onMouseEnter={handleButtonMouseEnter}
|
||||||
>
|
>
|
||||||
<ShoppingBag className="h-4 w-4" />
|
<ShoppingBag className="h-4 w-4" />
|
||||||
<span className="text-xs font-medium">{orders.length} Orders</span>
|
<span className="text-xs font-medium">
|
||||||
|
{orders.length > 0 ? `${orders.length} Orders` : "Orders"}
|
||||||
|
</span>
|
||||||
{productCount > 0 && (
|
{productCount > 0 && (
|
||||||
<Badge variant="secondary" className="text-[10px] px-1.5 py-0 ml-1">
|
<Badge variant="secondary" className="text-[10px] px-1.5 py-0 ml-1">
|
||||||
{productCount} items
|
{productCount} items
|
||||||
@@ -109,12 +174,31 @@ export default function BuyerOrderInfo({ buyerId, chatId }: BuyerOrderInfoProps)
|
|||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent side="bottom" align="start" className="w-80 p-0" sideOffset={10}>
|
<TooltipContent
|
||||||
|
side="bottom"
|
||||||
|
align="start"
|
||||||
|
className="w-80 p-0"
|
||||||
|
sideOffset={10}
|
||||||
|
>
|
||||||
<div className="py-2">
|
<div className="py-2">
|
||||||
<div className="px-3 py-2 text-xs font-medium border-b flex justify-between items-center">
|
<div className="px-3 py-2 text-xs font-medium border-b flex justify-between items-center">
|
||||||
<span>Recent Orders from this Customer</span>
|
<span>Recent Orders from this Customer</span>
|
||||||
<Info className="h-3.5 w-3.5 text-muted-foreground" />
|
<Info className="h-3.5 w-3.5 text-muted-foreground" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
// Show loading state
|
||||||
|
<div className="p-4 flex justify-center items-center">
|
||||||
|
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||||
|
<span className="ml-2 text-sm text-muted-foreground">Loading orders...</span>
|
||||||
|
</div>
|
||||||
|
) : orders.length === 0 ? (
|
||||||
|
// Show no orders state
|
||||||
|
<div className="p-4 text-center text-sm text-muted-foreground">
|
||||||
|
No orders found for this customer
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
// Show orders
|
||||||
<div className="max-h-64 overflow-y-auto divide-y divide-border">
|
<div className="max-h-64 overflow-y-auto divide-y divide-border">
|
||||||
{orders.map((order) => (
|
{orders.map((order) => (
|
||||||
<div
|
<div
|
||||||
@@ -149,6 +233,8 @@ export default function BuyerOrderInfo({ buyerId, chatId }: BuyerOrderInfoProps)
|
|||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="border-t px-3 py-2">
|
<div className="border-t px-3 py-2">
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
|
|||||||
Reference in New Issue
Block a user