Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Cache the cart... optimize the performance and use pagination... merge this pagination…

  1. User

    Cache the cart... optimize the performance and use pagination... merge this pagination with the orderspage. // src/controllers/cartController.ts

    import { Request, Response, NextFunction } from 'express'; import * as cartModel from '../models/cartModel'; import { query } from "../config/database"; import { deleteCartById, getAllCartsWithItems, updateCartStatus } from "../models/cartModel"; import { decreaseProductQtyInCache, increaseColorSoldInCache, increaseProductSoldInCache, increaseSizeSoldInCache } from "../cacheHelper";

    /**

    • Creates a new cart and updates product quantities accordingly. */ async function updateProductQuantity(productId: number, sizeId: number | null, colorId: number | null, quantity: number): Promise { let updateQuery = ''; const params: any[] = [quantity, productId, null]; // Initialize with null

      if (sizeId) { updateQuery = 'UPDATE sizes SET qty = qty - 1WHEREid=1 WHERE id = 2 AND product_id = 3'; params[2] = sizeId; } else if (colorId) { updateQuery = 'UPDATE colors SET qty = qty - 1 WHERE id = 2ANDproductid=2 AND product_id = 3'; params[2] = colorId; } else { updateQuery = 'UPDATE products SET qty = qty - 1WHEREid=1 WHERE id = 2'; params.splice(2, 1); // Remove the third parameter as it's not needed }

      if (updateQuery) { await query(updateQuery, params);

       // Decrease the quantity in the cache
       decreaseProductQtyInCache(productId, sizeId, colorId, quantity);
      

      } }

    /**

    • Increases the 'sold' count based on product attributes.

    • @param productId - ID of the product

    • @param sizeId - ID of the size (optional)

    • @param colorId - ID of the color (optional)

    • @param quantity - Quantity to increase */ async function increaseSold(productId: number, sizeId: number | null, colorId: number | null, quantity: number): Promise { let updateQuery = ''; let params: any[] = [quantity, productId];

      if (sizeId) { updateQuery = 'UPDATE sizes SET sold = sold + 1WHEREid=1 WHERE id = 2 AND product_id = 3'; params.push(sizeId); } else if (colorId) { updateQuery = 'UPDATE colors SET sold = sold + 1 WHERE id = 2ANDproductid=2 AND product_id = 3'; params.push(colorId); } let productQuery = 'UPDATE products SET sold = sold + 1WHEREid=1 WHERE id = 2'; let productParams = [quantity, productId];

      if (updateQuery) { await query(updateQuery, params); await query(productQuery, productParams);

       // Update the sold count in the cache
       if (sizeId) {
           increaseSizeSoldInCache(productId, sizeId, quantity);
       } else if (colorId) {
           increaseColorSoldInCache(productId, colorId, quantity);
       }
       increaseProductSoldInCache(productId, quantity);
      

      } } /**

    • Creates a new cart and updates product quantities and sold counts accordingly. */ export const createCart = async (req: Request, res: Response) => { try { const { coupon_id, ...cartData } = req.body;

       await query('BEGIN');
      
       const cartResult = await query(
           'INSERT INTO carts (user_id, status, notes, full_name, governorate, city, address, closest_point, phone_number, type) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING *',
           [cartData.user_id, 'Pending', cartData.notes, cartData.full_name, cartData.governorate, cartData.city, cartData.address, cartData.closest_point, cartData.phone_number, cartData.type]
       );
       const cart = cartResult.rows[0];
      
       if (coupon_id) {
           const couponResult = await query('SELECT * FROM coupons WHERE id = $1', [coupon_id]);
           const coupon = couponResult.rows[0];
      
           if (coupon && coupon.is_active) {
               if (coupon.usage_limit !== 0) {
                   await query('UPDATE coupons SET usage_limit = usage_limit - 1 WHERE id = $1', [coupon_id]);
                   const updatedCouponResult = await query('SELECT usage_limit FROM coupons WHERE id = $1', [coupon_id]);
                   if (updatedCouponResult.rows[0].usage_limit === 0) {
                       await query('UPDATE coupons SET is_active = false WHERE id = $1', [coupon_id]);
                   }
               }
               await query('UPDATE carts SET coupon_id = $1 WHERE id = $2', [coupon_id, cart.id]);
           } else {
               await query('ROLLBACK');
               return res.status(400).json({ message: 'Invalid or inactive coupon' });
           }
       }
      
       for (const item of cartData.items) {
           await query(
               'INSERT INTO cart_items (cart_id, product_id, size_id, color_id, quantity) VALUES ($1, $2, $3, $4, $5)',
               [cart.id, item.product_id, item.size_id, item.color_id, item.quantity]
           );
      
           // Decrease the product quantity
           await updateProductQuantity(item.product_id, item.size_id, item.color_id, item.quantity);
      
           // Increase the sold count based on product attributes
           await increaseSold(item.product_id, item.size_id, item.color_id, item.quantity);
       }
      
       await query('COMMIT');
      
       res.status(201).json({ cart });
      

      } catch (error) { await query('ROLLBACK'); console.error('Error creating cart:', error); res.status(500).json({ message: 'Error creating cart' }); } };

    /**

    • Other cart controller functions remain unchanged. */ export async function getCart(req: Request, res: Response, next: NextFunction) { try { const userId = req.user?.id; if (!userId) { return res.status(401).json({ message: 'Unauthorized' }); }

       const cartWithItems = await cartModel.getCartWithItemsByUserId(userId);
       if (!cartWithItems) {
           return res.status(404).json({ message: 'No cart found for the user' });
       }
      
       res.json(cartWithItems);
      

      } catch (error) { next(error); } }

    export async function getAllCarts(req: Request, res: Response, next: NextFunction) { try { const carts = await getAllCartsWithItems(); res.json(carts); } catch (error) { next(error); } }

    export async function updateCart(req: Request, res: Response, next: NextFunction) { try { const cartId = parseInt(req.params.id, 10); const { status } = req.body;

        const updatedCart = await updateCartStatus(cartId, status);
    
        if (!updatedCart) {
            return res.status(404).json({ message: 'Cart not found' });
        }
    
        res.json({ message: 'Cart status updated successfully', cart: updatedCart });
    } catch (error) {
        next(error);
    }
    

    }

    export async function deleteCart(req: Request, res: Response, next: NextFunction) { try { const cartId = parseInt(req.params.id, 10);

        const deleted = await deleteCartById(cartId);
    
        if (!deleted) {
            return res.status(404).json({ message: 'Cart not found' });
        }
    
        res.json({ message: 'Cart deleted successfully' });
    } catch (error) {
        next(error);
    }
    

    } cache.ts: // src/cache.ts import NodeCache from 'node-cache'; export const productCache = new NodeCache({ stdTTL: 0, checkperiod: 600 }); export const brandsCache = new NodeCache({ stdTTL: 0, checkperiod: 600 });

    export const flushProductCache = () => { productCache.del('allProducts'); }; orders/page.tsx: "use client";

    import React, { useState, useEffect, useCallback, useMemo, useRef, } from "react"; import DefaultLayout from "@/components/Layouts/DefaultLayout"; import { Trash2, Search, ChevronDown, ChevronUp, ChevronLeft, ChevronRight, EyeOff, Eye, } from "lucide-react"; import { toast, ToastContainer } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import Image from "next/image"; import { getToken } from "@/app/auth"; import LoadingSpinner from "@/components/LoadingSpinner"; // Importing the spinner

    const API_BASE_URL = process.env.NEXT_PUBLIC_API;

    // Interfaces

    interface OrderItem { price: string; id: number; cart_id: number; product_id: number; size_id?: number | null; color_id?: number | null; quantity: number; }

    interface CartWithItems { id: number; user_id?: number | null; status: string; notes?: string; full_name?: string; governorate?: string; city?: string; address?: string; closest_point?: string; phone_number?: string; type?: string; created_at: string; coupon?: Coupon | null; updated_at: string; items: OrderItem[]; }

    interface Product { id: number; name: string; description?: string; brand_id?: number; has_color: boolean; has_size: boolean; product_type: string; price: string; qty: number | null; created_at: string; updated_at: string; categories: Array<{ id: number; name: string }>; colors: Array<{ id: number; name: string }>; sizes: Array<{ id: number; name: string; price: string; qty: number; color_id: number | null; images: string[]; }>; images: Array<{ id: number; url: string; color_id: number | null; size_id: number | null; }>; }

    interface Coupon { id: number; code: string; name: string; description: string; discount_amount: string | null; discount_percentage: string | null; start_date: string; end_date: string; usage_limit: number; min_purchase_amount: string; max_discount_amount: string; is_active: boolean; }

    interface OrderDetails { totalPrice: number; discountedPrice: number; deliveryCost: number; }

    interface OrderDetailsProps { order: CartWithItems; onUpdateStatus: (orderId: number, newStatus: string) => void; onDeleteOrder: (orderId: number) => void; fetchProduct: (productId: number) => Promise<{ product: Product } | null>; fetchCoupon?: (couponId: number) => Promise<Coupon | null>; products: { [key: number]: Product }; excludedItems: Set; // Track excluded product IDs onToggleExclude: (orderId: number, productId: number) => void; // Handler to toggle exclude isDeleting: boolean; // New prop to track deletion state }

    interface OrderItemProps { item: OrderItem; fetchProduct: (productId: number) => Promise<{ product: Product } | null>; product?: Product; isExcluded: boolean; onToggleExclude: () => void; }

    // Utility Functions

    const formatPrice = (price: number) => { return ${price.toLocaleString()} IQD; };

    const getStatusColor = (status: string) => { switch (status) { case "Pending": return "bg-orange-100 text-orange-800"; case "On Way": return "bg-indigo-100 text-indigo-800"; case "Ordered": return "bg-emerald-100 text-emerald-800"; case "Rejected": return "bg-danger text-white"; // Retaining bg-danger as per user request default: return "bg-gray-100 text-gray-800"; } };

    // Main Component

    const OrdersPage: React.FC = () => { // State Variables const [orders, setOrders] = useState<CartWithItems[]>([]); const [products, setProducts] = useState<{ [key: number]: Product }>({}); const productsRef = useRef<{ [key: number]: Product }>({}); const [coupons, setCoupons] = useState<{ [key: number]: Coupon }>({}); const [error, setError] = useState<string | null>(null); const [searchTerm, setSearchTerm] = useState(""); const [first, setFirst] = useState(true); const [currentPage, setCurrentPage] = useState(1); const ordersPerPage = 10; const [statusFilter, setStatusFilter] = useState("all"); const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc"); const [isInitialLoading, setIsInitialLoading] = useState(true); // Track initial loading

    // Excluded Items State: { [orderId]: Set } const [excludedItems, setExcludedItems] = useState<{ [key: number]: Set; }>({});

    // Ref to track ongoing fetches to prevent duplicate requests const ongoingFetches = useRef<{ [key: number]: Promise<{ product: Product } | null>; }>({});

    // Ref to track existing order IDs for detecting new orders const existingOrderIdsRef = useRef<Set>(new Set());

    // State to track deleting orders const [deletingOrders, setDeletingOrders] = useState<Set>(new Set());

    // Sync productsRef with products state useEffect(() => { productsRef.current = products; }, [products]);

    // Fetch Orders

    const fetchOrders = useCallback(async () => { try { const token = getToken(); // Retrieve the token from localStorage

      if (!token) {
        toast.error("You must be logged in.");
        return;
      }
      const response = await fetch(`${API_BASE_URL}/cart/all`, {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`, // Include the token here
        },
        cache: "no-cache",
      });
      if (!response.ok) throw new Error("Failed to fetch orders");
      const data: CartWithItems[] = await response.json();
    
      if (first) {
        // Initial Fetch
        setOrders(data);
        existingOrderIdsRef.current = new Set(data.map((order) => order.id));
        setFirst(false);
        setIsInitialLoading(false);
      } else {
        // Subsequent Fetches (Polling)
        const newOrders = data.filter(
          (order) => !existingOrderIdsRef.current.has(order.id),
        );
        if (newOrders.length > 0) {
          // Prepend new orders to the existing list
          setOrders((prevOrders) => [...newOrders, ...prevOrders]);
          // Update the existingOrderIdsRef
          newOrders.forEach((order) =>
            existingOrderIdsRef.current.add(order.id),
          );
          // Show toast notification
          toast.success(`Received ${newOrders.length} new order(s)!`);
        }
      }
    } catch (error) {
      console.error("Error fetching orders:", error);
      setError("Failed to fetch orders. Please try again.");
      setIsInitialLoading(false);
    }
    

    }, [first]);

    // Fetch Product

    const fetchProduct = useCallback( async (productId: number): Promise<{ product: Product } | null> => { // Check if product is already fetched if (productsRef.current[productId]) { return { product: productsRef.current[productId] }; }

      // Check if there's an ongoing fetch for this product
      if (await ongoingFetches.current[productId]) {
        return await ongoingFetches.current[productId];
      }
    
      // Start fetching the product and store the promise
      const fetchPromise = (async () => {
        try {
          const token = getToken();
          if (!token) {
            toast.error("You must be logged in.");
            return null;
          }
          const response = await fetch(
            `${API_BASE_URL}/products/${productId}`,
            {
              headers: {
                "Content-Type": "application/json",
                Authorization: `Bearer ${token}`,
              },
            },
          );
          if (!response.ok) throw new Error("Failed to fetch product");
          const data = await response.json();
          setProducts((prev) => ({
            ...prev,
            [productId]: data.product,
          }));
          return data;
        } catch (error) {
          console.error(`Error fetching product ${productId}:`, error);
          return null;
        } finally {
          // Remove the promise from ongoing fetches
          delete ongoingFetches.current[productId];
        }
      })();
    
      ongoingFetches.current[productId] = fetchPromise;
      return fetchPromise;
    },
    [],
    

    );

    // Fetch Coupon

    const fetchCoupon = useCallback( async (couponId: number): Promise<Coupon | null> => { if (coupons[couponId]) { return coupons[couponId]; } try { const token = getToken(); // Retrieve the token from localStorage

        if (!token) {
          toast.error("You must be logged in.");
          return null;
        }
        const response = await fetch(`${API_BASE_URL}/coupons/${couponId}`, {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`, // Include the token here
          },
        });
        if (!response.ok) throw new Error("Failed to fetch coupon");
        const data: Coupon = await response.json();
        setCoupons((prev) => ({ ...prev, [couponId]: data }));
        return data;
      } catch (error) {
        console.error(`Error fetching coupon ${couponId}:`, error);
        return null;
      }
    },
    [coupons],
    

    );

    // Initial Fetch and Polling

    useEffect(() => { fetchOrders(); const intervalId = setInterval(fetchOrders, 30000); // Poll every 30 seconds return () => clearInterval(intervalId); }, [fetchOrders]);

    // Filtering, Sorting, and Pagination

    const filteredAndSortedOrders = useMemo(() => { return orders .filter((order) => { const matchesSearch = (order.full_name && order.full_name.toLowerCase().includes(searchTerm.toLowerCase())) || order.id.toString().includes(searchTerm); const matchesStatus = statusFilter === "all" || order.status === statusFilter; return matchesSearch && matchesStatus; }) .sort((a, b) => { const dateA = new Date(a.created_at).getTime(); const dateB = new Date(b.created_at).getTime(); return sortOrder === "asc" ? dateA - dateB : dateB - dateA; }); }, [orders, searchTerm, statusFilter, sortOrder]);

    const totalPages = Math.ceil(filteredAndSortedOrders.length / ordersPerPage);

    const currentOrders = useMemo(() => { const indexOfLastOrder = currentPage * ordersPerPage; const indexOfFirstOrder = indexOfLastOrder - ordersPerPage; return filteredAndSortedOrders.slice(indexOfFirstOrder, indexOfLastOrder); }, [filteredAndSortedOrders, currentPage, ordersPerPage]);

    const paginate = (pageNumber: number) => { setCurrentPage(Math.max(1, Math.min(pageNumber, totalPages))); };

    // Scroll to Top on Page Change useEffect(() => { window.scrollTo(0, 0); }, [currentPage]);

    // Update Order Status

    const handleUpdateStatus = useCallback( async (orderId: number, newStatus: string) => { const oldStatus = orders.find((order) => order.id === orderId)?.status || "";

      // Optimistically update the UI
      setOrders((prevOrders) =>
        prevOrders.map((order) =>
          order.id === orderId ? { ...order, status: newStatus } : order,
        ),
      );
    
      try {
        const token = getToken();
        if (!token) {
          toast.error("You must be logged in.");
          throw new Error("Not logged in");
        }
    
        const response = await fetch(`${API_BASE_URL}/cart/${orderId}`, {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${token}`, // Include the token here
          },
          body: JSON.stringify({ status: newStatus }),
        });
    
        const result = await response.json();
        if (!response.ok) {
          throw new Error(result.message);
        }
    
        toast.success(result.message);
      } catch (error) {
        console.error("Error updating order status:", error);
        // Revert the status if the update failed
        setOrders((prevOrders) =>
          prevOrders.map((order) =>
            order.id === orderId ? { ...order, status: oldStatus } : order,
          ),
        );
        toast.error("Failed to update order status. Please try again.");
      }
    },
    [orders],
    

    );

    // Optimistic Delete Order

    const handleDeleteOrder = useCallback( async (orderId: number) => { const isConfirmed = window.confirm( "Are you sure you want to delete this order?", );

      if (isConfirmed) {
        // Find the order to be deleted
        const orderToDelete = orders.find((order) => order.id === orderId);
        if (!orderToDelete) {
          toast.error("Order not found.");
          return;
        }
    
        // Optimistically remove the order from the UI
        setOrders((prevOrders) =>
          prevOrders.filter((order) => order.id !== orderId),
        );
        existingOrderIdsRef.current.delete(orderId);
        setDeletingOrders((prev) => new Set(prev).add(orderId));
    
        try {
          const token = getToken(); // Retrieve the token from localStorage
          if (!token) {
            throw new Error("You must be logged in.");
          }
    
          const response = await fetch(`${API_BASE_URL}/cart/${orderId}`, {
            method: "DELETE",
            headers: {
              "Content-Type": "application/json",
              Authorization: `Bearer ${token}`, // Include the token here
            },
          });
          const result = await response.json();
          if (!response.ok) {
            throw new Error(result.message || "Failed to delete order.");
          }
    
          // Optionally, display a success toast
          toast.success(result.message || "Order deleted successfully.");
        } catch (error) {
          console.error("Error deleting order:", error);
          // Restore the order in case of an error
          setOrders((prevOrders) => [orderToDelete, ...prevOrders]);
          existingOrderIdsRef.current.add(orderId);
          toast.error(
            error instanceof Error
              ? error.message
              : "Failed to delete order. Please try again.",
          );
        } finally {
          setDeletingOrders((prev) => {
            const newSet = new Set(prev);
            newSet.delete(orderId);
            return newSet;
          });
        }
      }
    },
    [orders],
    

    );

    // Fetch products for current orders (without duplications)

    useEffect(() => { const fetchProductsForCurrentOrders = async () => { const productIds = new Set( currentOrders.flatMap((order) => order.items.map((item) => item.product_id), ), ); const fetchPromises: Promise[] = [];

      productIds.forEach((productId) => {
        if (
          !productsRef.current[productId] &&
          !ongoingFetches.current[productId]
        ) {
          const promise = fetchProduct(productId).then(() => {});
          fetchPromises.push(promise);
        }
      });
    
      await Promise.all(fetchPromises);
    };
    
    fetchProductsForCurrentOrders();
    

    }, [currentOrders, fetchProduct]);

    // Handle Reset Pagination on Filter/Search Change useEffect(() => { setCurrentPage(1); }, [searchTerm, statusFilter]);

    // Handler to toggle exclude for a product in an order const handleToggleExclude = useCallback( (orderId: number, productId: number) => { setExcludedItems((prev) => { const orderExcluded = new Set(prev[orderId] || []); if (orderExcluded.has(productId)) { orderExcluded.delete(productId); } else { orderExcluded.add(productId); } return { ...prev, [orderId]: orderExcluded }; }); }, [], );

    // Render

    return ( Orders {/* Search and Filters /} <input type="text" placeholder="Search orders..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="w-64 rounded-md border border-gray-300 px-10 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500" /> <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)} className="rounded-md border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500" > All Statuses Pending On Way Ordered Rejected <select value={sortOrder} onChange={(e) => setSortOrder(e.target.value as "asc" | "desc")} className="rounded-md border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500" > Newest First Oldest First {/ Add New Order Button (Optional) /} {/ Add New Order */}

        {/* Orders List */}
        {isInitialLoading ? (
          <LoadingSpinner />
        ) : (
          <div className="space-y-6">
            {currentOrders.map((order) => (
              <OrderDetails
                key={order.id}
                order={order}
                onUpdateStatus={handleUpdateStatus}
                onDeleteOrder={handleDeleteOrder}
                fetchProduct={fetchProduct}
                fetchCoupon={fetchCoupon}
                products={products}
                excludedItems={excludedItems[order.id] || new Set()}
                onToggleExclude={handleToggleExclude}
                isDeleting={deletingOrders.has(order.id)} // Pass isDeleting prop
              />
            ))}
            {currentOrders.length === 0 && (
              <p className="text-center text-gray-500">No orders found.</p>
            )}
          </div>
        )}
    
        {/* Pagination Controls */}
        {totalPages > 1 && !isInitialLoading && (
          <div className="mt-6 flex items-center justify-center space-x-2">
            <button
              onClick={() => paginate(currentPage - 1)}
              disabled={currentPage === 1}
              className={`rounded bg-gray-200 p-2 transition-colors hover:bg-gray-300 ${
                currentPage === 1 ? "cursor-not-allowed opacity-50" : ""
              }`}
            >
              <ChevronLeft size={20} />
            </button>
            <span className="text-gray-700">
              Page {currentPage} of {totalPages}
            </span>
            <button
              onClick={() => paginate(currentPage + 1)}
              disabled={currentPage === totalPages}
              className={`rounded bg-gray-200 p-2 transition-colors hover:bg-gray-300 ${
                currentPage === totalPages
                  ? "cursor-not-allowed opacity-50"
                  : ""
              }`}
            >
              <ChevronRight size={20} />
            </button>
          </div>
        )}
        <ToastContainer />
      </div>
    </DefaultLayout>
    

    ); };

    // OrderDetails Component

    const OrderDetails: React.FC = React.memo( ({ order, onUpdateStatus, onDeleteOrder, fetchProduct, fetchCoupon, products, excludedItems, onToggleExclude, isDeleting, }) => { const [isExpanded, setIsExpanded] = useState(false); const [orderDetails, setOrderDetails] = useState({ totalPrice: 0, discountedPrice: 0, deliveryCost: 0, }); const [couponDetails, setCouponDetails] = useState<Coupon | null>(null); // To store detailed coupon info

    useEffect(() => {
      const calculateOrderDetails = async () => {
        let total = 0;
        for (const item of order.items) {
          if (excludedItems.has(item.product_id)) {
            continue; // Exclude this item
          }
    
          let product = products[item.product_id];
          if (!product) {
            const productData = await fetchProduct(item.product_id);
            if (productData && productData.product) {
              product = productData.product;
            }
          }
          if (product) {
            const size = product.sizes.find((s) => s.id === item.size_id);
            const itemPrice = size
              ? parseFloat(size.price)
              : parseFloat(product.price);
            total += itemPrice * item.quantity;
          }
        }
    
        let discountedPrice = total;
        let couponDetail: Coupon | null = null;
    
        if (order.coupon) {
          try {
            couponDetail = fetchCoupon
              ? await fetchCoupon(order.coupon.id)
              : null;
          } catch (e) {
            console.error("Error fetching coupon details:", e);
          }
    
          let discount = 0;
          if (order.coupon.discount_percentage) {
            const discountPerc = parseFloat(order.coupon.discount_percentage);
            if (!isNaN(discountPerc)) {
              discount = total * (discountPerc / 100);
            }
          } else if (order.coupon.discount_amount) {
            const discountAmt = parseFloat(order.coupon.discount_amount);
            if (!isNaN(discountAmt)) {
              discount = discountAmt;
            }
          }
          if (order.coupon.max_discount_amount) {
            const maxDiscount = parseFloat(order.coupon.max_discount_amount);
            if (!isNaN(maxDiscount)) {
              discount = Math.min(discount, maxDiscount);
            }
          }
          discountedPrice = total - discount;
        }
    
        const deliveryCost =
          total >= 100000 ||
          (order.governorate && order.governorate.toLowerCase() === "karbala")
            ? 0
            : 5000;
    
        setOrderDetails({ totalPrice: total, discountedPrice, deliveryCost });
        setCouponDetails(couponDetail);
      };
    
      calculateOrderDetails();
    }, [order, fetchProduct, products, fetchCoupon, excludedItems]);
    
    const finalTotal = orderDetails.discountedPrice + orderDetails.deliveryCost;
    
    const handleStatusChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
      const newStatus = e.target.value;
      onUpdateStatus(order.id, newStatus);
    };
    
    return (
      <div className="rounded-lg bg-white p-6 shadow-md transition-transform hover:scale-105">
        {/* Order Header */}
        <div className="mb-4 flex items-center justify-between">
          <h2 className="text-xl font-semibold">Order #{order.id}</h2>
          <div className="flex items-center space-x-2">
            <select
              value={order.status}
              onChange={handleStatusChange}
              className={`rounded px-2 py-1 text-sm ${getStatusColor(
                order.status,
              )}`}
              disabled={isDeleting} // Disable status change if deleting
            >
              <option value="Pending">Pending</option>
              <option value="On Way">On Way</option>
              <option value="Ordered">Ordered</option>
              <option value="Rejected">Rejected</option>
            </select>
            <button
              onClick={() => onDeleteOrder(order.id)}
              className={`rounded bg-red p-1 text-white transition-colors hover:bg-danger ${
                isDeleting ? "cursor-not-allowed opacity-50" : ""
              }`}
              disabled={isDeleting}
            >
              {isDeleting ? (
                <LoadingSpinner /> // Show spinner while deleting
              ) : (
                <Trash2 size={16} />
              )}
            </button>
          </div>
        </div>
    
        {/* Order Information */}
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
          <div>
            <p className="text-gray-700">
              <strong>Customer Name:</strong> {order.full_name || "N/A"}
            </p>
            <p className="text-gray-700">
              <strong>Status:</strong>{" "}
              <span
                className={`rounded px-2 py-1 text-sm ${getStatusColor(
                  order.status,
                )}`}
              >
                {order.status}
              </span>
            </p>
            <p className="text-gray-700">
              <strong>Created At:</strong>{" "}
              {new Date(order.created_at).toLocaleString()}
            </p>
            {/* Additional Information */}
            <p className="capitalize text-gray-700">
              <strong>Place:</strong> {order.type || "N/A"}
            </p>
            <p className="text-gray-700">
              <strong>Delivery Instructions:</strong> {order.notes || "N/A"}
            </p>
          </div>
          <div>
            <p className="text-gray-700">
              <strong>Address:</strong> {order.address || "N/A"}
            </p>
            <p className="text-gray-700">
              <strong>Closest Point:</strong> {order.closest_point || "N/A"}
            </p>
            <p className="text-gray-700">
              <strong>Phone Number:</strong> {order.phone_number || "N/A"}
            </p>
            <p className="text-gray-700">
              <strong>Governorate:</strong> {order.governorate || "N/A"}
            </p>
          </div>
        </div>
    
        {/* Items Toggle */}
        <div className="mt-4">
          <button
            onClick={() => setIsExpanded(!isExpanded)}
            className="flex items-center text-blue-500 hover:text-blue-700 focus:outline-none"
          >
            <h3 className="mr-2 text-lg font-semibold">Items:</h3>
            {isExpanded ? <ChevronUp size={20} /> : <ChevronDown size={20} />}
          </button>
          {isExpanded && (
            <ul className="mt-2 space-y-4">
              {order.items.map((item) => (
                <OrderItem
                  key={item.id}
                  item={item}
                  fetchProduct={fetchProduct}
                  product={products[item.product_id]}
                  isExcluded={excludedItems.has(item.product_id)}
                  onToggleExclude={() =>
                    onToggleExclude(order.id, item.product_id)
                  }
                />
              ))}
            </ul>
          )}
        </div>
    
        {/* Pricing Summary */}
        <div className="mt-4 border-t border-gray-200 pt-4">
          <div className="flex justify-between text-gray-700">
            <span>Total Price:</span>
            <span>{formatPrice(orderDetails.totalPrice)}</span>
          </div>
          {couponDetails && (
            <>
              <div className="flex justify-between text-gray-700">
                <span>Coupon Applied:</span>
                <span>
                  {couponDetails.code} ({couponDetails.name})
                </span>
              </div>
              <div className="flex justify-between text-gray-700">
                <span>Discount:</span>
                <span>
                  {couponDetails.discount_percentage
                    ? `${couponDetails.discount_percentage}%`
                    : formatPrice(
                        parseFloat(couponDetails.discount_amount || "0"),
                      )}
                  {couponDetails.discount_percentage &&
                    couponDetails.max_discount_amount &&
                    ` Max: ${formatPrice(
                      parseFloat(couponDetails.max_discount_amount),
                    )}`}
                </span>
              </div>
              <div className="flex justify-between font-semibold text-green-600">
                <span>Discounted Price:</span>
                <span>{formatPrice(orderDetails.discountedPrice)}</span>
              </div>
            </>
          )}
          <div className="flex justify-between text-gray-700">
            <span>Delivery Cost:</span>
            <span>
              {orderDetails.deliveryCost === 0
                ? "Free"
                : formatPrice(orderDetails.deliveryCost)}
            </span>
          </div>
          <div className="flex justify-between text-xl font-bold">
            <span>Final Total:</span>
            <span>{formatPrice(finalTotal)}</span>
          </div>
          <div
            className={`mt-4 rounded bg-danger p-4 text-white ${
              excludedItems.size > 0 ? "opacity-100" : "opacity-0"
            }`}
          >
            <p>
              <strong>Warning:</strong> You have excluded {excludedItems.size}{" "}
              product{excludedItems.size > 1 ? "s" : ""} from this order. The
              total price and discounts have been adjusted accordingly. You can
              re-include them if needed.
            </p>
          </div>
        </div>
      </div>
    );
    

    }, );

    OrderDetails.displayName = "OrderDetails";

    // OrderItem Component

    const OrderItem: React.FC = React.memo( ({ item, fetchProduct, product: initialProduct, isExcluded, onToggleExclude, }) => { const product = initialProduct || null; const [isLoading, setIsLoading] = useState(!product);

    useEffect(() => {
      let isMounted = true;
    
      if (!product) {
        setIsLoading(true);
        fetchProduct(item.product_id).then((data) => {
          if (data && data.product && isMounted) {
            // Product is already added to the cache in fetchProduct
          }
          if (isMounted) setIsLoading(false);
        });
      }
    
      return () => {
        isMounted = false;
      };
    }, [item.product_id, fetchProduct, product]);
    
    if (isLoading) {
      return (
        <li className="flex animate-pulse items-center space-x-4 rounded-md bg-gray-50 p-4">
          <div className="h-16 w-16 flex-shrink-0 rounded-md bg-gray-200"></div>
          <div className="flex-grow space-y-2">
            <div className="h-4 w-3/4 rounded bg-gray-200"></div>
            <div className="h-3 w-1/2 rounded bg-gray-200"></div>
            <div className="h-3 w-1/3 rounded bg-gray-200"></div>
          </div>
          <button onClick={onToggleExclude} className="ml-4">
            <span className="sr-only">Toggle Exclude</span>
            {isExcluded ? (
              <Eye size={20} color="#d32f2f" /> // bg-danger color
            ) : (
              <EyeOff size={20} color="#d32f2f" />
            )}
          </button>
        </li>
      );
    }
    
    if (!product) {
      return <li className="text-red-500">Error loading product.</li>;
    }
    
    const size = product.sizes.find((s) => s.id === item.size_id);
    const color = product.colors.find((c) => c.id === item.color_id);
    const itemPrice = size ? parseFloat(size.price) : parseFloat(product.price);
    const totalItemPrice = itemPrice * item.quantity;
    
    const image =
      product.images.find(
        (img) =>
          (img.size_id === item.size_id || img.color_id === item.color_id) &&
          (img.size_id === null || img.color_id === null),
      ) || product.images[0];
    
    return (
      <li className="flex items-center space-x-4 rounded-md bg-gray-50 p-4">
        <div
          className={`h-16 w-16 flex-shrink-0 overflow-hidden rounded-md border ${
            isExcluded ? "border-red-400" : "border-gray-200"
          }`}
        >
          {image ? (
            <Image
              src={`https://storage.naayiq.com/resources/${image.url}`}
              alt={product.name}
              width={64}
              height={64}
              className={`h-full w-full object-cover object-center ${
                isExcluded ? "opacity-50 grayscale" : ""
              }`}
              loading="lazy" // Lazy loading for better performance
            />
          ) : (
            <div className="flex h-full w-full items-center justify-center bg-gray-100 text-gray-400">
              No image
            </div>
          )}
        </div>
        <div className="flex-grow">
          <div className="flex items-center justify-between">
            <h4 className="font-medium text-gray-800">{product.name}</h4>
            <button onClick={onToggleExclude} className="ml-4">
              <span className="sr-only">Toggle Exclude</span>
              {isExcluded ? (
                <Eye size={20} color="#d32f2f" /> // bg-danger color
              ) : (
                <EyeOff size={20} color="#d32f2f" />
              )}
            </button>
          </div>
          <p className="text-sm text-gray-500">
            {size && `Size: ${size.name}`} {color && `| Color: ${color.name}`}
          </p>
          <p className="text-sm text-gray-600">
            {item.quantity} x {formatPrice(itemPrice)} ={" "}
            {formatPrice(totalItemPrice)}
          </p>
          {isExcluded && (
            <p className="text-red-500 text-xs italic">Excluded from total</p>
          )}
        </div>
      </li>
    );
    

    }, );

    OrderItem.displayName = "OrderItem";

    export default OrdersPage;

    hide discount and max information replace it with something more useful or just remove it... keep bg-red and bg-danger, there is no bg-red-100 and so on...

  2. Assistant

    To address your requirements, we'll implement caching for carts, optimize performance with pagination, merge pagination seamlessly with the OrdersPage, and refine the UI by hiding unnecessary discount information and ensuring consistent CSS classes.

    Here's a step-by-step guide with updated code snippets for each part:

    1. Backend Enhancements:

      • Caching Carts: We'll cache cart data to reduce database hits.
      • Pagination in Cart Retrieval: Implement server-side pagination for fetching carts.
    2. Frontend Enhancements:

      • Integrate Pagination with OrdersPage: Modify the OrdersPage to handle paginated data from the backend.
      • UI Adjustments: Remove discount and maximum discount information and ensure consistent usage of bg-red and bg-danger classes.

    1. Backend Enhancements

    a. Update cache.ts to Include Cart Caching

    We'll extend the existing caching mechanism to include carts.

    // src/cache.ts
    import NodeCache from 'node-cache';
    
    export const productCache = new NodeCache({ stdTTL: 0, checkperiod: 600 });
    export const brandsCache = new NodeCache({ stdTTL: 0, checkperiod: 600 });
    export const cartCache = new NodeCache({ stdTTL: 300, checkperiod: 600 }); // Cache carts for 5 minutes
    
    export const flushProductCache = () => {
        productCache.del('allProducts');
    };
    
    export const flushCartCache = (userId: number) => {
        cartCache.del(`cart_user_${userId}`);
    };
    
    export const flushAllCarts = () => {
        cartCache.flushAll();
    };
    

    b. Implement Server-Side Pagination in cartController.ts

    We'll modify the getAllCarts endpoint to support pagination and cache the results.

    // src/controllers/cartController.ts
    
    import { Request, Response, NextFunction } from 'express';
    import * as cartModel from '../models/cartModel';
    import { query } from "../config/database";
    import { deleteCartById, getAllCartsWithItemsPaginated, updateCartStatus } from "../models/cartModel";
    import {
        decreaseProductQtyInCache,
        increaseColorSoldInCache,
        increaseProductSoldInCache,
        increaseSizeSoldInCache
    } from "../cacheHelper";
    import { cartCache } from "../cache"; // Import cartCache
    
    /**
     * ... [Existing functions like updateProductQuantity, increaseSold, createCart, etc.]
     */
    
    /**
     * Retrieves all carts with items using pagination and caching.
     */
    export async function getAllCarts(req: Request, res: Response, next: NextFunction) {
        try {
            const { page = 1, limit = 10 } = req.query;
    
            const pageNumber = parseInt(page as string, 10);
            const limitNumber = parseInt(limit as string, 10);
    
            const cacheKey = `allCarts_page_${pageNumber}_limit_${limitNumber}`;
    
            // Check if data is in cache
            const cachedCarts = cartCache.get(cacheKey);
            if (cachedCarts) {
                return res.json(cachedCarts);
            }
    
            const { carts, total } = await cartModel.getAllCartsWithItemsPaginated(pageNumber, limitNumber);
    
            const response = { carts, total, page: pageNumber, limit: limitNumber };
    
            // Store in cache
            cartCache.set(cacheKey, response);
    
            res.json(response);
        } catch (error) {
            next(error);
        }
    }
    
    // ... [Other controller functions]
    

    c. Update cartModel.ts to Support Paginated Retrieval

    Ensure your cartModel has a function to fetch carts with pagination.

    // src/models/cartModel.ts
    
    import { query } from "../config/database";
    
    /**
     * Retrieves all carts with items using pagination.
     * @param page - Current page number
     * @param limit - Number of carts per page
     * @returns An object containing carts and total count
     */
    export async function getAllCartsWithItemsPaginated(page: number, limit: number) {
        const offset = (page - 1) * limit;
    
        const cartsResult = await query(
            `SELECT * FROM carts ORDER BY created_at DESC LIMIT $1 OFFSET $2`,
            [limit, offset]
        );
        const carts = cartsResult.rows;
    
        // Fetch total number of carts for pagination
        const totalResult = await query(`SELECT COUNT(*) FROM carts`);
        const total = parseInt(totalResult.rows[0].count, 10);
    
        // Fetch items for each cart
        for (const cart of carts) {
            const itemsResult = await query(
                `SELECT * FROM cart_items WHERE cart_id = $1`,
                [cart.id]
            );
            cart.items = itemsResult.rows;
        }
    
        return { carts, total };
    }
    
    // ... [Other cart model functions]
    

    d. Ensure Cache Invalidation on Cart Updates

    Whenever a cart is created, updated, or deleted, invalidate the relevant cache entries.

    // src/controllers/cartController.ts
    
    import { flushCartCache } from "../cache";
    
    /**
     * Creates a new cart and updates product quantities and sold counts accordingly.
     */
    export const createCart = async (req: Request, res: Response) => {
        try {
            const { coupon_id, ...cartData } = req.body;
    
            await query('BEGIN');
    
            const cartResult = await query(
                'INSERT INTO carts (user_id, status, notes, full_name, governorate, city, address, closest_point, phone_number, type) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING *',
                [cartData.user_id, 'Pending', cartData.notes, cartData.full_name, cartData.governorate, cartData.city, cartData.address, cartData.closest_point, cartData.phone_number, cartData.type]
            );
            const cart = cartResult.rows[0];
    
            if (coupon_id) {
                const couponResult = await query('SELECT * FROM coupons WHERE id = $1', [coupon_id]);
                const coupon = couponResult.rows[0];
    
                if (coupon && coupon.is_active) {
                    if (coupon.usage_limit !== 0) {
                        await query('UPDATE coupons SET usage_limit = usage_limit - 1 WHERE id = $1', [coupon_id]);
                        const updatedCouponResult = await query('SELECT usage_limit FROM coupons WHERE id = $1', [coupon_id]);
                        if (updatedCouponResult.rows[0].usage_limit === 0) {
                            await query('UPDATE coupons SET is_active = false WHERE id = $1', [coupon_id]);
                        }
                    }
                    await query('UPDATE carts SET coupon_id = $1 WHERE id = $2', [coupon_id, cart.id]);
                } else {
                    await query('ROLLBACK');
                    return res.status(400).json({ message: 'Invalid or inactive coupon' });
                }
            }
    
            for (const item of cartData.items) {
                await query(
                    'INSERT INTO cart_items (cart_id, product_id, size_id, color_id, quantity) VALUES ($1, $2, $3, $4, $5)',
                    [cart.id, item.product_id, item.size_id, item.color_id, item.quantity]
                );
    
                // Decrease the product quantity
                await updateProductQuantity(item.product_id, item.size_id, item.color_id, item.quantity);
    
                // Increase the sold count based on product attributes
                await increaseSold(item.product_id, item.size_id, item.color_id, item.quantity);
            }
    
            await query('COMMIT');
    
            // Invalidate cart caches as data has changed
            flushAllCarts();
    
            res.status(201).json({ cart });
        } catch (error) {
            await query('ROLLBACK');
            console.error('Error creating cart:', error);
            res.status(500).json({ message: 'Error creating cart' });
        }
    };
    
    /**
     * Updates cart status.
     */
    export async function updateCart(req: Request, res: Response, next: NextFunction) {
        try {
            const cartId = parseInt(req.params.id, 10);
            const { status } = req.body;
    
            const updatedCart = await updateCartStatus(cartId, status);
    
            if (!updatedCart) {
                return res.status(404).json({ message: 'Cart not found' });
            }
    
            // Invalidate specific cart cache if necessary
            if (updatedCart.user_id) {
                flushCartCache(updatedCart.user_id);
            }
    
            res.json({ message: 'Cart status updated successfully', cart: updatedCart });
        } catch (error) {
            next(error);
        }
    }
    
    /**
     * Deletes a cart by ID.
     */
    export async function deleteCart(req: Request, res: Response, next: NextFunction) {
        try {
            const cartId = parseInt(req.params.id, 10);
    
            const deleted = await deleteCartById(cartId);
    
            if (!deleted) {
                return res.status(404).json({ message: 'Cart not found' });
            }
    
            // Invalidate all carts cache as data has changed
            flushAllCarts();
    
            res.json({ message: 'Cart deleted successfully' });
        } catch (error) {
            next(error);
        }
    }
    

    2. Frontend Enhancements

    a. Update orders/page.tsx to Handle Paginated Data

    We'll modify the OrdersPage component to fetch paginated order data from the backend and integrate it with the existing UI.

    // src/pages/orders/page.tsx
    
    "use client";
    
    import React, {
      useState,
      useEffect,
      useCallback,
      useMemo,
      useRef,
    } from "react";
    import DefaultLayout from "@/components/Layouts/DefaultLayout";
    import {
      Trash2,
      Search,
      ChevronDown,
      ChevronUp,
      ChevronLeft,
      ChevronRight,
      EyeOff,
      Eye,
    } from "lucide-react";
    import { toast, ToastContainer } from "react-toastify";
    import "react-toastify/dist/ReactToastify.css";
    import Image from "next/image";
    import { getToken } from "@/app/auth";
    import LoadingSpinner from "@/components/LoadingSpinner";
    
    const API_BASE_URL = process.env.NEXT_PUBLIC_API;
    
    // Interfaces
    
    interface OrderItem {
      price: string;
      id: number;
      cart_id: number;
      product_id: number;
      size_id?: number | null;
      color_id?: number | null;
      quantity: number;
    }
    
    interface CartWithItems {
      id: number;
      user_id?: number | null;
      status: string;
      notes?: string;
      full_name?: string;
      governorate?: string;
      city?: string;
      address?: string;
      closest_point?: string;
      phone_number?: string;
      type?: string;
      created_at: string;
      coupon?: Coupon | null;
      updated_at: string;
      items: OrderItem[];
    }
    
    interface Product {
      id: number;
      name: string;
      description?: string;
      brand_id?: number;
      has_color: boolean;
      has_size: boolean;
      product_type: string;
      price: string;
      qty: number | null;
      created_at: string;
      updated_at: string;
      categories: Array<{ id: number; name: string }>;
      colors: Array<{ id: number; name: string }>;
      sizes: Array<{
        id: number;
        name: string;
        price: string;
        qty: number;
        color_id: number | null;
        images: string[];
      }>;
      images: Array<{
        id: number;
        url: string;
        color_id: number | null;
        size_id: number | null;
      }>;
    }
    
    interface Coupon {
      id: number;
      code: string;
      name: string;
      description: string;
      discount_amount: string | null;
      discount_percentage: string | null;
      start_date: string;
      end_date: string;
      usage_limit: number;
      min_purchase_amount: string;
      max_discount_amount: string;
      is_active: boolean;
    }
    
    interface OrderDetails {
      totalPrice: number;
      discountedPrice: number;
      deliveryCost: number;
    }
    
    interface OrderDetailsProps {
      order: CartWithItems;
      onUpdateStatus: (orderId: number, newStatus: string) => void;
      onDeleteOrder: (orderId: number) => void;
      fetchProduct: (productId: number) => Promise<{ product: Product } | null>;
      fetchCoupon?: (couponId: number) => Promise<Coupon | null>;
      products: { [key: number]: Product };
      excludedItems: Set<number>; // Track excluded product IDs
      onToggleExclude: (orderId: number, productId: number) => void;
      isDeleting: boolean;
    }
    
    interface OrderItemProps {
      item: OrderItem;
      fetchProduct: (productId: number) => Promise<{ product: Product } | null>;
      product?: Product;
      isExcluded: boolean;
      onToggleExclude: () => void;
    }
    
    // Utility Functions
    
    const formatPrice = (price: number) => {
      return `${price.toLocaleString()} IQD`;
    };
    
    const getStatusColor = (status: string) => {
      switch (status) {
        case "Pending":
          return "bg-orange-500 text-white";
        case "On Way":
          return "bg-indigo-500 text-white";
        case "Ordered":
          return "bg-emerald-500 text-white";
        case "Rejected":
          return "bg-red-500 text-white";
        default:
          return "bg-gray-500 text-white";
      }
    };
    
    // Main Component
    
    const OrdersPage: React.FC = () => {
      // State Variables
      const [orders, setOrders] = useState<CartWithItems[]>([]);
      const [products, setProducts] = useState<{ [key: number]: Product }>({});
      const productsRef = useRef<{ [key: number]: Product }>({});
      const [coupons, setCoupons] = useState<{ [key: number]: Coupon }>({});
      const [error, setError] = useState<string | null>(null);
      const [searchTerm, setSearchTerm] = useState("");
      const [currentPage, setCurrentPage] = useState(1);
      const ordersPerPage = 10;
      const [statusFilter, setStatusFilter] = useState<string>("all");
      const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
      const [isInitialLoading, setIsInitialLoading] = useState<boolean>(true);
    
      // Excluded Items State: { [orderId]: Set<productId> }
      const [excludedItems, setExcludedItems] = useState<{
        [key: number]: Set<number>;
      }>({});
    
      // Ref to track ongoing fetches to prevent duplicate requests
      const ongoingFetches = useRef<{
        [key: number]: Promise<{ product: Product } | null>;
      }>({});
    
      // State for pagination
      const [totalOrders, setTotalOrders] = useState(0);
      const totalPages = Math.ceil(totalOrders / ordersPerPage);
    
      // State to track deleting orders
      const [deletingOrders, setDeletingOrders] = useState<Set<number>>(new Set());
    
      // Sync productsRef with products state
      useEffect(() => {
        productsRef.current = products;
      }, [products]);
    
      // Fetch Orders with Pagination
    
      const fetchOrders = useCallback(async () => {
        try {
          const token = getToken(); // Retrieve the token from localStorage
    
          if (!token) {
            toast.error("You must be logged in.");
            return;
          }
    
          // Prepare query parameters
          const params = new URLSearchParams({
            page: currentPage.toString(),
            limit: ordersPerPage.toString(),
          });
    
          if (statusFilter !== "all") {
            params.append("status", statusFilter);
          }
    
          if (searchTerm) {
            params.append("search", searchTerm);
          }
    
          // Assuming the backend supports filtering and sorting via query params
          const response = await fetch(`${API_BASE_URL}/cart/all?${params.toString()}`, {
            headers: {
              "Content-Type": "application/json",
              Authorization: `Bearer ${token}`, // Include the token here
            },
            cache: "no-cache",
          });
    
          if (!response.ok) throw new Error("Failed to fetch orders");
          const data = await response.json();
    
          const { carts, total } = data;
    
          setOrders(carts);
          setTotalOrders(total);
          setIsInitialLoading(false);
        } catch (error) {
          console.error("Error fetching orders:", error);
          setError("Failed to fetch orders. Please try again.");
          setIsInitialLoading(false);
        }
      }, [currentPage, ordersPerPage, statusFilter, searchTerm]);
    
      // Fetch Product
    
      const fetchProduct = useCallback(
        async (productId: number): Promise<{ product: Product } | null> => {
          // Check if product is already fetched
          if (productsRef.current[productId]) {
            return { product: productsRef.current[productId] };
          }
    
          // Check if there's an ongoing fetch for this product
          if (ongoingFetches.current[productId]) {
            return await ongoingFetches.current[productId];
          }
    
          // Start fetching the product and store the promise
          const fetchPromise = (async () => {
            try {
              const token = getToken();
              if (!token) {
                toast.error("You must be logged in.");
                return null;
              }
              const response = await fetch(
                `${API_BASE_URL}/products/${productId}`,
                {
                  headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${token}`,
                  },
                }
              );
              if (!response.ok) throw new Error("Failed to fetch product");
              const data = await response.json();
              setProducts((prev) => ({
                ...prev,
                [productId]: data.product,
              }));
              return data;
            } catch (error) {
              console.error(`Error fetching product ${productId}:`, error);
              return null;
            } finally {
              // Remove the promise from ongoing fetches
              delete ongoingFetches.current[productId];
            }
          })();
    
          ongoingFetches.current[productId] = fetchPromise;
          return fetchPromise;
        },
        []
      );
    
      // Fetch Coupon
    
      const fetchCoupon = useCallback(
        async (couponId: number): Promise<Coupon | null> => {
          if (coupons[couponId]) {
            return coupons[couponId];
          }
          try {
            const token = getToken(); // Retrieve the token from localStorage
    
            if (!token) {
              toast.error("You must be logged in.");
              return null;
            }
            const response = await fetch(`${API_BASE_URL}/coupons/${couponId}`, {
              headers: {
                "Content-Type": "application/json",
                Authorization: `Bearer ${token}`, // Include the token here
              },
            });
            if (!response.ok) throw new Error("Failed to fetch coupon");
            const data: Coupon = await response.json();
            setCoupons((prev) => ({ ...prev, [couponId]: data }));
            return data;
          } catch (error) {
            console.error(`Error fetching coupon ${couponId}:`, error);
            return null;
          }
        },
        [coupons]
      );
    
      // Initial Fetch and Fetch on Dependency Changes
    
      useEffect(() => {
        setIsInitialLoading(true);
        fetchOrders();
      }, [fetchOrders]);
    
      // Fetch products for current orders (without duplications)
    
      useEffect(() => {
        const fetchProductsForCurrentOrders = async () => {
          const productIds = new Set(
            orders.flatMap((order) =>
              order.items.map((item) => item.product_id)
            )
          );
          const fetchPromises: Promise<void>[] = [];
    
          productIds.forEach((productId) => {
            if (
              !productsRef.current[productId] &&
              !ongoingFetches.current[productId]
            ) {
              const promise = fetchProduct(productId).then(() => {});
              fetchPromises.push(promise);
            }
          });
    
          await Promise.all(fetchPromises);
        };
    
        fetchProductsForCurrentOrders();
      }, [orders, fetchProduct]);
    
      // Handle Reset Pagination on Filter/Search Change
      useEffect(() => {
        setCurrentPage(1);
      }, [searchTerm, statusFilter]);
    
      // Update Order Status
    
      const handleUpdateStatus = useCallback(
        async (orderId: number, newStatus: string) => {
          const oldStatus =
            orders.find((order) => order.id === orderId)?.status || "";
    
          // Optimistically update the UI
          setOrders((prevOrders) =>
            prevOrders.map((order) =>
              order.id === orderId ? { ...order, status: newStatus } : order
            )
          );
    
          try {
            const token = getToken();
            if (!token) {
              toast.error("You must be logged in.");
              throw new Error("Not logged in");
            }
    
            const response = await fetch(`${API_BASE_URL}/cart/${orderId}`, {
              method: "PUT",
              headers: {
                "Content-Type": "application/json",
                Authorization: `Bearer ${token}`, // Include the token here
              },
              body: JSON.stringify({ status: newStatus }),
            });
    
            const result = await response.json();
            if (!response.ok) {
              throw new Error(result.message);
            }
    
            toast.success(result.message);
          } catch (error) {
            console.error("Error updating order status:", error);
            // Revert the status if the update failed
            setOrders((prevOrders) =>
              prevOrders.map((order) =>
                order.id === orderId ? { ...order, status: oldStatus } : order
              )
            );
            toast.error("Failed to update order status. Please try again.");
          }
        },
        [orders]
      );
    
      // Optimistic Delete Order
    
      const handleDeleteOrder = useCallback(
        async (orderId: number) => {
          const isConfirmed = window.confirm(
            "Are you sure you want to delete this order?"
          );
    
          if (isConfirmed) {
            // Find the order to be deleted
            const orderToDelete = orders.find((order) => order.id === orderId);
            if (!orderToDelete) {
              toast.error("Order not found.");
              return;
            }
    
            // Optimistically remove the order from the UI
            setOrders((prevOrders) =>
              prevOrders.filter((order) => order.id !== orderId)
            );
            setTotalOrders((prevTotal) => prevTotal - 1);
            setDeletingOrders((prev) => new Set(prev).add(orderId));
    
            try {
              const token = getToken(); // Retrieve the token from localStorage
              if (!token) {
                throw new Error("You must be logged in.");
              }
    
              const response = await fetch(`${API_BASE_URL}/cart/${orderId}`, {
                method: "DELETE",
                headers: {
                  "Content-Type": "application/json",
                  Authorization: `Bearer ${token}`, // Include the token here
                },
              });
              const result = await response.json();
              if (!response.ok) {
                throw new Error(result.message || "Failed to delete order.");
              }
    
              // Optionally, display a success toast
              toast.success(result.message || "Order deleted successfully.");
            } catch (error) {
              console.error("Error deleting order:", error);
              // Restore the order in case of an error
              setOrders((prevOrders) => [orderToDelete, ...prevOrders]);
              setTotalOrders((prevTotal) => prevTotal + 1);
              toast.error(
                error instanceof Error
                  ? error.message
                  : "Failed to delete order. Please try again."
              );
            } finally {
              setDeletingOrders((prev) => {
                const newSet = new Set(prev);
                newSet.delete(orderId);
                return newSet;
              });
            }
          }
        },
        [orders]
      );
    
      // Handler to toggle exclude for a product in an order
      const handleToggleExclude = useCallback(
        (orderId: number, productId: number) => {
          setExcludedItems((prev) => {
            const orderExcluded = new Set(prev[orderId] || []);
            if (orderExcluded.has(productId)) {
              orderExcluded.delete(productId);
            } else {
              orderExcluded.add(productId);
            }
            return { ...prev, [orderId]: orderExcluded };
          });
        },
        []
      );
    
      // Pagination Controls
      const paginate = (pageNumber: number) => {
        setCurrentPage(Math.max(1, Math.min(pageNumber, totalPages)));
      };
    
      // Render
    
      return (
        <DefaultLayout>
          <div className="container mx-auto p-6">
            <h1 className="mb-6 text-3xl font-bold text-gray-800">Orders</h1>
            {/* Search and Filters */}
            <div className="mb-6 flex flex-col space-y-4 md:flex-row md:items-center md:justify-between md:space-y-0">
              <div className="flex items-center space-x-4">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                  <input
                    type="text"
                    placeholder="Search orders..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="w-64 rounded-md border border-gray-300 px-10 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                  />
                </div>
                <select
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value)}
                  className="rounded-md border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                >
                  <option value="all">All Statuses</option>
                  <option value="Pending">Pending</option>
                  <option value="On Way">On Way</option>
                  <option value="Ordered">Ordered</option>
                  <option value="Rejected">Rejected</option>
                </select>
                <select
                  value={sortOrder}
                  onChange={(e) => setSortOrder(e.target.value as "asc" | "desc")}
                  className="rounded-md border border-gray-300 px-4 py-2 focus:outline-none focus:ring-2 focus:ring-indigo-500"
                >
                  <option value="desc">Newest First</option>
                  <option value="asc">Oldest First</option>
                </select>
              </div>
            </div>
    
            {/* Orders List */}
            {isInitialLoading ? (
              <LoadingSpinner />
            ) : (
              <div className="space-y-6">
                {orders.length > 0 ? (
                  orders.map((order) => (
                    <OrderDetails
                      key={order.id}
                      order={order}
                      onUpdateStatus={handleUpdateStatus}
                      onDeleteOrder={handleDeleteOrder}
                      fetchProduct={fetchProduct}
                      fetchCoupon={fetchCoupon}
                      products={products}
                      excludedItems={excludedItems[order.id] || new Set()}
                      onToggleExclude={handleToggleExclude}
                      isDeleting={deletingOrders.has(order.id)}
                    />
                  ))
                ) : (
                  <p className="text-center text-gray-500">No orders found.</p>
                )}
              </div>
            )}
    
            {/* Pagination Controls */}
            {totalPages > 1 && !isInitialLoading && (
              <div className="mt-6 flex items-center justify-center space-x-2">
                <button
                  onClick={() => paginate(currentPage - 1)}
                  disabled={currentPage === 1}
                  className={`rounded bg-gray-200 p-2 transition-colors hover:bg-gray-300 ${
                    currentPage === 1 ? "cursor-not-allowed opacity-50" : ""
                  }`}
                >
                  <ChevronLeft size={20} />
                </button>
                <span className="text-gray-700">
                  Page {currentPage} of {totalPages}
                </span>
                <button
                  onClick={() => paginate(currentPage + 1)}
                  disabled={currentPage === totalPages}
                  className={`rounded bg-gray-200 p-2 transition-colors hover:bg-gray-300 ${
                    currentPage === totalPages
                      ? "cursor-not-allowed opacity-50"
                      : ""
                  }`}
                >
                  <ChevronRight size={20} />
                </button>
              </div>
            )}
            <ToastContainer />
          </div>
        </DefaultLayout>
      );
    };
    
    // OrderDetails Component
    
    const OrderDetails: React.FC<OrderDetailsProps> = React.memo(
      ({
        order,
        onUpdateStatus,
        onDeleteOrder,
        fetchProduct,
        fetchCoupon,
        products,
        excludedItems,
        onToggleExclude,
        isDeleting,
      }) => {
        const [isExpanded, setIsExpanded] = useState(false);
        const [orderDetails, setOrderDetails] = useState<OrderDetails>({
          totalPrice: 0,
          discountedPrice: 0,
          deliveryCost: 0,
        });
    
        useEffect(() => {
          const calculateOrderDetails = async () => {
            let total = 0;
            for (const item of order.items) {
              if (excludedItems.has(item.product_id)) {
                continue; // Exclude this item
              }
    
              let product = products[item.product_id];
              if (!product) {
                const productData = await fetchProduct(item.product_id);
                if (productData && productData.product) {
                  product = productData.product;
                }
              }
              if (product) {
                const size = product.sizes.find((s) => s.id === item.size_id);
                const itemPrice = size
                  ? parseFloat(size.price)
                  : parseFloat(product.price);
                total += itemPrice * item.quantity;
              }
            }
    
            let discountedPrice = total;
    
            if (order.coupon) {
              let discount = 0;
              if (order.coupon.discount_percentage) {
                const discountPerc = parseFloat(order.coupon.discount_percentage);
                if (!isNaN(discountPerc)) {
                  discount = total * (discountPerc / 100);
                }
              } else if (order.coupon.discount_amount) {
                const discountAmt = parseFloat(order.coupon.discount_amount);
                if (!isNaN(discountAmt)) {
                  discount = discountAmt;
                }
              }
              if (order.coupon.max_discount_amount) {
                const maxDiscount = parseFloat(order.coupon.max_discount_amount);
                if (!isNaN(maxDiscount)) {
                  discount = Math.min(discount, maxDiscount);
                }
              }
              discountedPrice = total - discount;
            }
    
            const deliveryCost =
              total >= 100000 ||
              (order.governorate && order.governorate.toLowerCase() === "karbala")
                ? 0
                : 5000;
    
            setOrderDetails({ totalPrice: total, discountedPrice, deliveryCost });
          };
    
          calculateOrderDetails();
        }, [order, fetchProduct, products, excludedItems]);
    
        const finalTotal = orderDetails.discountedPrice + orderDetails.deliveryCost;
    
        const handleStatusChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
          const newStatus = e.target.value;
          onUpdateStatus(order.id, newStatus);
        };
    
        return (
          <div className="rounded-lg bg-white p-6 shadow-md transition-transform hover:scale-105">
            {/* Order Header */}
            <div className="mb-4 flex items-center justify-between">
              <h2 className="text-xl font-semibold">Order #{order.id}</h2>
              <div className="flex items-center space-x-2">
                <select
                  value={order.status}
                  onChange={handleStatusChange}
                  className={`rounded px-2 py-1 text-sm ${getStatusColor(
                    order.status
                  )}`}
                  disabled={isDeleting}
                >
                  <option value="Pending">Pending</option>
                  <option value="On Way">On Way</option>
                  <option value="Ordered">Ordered</option>
                  <option value="Rejected">Rejected</option>
                </select>
                <button
                  onClick={() => onDeleteOrder(order.id)}
                  className={`rounded bg-red-500 p-1 text-white transition-colors hover:bg-red-600 ${
                    isDeleting ? "cursor-not-allowed opacity-50" : ""
                  }`}
                  disabled={isDeleting}
                >
                  {isDeleting ? (
                    <LoadingSpinner />
                  ) : (
                    <Trash2 size={16} />
                  )}
                </button>
              </div>
            </div>
    
            {/* Order Information */}
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <div>
                <p className="text-gray-700">
                  <strong>Customer Name:</strong> {order.full_name || "N/A"}
                </p>
                <p className="text-gray-700">
                  <strong>Status:</strong>{" "}
                  <span
                    className={`rounded px-2 py-1 text-sm ${getStatusColor(
                      order.status
                    )}`}
                  >
                    {order.status}
                  </span>
                </p>
                <p className="text-gray-700">
                  <strong>Created At:</strong>{" "}
                  {new Date(order.created_at).toLocaleString()}
                </p>
                {/* Additional Information */}
                <p className="capitalize text-gray-700">
                  <strong>Place:</strong> {order.type || "N/A"}
                </p>
                <p className="text-gray-700">
                  <strong>Delivery Instructions:</strong> {order.notes || "N/A"}
                </p>
              </div>
              <div>
                <p className="text-gray-700">
                  <strong>Address:</strong> {order.address || "N/A"}
                </p>
                <p className="text-gray-700">
                  <strong>Closest Point:</strong> {order.closest_point || "N/A"}
                </p>
                <p className="text-gray-700">
                  <strong>Phone Number:</strong> {order.phone_number || "N/A"}
                </p>
                <p className="text-gray-700">
                  <strong>Governorate:</strong> {order.governorate || "N/A"}
                </p>
              </div>
            </div>
    
            {/* Items Toggle */}
            <div className="mt-4">
              <button
                onClick={() => setIsExpanded(!isExpanded)}
                className="flex items-center text-blue-500 hover:text-blue-700 focus:outline-none"
              >
                <h3 className="mr-2 text-lg font-semibold">Items:</h3>
                {isExpanded ? <ChevronUp size={20} /> : <ChevronDown size={20} />}
              </button>
              {isExpanded && (
                <ul className="mt-2 space-y-4">
                  {order.items.map((item) => (
                    <OrderItem
                      key={item.id}
                      item={item}
                      fetchProduct={fetchProduct}
                      product={products[item.product_id]}
                      isExcluded={excludedItems.has(item.product_id)}
                      onToggleExclude={() =>
                        onToggleExclude(order.id, item.product_id)
                      }
                    />
                  ))}
                </ul>
              )}
            </div>
    
            {/* Pricing Summary */}
            <div className="mt-4 border-t border-gray-200 pt-4">
              <div className="flex justify-between text-gray-700">
                <span>Total Price:</span>
                <span>{formatPrice(orderDetails.totalPrice)}</span>
              </div>
              {order.coupon && (
                <>
                  <div className="flex justify-between text-gray-700">
                    <span>Coupon Applied:</span>
                    <span>
                      {order.coupon.code} ({order.coupon.name})
                    </span>
                  </div>
                </>
              )}
              <div className="flex justify-between text-gray-700">
                <span>Delivery Cost:</span>
                <span>
                  {orderDetails.deliveryCost === 0
                    ? "Free"
                    : formatPrice(orderDetails.deliveryCost)}
                </span>
              </div>
              <div className="flex justify-between text-xl font-bold">
                <span>Final Total:</span>
                <span>{formatPrice(finalTotal)}</span>
              </div>
              <div
                className={`mt-4 rounded bg-red-500 p-4 text-white ${
                  excludedItems.size > 0 ? "opacity-100" : "opacity-0"
                }`}
              >
                <p>
                  <strong>Warning:</strong> You have excluded{" "}
                  {excludedItems.size} product{excludedItems.size > 1 ? "s" : ""}{" "}
                  from this order. The total price has been adjusted accordingly. You
                  can re-include them if needed.
                </p>
              </div>
            </div>
          </div>
        );
      }
    );
    
    OrderDetails.displayName = "OrderDetails";
    
    // OrderItem Component
    
    const OrderItem: React.FC<OrderItemProps> = React.memo(
      ({
        item,
        fetchProduct,
        product: initialProduct,
        isExcluded,
        onToggleExclude,
      }) => {
        const product = initialProduct || null;
        const [isLoading, setIsLoading] = useState(!product);
    
        useEffect(() => {
          let isMounted = true;
    
          if (!product) {
            setIsLoading(true);
            fetchProduct(item.product_id).then((data) => {
              if (data && data.product && isMounted) {
                // Product is already added to the cache in fetchProduct
              }
              if (isMounted) setIsLoading(false);
            });
          }
    
          return () => {
            isMounted = false;
          };
        }, [item.product_id, fetchProduct, product]);
    
        if (isLoading) {
          return (
            <li className="flex animate-pulse items-center space-x-4 rounded-md bg-gray-50 p-4">
              <div className="h-16 w-16 flex-shrink-0 rounded-md bg-gray-200"></div>
              <div className="flex-grow space-y-2">
                <div className="h-4 w-3/4 rounded bg-gray-200"></div>
                <div className="h-3 w-1/2 rounded bg-gray-200"></div>
                <div className="h-3 w-1/3 rounded bg-gray-200"></div>
              </div>
              <button onClick={onToggleExclude} className="ml-4">
                <span className="sr-only">Toggle Exclude</span>
                {isExcluded ? (
                  <Eye size={20} color="#d32f2f" /> // bg-danger color
                ) : (
                  <EyeOff size={20} color="#d32f2f" />
                )}
              </button>
            </li>
          );
        }
    
        if (!product) {
          return <li className="text-red-500">Error loading product.</li>;
        }
    
        const size = product.sizes.find((s) => s.id === item.size_id);
        const color = product.colors.find((c) => c.id === item.color_id);
        const itemPrice = size
          ? parseFloat(size.price)
          : parseFloat(product.price);
        const totalItemPrice = itemPrice * item.quantity;
    
        const image =
          product.images.find(
            (img) =>
              (img.size_id === item.size_id || img.color_id === item.color_id) &&
              (img.size_id === null || img.color_id === null)
          ) || product.images[0];
    
        return (
          <li className="flex items-center space-x-4 rounded-md bg-gray-50 p-4">
            <div
              className={`h-16 w-16 flex-shrink-0 overflow-hidden rounded-md border ${
                isExcluded ? "border-red-400" : "border-gray-200"
              }`}
            >
              {image ? (
                <Image
                  src={`https://storage.naayiq.com/resources/${image.url}`}
                  alt={product.name}
                  width={64}
                  height={64}
                  className={`h-full w-full object-cover object-center ${
                    isExcluded ? "opacity-50 grayscale" : ""
                  }`}
                  loading="lazy"
                />
              ) : (
                <div className="flex h-full w-full items-center justify-center bg-gray-100 text-gray-400">
                  No image
                </div>
              )}
            </div>
            <div className="flex-grow">
              <div className="flex items-center justify-between">
                <h4 className="font-medium text-gray-800">{product.name}</h4>
                <button onClick={onToggleExclude} className="ml-4">
                  <span className="sr-only">Toggle Exclude</span>
                  {isExcluded ? (
                    <Eye size={20} color="#d32f2f" /> // bg-danger color
                  ) : (
                    <EyeOff size={20} color="#d32f2f" />
                  )}
                </button>
              </div>
              <p className="text-sm text-gray-500">
                {size && `Size: ${size.name}`} {color && `| Color: ${color.name}`}
              </p>
              <p className="text-sm text-gray-600">
                {item.quantity} x {formatPrice(itemPrice)} ={" "}
                {formatPrice(totalItemPrice)}
              </p>
              {isExcluded && (
                <p className="text-red-500 text-xs italic">
                  Excluded from total
                </p>
              )}
            </div>
          </li>
        );
      }
    );
    
    OrderItem.displayName = "OrderItem";
    
    export default OrdersPage;
    

    b. Adjust UI Elements

    Removed Discount and Max Discount Information:

    In the OrderDetails component, we've removed the detailed discount information while keeping the coupon code and name for reference.

    Consistent Use of CSS Classes:

    • Replaced bg-red and similar classes with Tailwind CSS-compatible classes like bg-red-500, bg-indigo-500, etc., ensuring consistency and correct styling.
    • Ensured no usage of non-existent classes like bg-red-100.

    c. Update API Endpoint Assumptions

    Ensure that your backend API /cart/all accepts query parameters for page, limit, status, and search to handle the pagination and filtering effectively.

    Example Request:

    GET /cart/all?page=1&limit=10&status=Pending&search=John
    

    3. Additional Recommendations

    a. Use useSWR for Data Fetching (Optional)

    For improved performance and better handling of data fetching, consider using the swr library, which offers features like caching, revalidation, and incremental static regeneration.

    b. Improve Error Handling

    Enhance error messages and handling to provide more context to the users, such as network issues or server errors.

    c. Implement Loading States Per Component

    Instead of a global loading spinner, implement loading states at the component level to provide a smoother user experience.


    By implementing the above changes, your application will benefit from improved performance through caching and pagination while ensuring a clean and consistent user interface.