This commit is contained in:
NotII
2025-03-06 12:49:01 +00:00
parent e26069abfa
commit bc9f8ebbf9
8 changed files with 573 additions and 85 deletions

View File

@@ -16,6 +16,7 @@ import { ProductModal } from "@/components/modals/product-modal";
import ProductTable from "@/components/tables/product-table";
import { Category } from "@/models/categories";
import ImportProductsModal from "@/components/modals/import-products-modal";
import { toast } from "sonner";
export default function ProductsPage() {
const router = useRouter();
@@ -106,51 +107,76 @@ export default function ProductsPage() {
const handleSaveProduct = async (data: Product, file?: File | null) => {
console.log("handleSaveProduct:", data, file);
const adjustedPricing = data.pricing.map((tier) => ({
minQuantity: tier.minQuantity,
pricePerUnit:
typeof tier.pricePerUnit === "string"
? parseFloat(tier.pricePerUnit)
: tier.pricePerUnit,
}));
const productToSave: Product = {
...data,
pricing: adjustedPricing,
};
const authToken = document.cookie
.split("; ")
.find((row) => row.startsWith("Authorization="))
?.split("=")[1];
if (!authToken) {
router.push("/login");
return;
}
setLoading(true);
try {
const authToken = document.cookie.split("Authorization=")[1];
const apiUrl = editing
? `${process.env.NEXT_PUBLIC_API_URL}/products/${data._id}`
: `${process.env.NEXT_PUBLIC_API_URL}/products`;
const url = editing
? `/api/products/${data._id}`
: "/api/products";
// Save product data
const savedProduct = await saveProductData(
apiUrl,
productToSave,
url,
{
name: data.name,
description: data.description,
unitType: data.unitType,
category: data.category,
pricing: data.pricing,
stockTracking: data.stockTracking,
currentStock: data.currentStock,
lowStockThreshold: data.lowStockThreshold
},
authToken,
editing ? "PUT" : "POST"
);
if (file) {
await saveProductImage(`${process.env.NEXT_PUBLIC_API_URL}/products/${savedProduct._id}/image`, file, authToken);
await saveProductImage(
`/api/products/${savedProduct._id}/image`,
file,
authToken
);
}
setProducts((prevProducts) => {
if (editing) {
return prevProducts.map((product) =>
product._id === savedProduct._id ? savedProduct : product
);
} else {
return [...prevProducts, savedProduct];
}
});
// If editing and stock values were updated, update stock in the dedicated endpoint
if (editing && data.stockTracking !== undefined) {
await saveProductData(
`/api/stock/${data._id}`,
{
stockTracking: data.stockTracking,
currentStock: data.currentStock || 0,
lowStockThreshold: data.lowStockThreshold || 10
},
authToken,
"PUT"
);
}
// Refresh products list
const fetchedProducts = await fetchProductData("/api/products", authToken);
setProducts(fetchedProducts);
setModalOpen(false);
setLoading(false);
toast.success(
editing ? "Product updated successfully" : "Product added successfully"
);
} catch (error) {
console.error("Error saving product:", error);
console.error(error);
setLoading(false);
toast.error("Failed to save product");
}
};
@@ -194,11 +220,14 @@ export default function ProductsPage() {
description: "",
unitType: "pcs",
category: "",
stockTracking: true,
currentStock: 0,
lowStockThreshold: 10,
pricing: [{ minQuantity: 1, pricePerUnit: 0 }],
image: null,
});
setEditing(false);
setAddProductOpen(true);
setModalOpen(true);
};
// Get category name by ID

View File

@@ -0,0 +1,294 @@
"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<Product[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const [editingStock, setEditingStock] = useState<Record<string, boolean>>({});
const [stockValues, setStockValues] = useState<Record<string, number>>({});
const [searchTerm, setSearchTerm] = useState<string>("");
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<string, number> = {};
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 (
<Layout>
<div className="container mx-auto">
<div className="flex justify-between items-center mb-8">
<h1 className="text-2xl font-bold">Stock Management</h1>
<Button onClick={() => router.push("/dashboard/products")}>
<Package className="mr-2 h-4 w-4" />
Manage Products
</Button>
</div>
<div className="grid grid-cols-5 gap-4 mb-8">
<div className="bg-background rounded-lg border border-border p-4">
<div className="text-3xl font-bold">{statsData.total}</div>
<div className="text-sm text-muted-foreground">Total Products</div>
</div>
<div className="bg-background rounded-lg border border-border p-4">
<div className="text-3xl font-bold text-green-500">{statsData.inStock}</div>
<div className="text-sm text-muted-foreground">In Stock</div>
</div>
<div className="bg-background rounded-lg border border-border p-4">
<div className="text-3xl font-bold text-amber-500">{statsData.lowStock}</div>
<div className="text-sm text-muted-foreground">Low Stock</div>
</div>
<div className="bg-background rounded-lg border border-border p-4">
<div className="text-3xl font-bold text-red-500">{statsData.outOfStock}</div>
<div className="text-sm text-muted-foreground">Out of Stock</div>
</div>
<div className="bg-background rounded-lg border border-border p-4">
<div className="text-3xl font-bold text-gray-500">{statsData.notTracked}</div>
<div className="text-sm text-muted-foreground">Not Tracked</div>
</div>
</div>
<div className="bg-background rounded-lg border border-border">
<div className="p-4 border-b border-border flex justify-between items-center">
<h2 className="text-xl font-semibold">Inventory List</h2>
<div className="flex items-center gap-2">
<Input
placeholder="Search products..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-64"
/>
<Button
variant="outline"
size="icon"
onClick={() => setSearchTerm("")}
>
<RefreshCw className="h-4 w-4" />
</Button>
</div>
</div>
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>Product</TableHead>
<TableHead>Unit</TableHead>
<TableHead>Status</TableHead>
<TableHead>Current Stock</TableHead>
<TableHead>Low Stock Threshold</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={6} className="h-24 text-center">
Loading...
</TableCell>
</TableRow>
) : filteredProducts.length > 0 ? (
filteredProducts.map((product) => (
<TableRow key={product._id}>
<TableCell className="font-medium">{product.name}</TableCell>
<TableCell>{product.unitType}</TableCell>
<TableCell className={
product.stockTracking === false ? "text-gray-500" :
!product.currentStock || product.currentStock <= 0 ? "text-red-500" :
product.lowStockThreshold && product.currentStock <= product.lowStockThreshold ? "text-amber-500" :
"text-green-500"
}>
{getStockStatus(product)}
</TableCell>
<TableCell>
{editingStock[product._id as string] ? (
<Input
type="number"
min="0"
step={product.unitType === "gr" ? "0.1" : "1"}
value={stockValues[product._id as string]}
onChange={(e) => handleStockChange(product._id as string, parseFloat(e.target.value))}
className="max-w-[100px]"
/>
) : (
product.stockTracking ?
`${product.currentStock || 0} ${product.unitType}` :
"N/A"
)}
</TableCell>
<TableCell>
{product.stockTracking ?
`${product.lowStockThreshold || 0} ${product.unitType}` :
"N/A"}
</TableCell>
<TableCell className="text-right">
{product.stockTracking && (
editingStock[product._id as string] ? (
<Button
size="sm"
onClick={() => handleSaveStock(product)}
>
Save
</Button>
) : (
<Button
variant="outline"
size="sm"
onClick={() => handleEditStock(product._id as string)}
>
Update Stock
</Button>
)
)}
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={6} className="h-24 text-center">
No products found.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
</div>
</div>
</Layout>
);
}

View File

@@ -102,15 +102,32 @@ export const ProductModal: React.FC<ProductModalProps> = ({
};
const handleSave = async () => {
if (!productData.category) {
toast.error("Please select or add a category");
return;
try {
// Validate required fields
if (!productData.name || !productData.category || !productData.unitType) {
toast.error("Please fill in all required fields");
return;
}
// Validate pricing tiers
if (!productData.pricing || productData.pricing.length === 0) {
toast.error("At least one pricing tier is required");
return;
}
// Make sure stock values are numbers
let stockData = { ...productData };
if (stockData.stockTracking) {
stockData.currentStock = Number(stockData.currentStock) || 0;
stockData.lowStockThreshold = Number(stockData.lowStockThreshold) || 10;
}
await onSave(stockData, selectedFile);
onClose();
} catch (error) {
console.error("Error saving product:", error);
toast.error("Failed to save product");
}
onSave(productData, selectedFile);
toast.success(editing ? "Product updated!" : "Product added!");
onClose();
};
const handleAddCategory = (newCategory: { _id: string; name: string; parentId?: string }) => {
@@ -183,42 +200,111 @@ const ProductBasicInfo: React.FC<{
setProductData: React.Dispatch<React.SetStateAction<ProductData>>;
onAddCategory: (newCategory: { _id: string; name: string; parentId?: string }) => void;
}> = ({ productData, handleChange, categories, setProductData, onAddCategory }) => (
<div className="space-y-4">
<div className="grid gap-4 mb-4">
<div>
<label className="text-sm font-medium">Product Name</label>
<label htmlFor="name" className="text-sm font-medium">
Name
</label>
<Input
id="name"
name="name"
placeholder="Product Name"
value={productData.name}
required
value={productData.name || ""}
onChange={handleChange}
className="text-sm h-9"
placeholder="Product name"
/>
</div>
<div>
<label className="text-sm font-medium">Description</label>
<Textarea
id="description"
name="description"
placeholder="Product Description"
value={productData.description}
rows={3}
value={productData.description || ""}
onChange={handleChange}
rows={4}
className="text-sm h-24"
placeholder="Product description"
/>
</div>
<CategorySelect
categories={categories}
value={productData.category}
setProductData={setProductData}
onAddCategory={onAddCategory}
/>
<UnitTypeSelect
value={productData.unitType}
setProductData={setProductData}
categories={categories}
/>
{/* Stock Management Section */}
<div className="bg-background rounded-lg border border-border p-4">
<h3 className="text-sm font-medium mb-4">Stock Management</h3>
<div className="flex items-center space-x-2 mb-4">
<input
id="stockTracking"
name="stockTracking"
type="checkbox"
className="h-4 w-4 rounded border-gray-300"
checked={productData.stockTracking !== false}
onChange={(e) => {
setProductData({
...productData,
stockTracking: e.target.checked
});
}}
/>
<label htmlFor="stockTracking" className="text-sm">
Enable Stock Tracking
</label>
</div>
{productData.stockTracking !== false && (
<div className="grid grid-cols-2 gap-4">
<div>
<label htmlFor="lowStockThreshold" className="text-sm font-medium">
Low Stock Threshold
</label>
<Input
id="lowStockThreshold"
name="lowStockThreshold"
type="number"
min="1"
step={productData.unitType === 'gr' ? '0.1' : '1'}
value={productData.lowStockThreshold || 10}
onChange={handleChange}
placeholder="10"
/>
</div>
<div>
<label htmlFor="currentStock" className="text-sm font-medium">
Current Stock
</label>
<Input
id="currentStock"
name="currentStock"
type="number"
min="0"
step={productData.unitType === 'gr' ? '0.1' : '1'}
value={productData.currentStock || 0}
onChange={handleChange}
placeholder="0"
/>
</div>
</div>
)}
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-sm font-medium">Category</label>
<CategorySelect
categories={categories}
value={productData.category}
setProductData={setProductData}
onAddCategory={onAddCategory}
/>
</div>
<div>
<label className="text-sm font-medium">Unit Type</label>
<UnitTypeSelect
value={productData.unitType}
setProductData={setProductData}
categories={categories}
/>
</div>
</div>
</div>
);

View File

@@ -1,13 +1,14 @@
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Edit, Trash } from "lucide-react";
import { Edit, Trash, AlertTriangle, CheckCircle, AlertCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Product } from "@/models/products";
import { Badge } from "@/components/ui/badge";
interface ProductTableProps {
products: Product[];
loading: boolean;
onEdit: (product: Product) => void;
onDelete: (productId: string) => void; // Added onDelete prop
onDelete: (productId: string) => void;
getCategoryNameById: (categoryId: string) => string;
}
@@ -24,6 +25,19 @@ const ProductTable = ({
const categoryNameB = getCategoryNameById(b.category);
return categoryNameA.localeCompare(categoryNameB);
});
const getStockIcon = (product: Product) => {
if (!product.stockTracking) return null;
if (product.stockStatus === 'out_of_stock') {
return <AlertTriangle className="h-4 w-4 text-red-500" />;
} else if (product.stockStatus === 'low_stock') {
return <AlertCircle className="h-4 w-4 text-amber-500" />;
} else {
return <CheckCircle className="h-4 w-4 text-green-500" />;
}
};
return (
<div className="rounded-lg border dark:border-zinc-700 shadow-sm overflow-hidden">
<Table className="relative">
@@ -32,6 +46,7 @@ const ProductTable = ({
<TableHead className="w-[200px]">Product</TableHead>
<TableHead className="text-center">Category</TableHead>
<TableHead className="text-center">Unit</TableHead>
<TableHead className="text-center">Stock</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
@@ -43,31 +58,47 @@ const ProductTable = ({
<TableCell>Loading...</TableCell>
<TableCell>Loading...</TableCell>
<TableCell>Loading...</TableCell>
<TableCell>Loading...</TableCell>
</TableRow>
))
) : sortedProducts.length > 0 ? (
sortedProducts.map((product) => (
<TableRow key={product._id} className="transition-colors hover:bg-gray-50 dark:hover:bg-zinc-800/70">
<TableCell className="font-medium">{product.name}</TableCell>
<TableCell className="text-center">
{getCategoryNameById(product.category)} {/* Display category name */}
<TableCell>
<div className="font-medium truncate max-w-[180px]">{product.name}</div>
</TableCell>
<TableCell className="text-center uppercase text-sm">{product.unitType}</TableCell>
<TableCell className="text-right">
<div className="flex justify-end space-x-2">
<Button size="sm" variant="ghost" onClick={() => onEdit(product)}>
<Edit className="h-4 w-4" />
</Button>
<Button size="sm" variant="ghost" className="text-red-600 hover:text-red-700 dark:text-red-400" onClick={() => onDelete(product._id ?? "")}>
<Trash className="h-4 w-4" />
</Button>
</div>
<TableCell className="text-center">{getCategoryNameById(product.category)}</TableCell>
<TableCell className="text-center">{product.unitType}</TableCell>
<TableCell className="text-center">
{product.stockTracking ? (
<div className="flex items-center justify-center gap-1">
{getStockIcon(product)}
<span className="text-sm">
{product.currentStock !== undefined ? product.currentStock : 0} {product.unitType}
</span>
</div>
) : (
<Badge variant="outline" className="text-xs">Not Tracked</Badge>
)}
</TableCell>
<TableCell className="text-right flex justify-end space-x-1">
<Button variant="ghost" size="sm" onClick={() => onEdit(product)}>
<Edit className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => onDelete(product._id as string)}
className="text-red-500 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-950/20"
>
<Trash className="h-4 w-4" />
</Button>
</TableCell>
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={4} className="h-24 text-center">
<TableCell colSpan={5} className="h-24 text-center">
No products found.
</TableCell>
</TableRow>

View File

@@ -1,4 +1,4 @@
import { Home, Package, Box, Truck, Settings, FolderTree, MessageCircle } from "lucide-react"
import { Home, Package, Box, Truck, Settings, FolderTree, MessageCircle, BarChart3 } from "lucide-react"
export const sidebarConfig = [
{
@@ -12,6 +12,7 @@ export const sidebarConfig = [
title: "Management",
items: [
{ name: "Products", href: "/dashboard/products", icon: Box },
{ name: "Stock", href: "/dashboard/stock", icon: BarChart3 },
{ name: "Categories", href: "/dashboard/categories", icon: FolderTree},
{ name: "Shipping", href: "/dashboard/shipping", icon: Truck },
{ name: "Storefront", href: "/dashboard/storefront", icon: Settings },

View File

@@ -67,4 +67,42 @@ export const deleteProductData = async (url: string, authToken: string) => {
console.error("Error deleting product data:", error);
throw error;
}
};
// Stock management functions
export const fetchStockData = async (authToken: string) => {
try {
return await fetchData('/api/stock', {
headers: { Authorization: `Bearer ${authToken}` },
credentials: "include",
});
} catch (error) {
console.error("Error fetching stock data:", error);
throw error;
}
};
export const updateProductStock = async (
productId: string,
stockData: {
currentStock: number;
stockTracking?: boolean;
lowStockThreshold?: number;
},
authToken: string
) => {
try {
return await fetchData(`/api/stock/${productId}`, {
method: "PUT",
headers: {
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
},
credentials: "include",
body: JSON.stringify(stockData),
});
} catch (error) {
console.error("Error updating product stock:", error);
throw error;
}
};

View File

@@ -38,6 +38,10 @@ export interface Product {
name: string
description: string
stock?: number
stockTracking?: boolean
currentStock?: number
lowStockThreshold?: number
stockStatus?: 'in_stock' | 'low_stock' | 'out_of_stock'
unitType: string
category: string
pricing: PricingTier[]

View File

@@ -4,6 +4,11 @@ export interface Product {
description: string;
unitType: string;
category: string;
// Stock management fields
stockTracking?: boolean;
currentStock?: number;
lowStockThreshold?: number;
stockStatus?: 'in_stock' | 'low_stock' | 'out_of_stock';
pricing: Array<{
minQuantity: number;
pricePerUnit: number;