Files
ember-market-frontend/components/dashboard/BuyerOrderInfo.tsx
2025-03-24 01:09:49 +00:00

255 lines
8.1 KiB
TypeScript

"use client";
import React, { useState, useEffect, useCallback, useRef } from "react";
import { Package, ShoppingBag, Info, ExternalLink, Loader2 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { clientFetch } from "@/lib/client-utils";
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[];
}
interface BuyerOrderInfoProps {
buyerId: string;
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);
/**
* Fetch buyer orders from the API
*/
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;
isFetchingRef.current = true;
setLoading(true);
try {
// Use clientFetch to handle auth and API routing automatically
const response = await clientFetch(`/chats/${chatId}/orders?limit=10`);
if (response && response.orders) {
setOrders(response.orders);
setHasOrders(response.orders.length > 0);
} else {
setHasOrders(false);
}
lastFetchedRef.current = Date.now();
} catch (error) {
console.error("Error fetching buyer orders:", error);
setHasOrders(false);
} finally {
setLoading(false);
isFetchingRef.current = false;
}
}, [chatId, orders.length, hasOrders]);
// Fetch orders when component mounts
useEffect(() => {
if (chatId) {
fetchBuyerOrders();
}
}, [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
*/
const handleButtonMouseEnter = () => {
if (!isFetchingRef.current) {
queueMicrotask(() => fetchBuyerOrders());
}
};
/**
* Handle tooltip state change, load data if opening
*/
const handleTooltipOpenChange = (open: boolean) => {
setIsTooltipOpen(open);
if (open && !isFetchingRef.current) {
queueMicrotask(() => fetchBuyerOrders());
}
};
/**
* Format price as currency
*/
const formatPrice = (price: number) => {
return `£${price.toFixed(2)}`;
};
// If we know there are no orders, don't show the component at all
if (hasOrders === false) {
return null;
}
// Calculate total products across all 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}>
<TooltipTrigger asChild>
<Button
variant="outline"
size="sm"
className="ml-2 flex items-center gap-1.5"
onMouseEnter={handleButtonMouseEnter}
>
<ShoppingBag className="h-4 w-4" />
<span className="text-xs font-medium">
{orders.length > 0 ? `${orders.length} Orders` : "Orders"}
</span>
{productCount > 0 && (
<Badge variant="secondary" className="text-[10px] px-1.5 py-0 ml-1">
{productCount} items
</Badge>
)}
</Button>
</TooltipTrigger>
<TooltipContent
side="bottom"
align="start"
className="w-80 p-0"
sideOffset={10}
>
<div className="py-2">
<div className="px-3 py-2 text-xs font-medium border-b flex justify-between items-center">
<span>Recent Orders from this Customer</span>
<Info className="h-3.5 w-3.5 text-muted-foreground" />
</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">
{orders.map((order) => (
<div
key={order._id}
className="px-3 py-2 hover:bg-accent/50 cursor-pointer"
onClick={() => handleViewOrder(order._id)}
>
<div className="flex items-center justify-between mb-1">
<div className="flex items-center gap-2">
<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"
>
{order.status.toUpperCase()}
</Badge>
</div>
<div className="flex justify-between items-center text-xs text-muted-foreground pl-5">
<div className="flex gap-1">
<span>{order.products.length} {order.products.length === 1 ? 'product' : 'products'}</span>
<span>·</span>
<span>{formatPrice(order.totalPrice)}</span>
</div>
<span className="text-[10px]">{new Date(order.orderDate).toLocaleDateString()}</span>
</div>
</div>
))}
</div>
)}
<div className="border-t px-3 py-2">
<Button
variant="ghost"
size="sm"
className="w-full h-7 text-xs flex items-center gap-1.5"
onClick={() => router.push(`/dashboard/orders?buyer=${buyerId}`)}
>
<ExternalLink className="h-3.5 w-3.5" />
View All Customer Orders
</Button>
</div>
</div>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}