balls
This commit is contained in:
@@ -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
|
||||
|
||||
294
app/dashboard/stock/page.tsx
Normal file
294
app/dashboard/stock/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user