"use client"; import { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import Layout from "@/components/layout/layout"; import { Button } from "@/components/ui/button"; import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table"; import { Input } from "@/components/ui/input"; import { Product } from "@/models/products"; import { Package, RefreshCw } from "lucide-react"; import { fetchProductData, updateProductStock } from "@/lib/productData"; import { toast } from "sonner"; export default function StockManagementPage() { const router = useRouter(); const [products, setProducts] = useState([]); const [loading, setLoading] = useState(true); const [editingStock, setEditingStock] = useState>({}); const [stockValues, setStockValues] = useState>({}); const [searchTerm, setSearchTerm] = useState(""); useEffect(() => { const authToken = document.cookie .split("; ") .find((row) => row.startsWith("Authorization=")) ?.split("=")[1]; if (!authToken) { router.push("/login"); return; } const fetchDataAsync = async () => { try { const fetchedProducts = await fetchProductData("/api/products", authToken); setProducts(fetchedProducts); // Initialize stock values const initialStockValues: Record = {}; fetchedProducts.forEach((product: Product) => { if (product._id) { initialStockValues[product._id] = product.currentStock || 0; } }); setStockValues(initialStockValues); setLoading(false); } catch (error) { console.error("Error fetching products:", error); setLoading(false); } }; fetchDataAsync(); }, [router]); const handleEditStock = (productId: string) => { setEditingStock({ ...editingStock, [productId]: true, }); }; const handleSaveStock = async (product: Product) => { if (!product._id) return; const authToken = document.cookie .split("; ") .find((row) => row.startsWith("Authorization=")) ?.split("=")[1]; if (!authToken) { router.push("/login"); return; } try { const newStockValue = stockValues[product._id] || 0; await updateProductStock( product._id, { currentStock: newStockValue, stockTracking: product.stockTracking }, authToken ); // Update local products state setProducts(products.map(p => { if (p._id === product._id) { return { ...p, currentStock: newStockValue }; } return p; })); setEditingStock({ ...editingStock, [product._id]: false, }); toast.success("Stock updated successfully"); } catch (error) { console.error("Error updating stock:", error); toast.error("Failed to update stock"); } }; const handleStockChange = (productId: string, value: number) => { setStockValues({ ...stockValues, [productId]: value, }); }; const getStockStatus = (product: Product) => { if (!product.stockTracking) return "Not Tracked"; if (!product.currentStock || product.currentStock <= 0) { return "Out of Stock"; } else if (product.lowStockThreshold && product.currentStock <= product.lowStockThreshold) { return "Low Stock"; } else { return "In Stock"; } }; const filteredProducts = products.filter(product => { const matchesSearch = !searchTerm || product.name.toLowerCase().includes(searchTerm.toLowerCase()); return matchesSearch; }); const statsData = { total: products.length, inStock: products.filter(p => p.stockTracking && p.currentStock && p.currentStock > 0 && (!p.lowStockThreshold || p.currentStock > p.lowStockThreshold)).length, lowStock: products.filter(p => p.stockTracking && p.lowStockThreshold && p.currentStock && p.currentStock <= p.lowStockThreshold && p.currentStock > 0).length, outOfStock: products.filter(p => p.stockTracking && (!p.currentStock || p.currentStock <= 0)).length, notTracked: products.filter(p => p.stockTracking === false).length }; return (

Stock Management

{statsData.total}
Total Products
{statsData.inStock}
In Stock
{statsData.lowStock}
Low Stock
{statsData.outOfStock}
Out of Stock
{statsData.notTracked}
Not Tracked

Inventory List

setSearchTerm(e.target.value)} className="w-64" />
Product Unit Status Current Stock Low Stock Threshold Actions {loading ? ( Loading... ) : filteredProducts.length > 0 ? ( filteredProducts.map((product) => ( {product.name} {product.unitType} {getStockStatus(product)} {editingStock[product._id as string] ? ( handleStockChange(product._id as string, parseFloat(e.target.value))} className="max-w-[100px]" /> ) : ( product.stockTracking ? `${product.currentStock || 0} ${product.unitType}` : "N/A" )} {product.stockTracking ? `${product.lowStockThreshold || 0} ${product.unitType}` : "N/A"} {product.stockTracking && ( editingStock[product._id as string] ? ( ) : ( ) )} )) ) : ( No products found. )}
); }