import { useLocation } from "wouter"; import { useAuth } from "@/hooks/use-auth"; import { useQuery, useMutation } from "@tanstack/react-query"; import { ordersApi } from "@/lib/api"; import { apiRequest, queryClient } from "@/lib/queryClient"; import Header from "@/components/layout/header"; import { useToast } from "@/hooks/use-toast"; import { Package, ArrowLeft, Eye, RotateCcw, X } from "lucide-react"; import { useState } from "react"; export default function Orders() { const [, setLocation] = useLocation(); const { user, isLoading } = useAuth(); const [searchQuery, setSearchQuery] = useState(""); const [activeCategory, setActiveCategory] = useState<'all' | 'delivered' | 'undelivered'>('all'); const { toast } = useToast(); // Always call useQuery hook to maintain consistent hook order const { data: orders = [], isLoading: ordersLoading } = useQuery({ queryKey: ['/api/orders'], queryFn: async () => { const response = await ordersApi.get(); return response.json(); }, enabled: !!user, // Only fetch when user is authenticated }); // Always call useMutation hook to maintain consistent hook order const cancelOrderMutation = useMutation({ mutationFn: async (orderId: string) => { const response = await apiRequest('PATCH', `/api/orders/${orderId}/cancel`); return response.json(); }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['/api/orders'] }); toast({ title: "Order Cancelled", description: "Your order has been successfully cancelled.", }); }, onError: (error: any) => { toast({ title: "Failed to Cancel Order", description: error.message || "Something went wrong. Please try again.", variant: "destructive", }); }, }); // Show loading while authentication is being verified if (isLoading) { return (

Loading...

); } // Redirect if not authenticated after loading completes if (!user) { setLocation('/auth'); return null; } const getStatusColor = (status: string) => { switch (status.toLowerCase()) { case 'delivered': return '#10b981'; // green case 'shipped': return '#3b82f6'; // blue case 'pending': return '#f59e0b'; // amber case 'cancelled': return '#ef4444'; // red default: return '#6b7280'; // gray } }; const getStatusText = (status: string) => { return status.charAt(0).toUpperCase() + status.slice(1); }; const isDelivered = (status: string) => { return status.toLowerCase() === 'delivered'; }; const filteredOrders = orders.filter((order: any) => { if (activeCategory === 'delivered') { return isDelivered(order.status); } else if (activeCategory === 'undelivered') { return !isDelivered(order.status); } return true; // 'all' }); const handleTrackOrder = (orderId: string) => { // For now, just show an alert - in a real app you'd open a tracking modal or page alert(`Tracking order ${orderId.slice(0, 8)}...`); }; const handleReorder = (order: any) => { // For now, just navigate to home - in a real app you'd add items to cart alert('Items added to cart!'); setLocation('/'); }; const handleCancelOrder = (orderId: string) => { if (confirm('Are you sure you want to cancel this order? This action cannot be undone.')) { cancelOrderMutation.mutate(orderId); } }; return (
{/* Back Button */}
{/* Header */}

My Orders

Track and manage your order history

{/* Category Filters */}
{/* Orders List */}

Order History

{ordersLoading ? (
{[...Array(3)].map((_, i) => (
))}
) : filteredOrders.length > 0 ? (
{filteredOrders.map((order: any) => (
{/* Order Header */}

Order #{order.id.slice(0, 8).toUpperCase()}

Placed on {new Date(order.createdAt).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}

{getStatusText(order.status)}
{/* Order Items */} {order.items && order.items.length > 0 && (
{order.items.map((item: any) => (
{item.product?.images && item.product.images.length > 0 ? ( {item.product.title} ) : (
)}

{item.product?.title || 'Unknown Product'}

Sold by {item.product?.store?.name || 'Unknown Seller'}

Qty: {item.quantity}

₹{parseFloat(item.price).toFixed(2)}

))}
)} {/* Order Summary */}
Total: ₹{parseFloat(order.total).toFixed(2)}

Payment: {order.paymentMethod === 'cod' ? 'Cash on Delivery' : 'UPI'}

{order.status === 'pending' && ( )}
))}
) : (

{activeCategory === 'all' ? 'No orders yet' : `No ${activeCategory} orders`}

{activeCategory === 'all' ? "You haven't placed any orders yet. Start shopping to see your orders here!" : `You don't have any ${activeCategory} orders.` }

)}
); }