Update page.tsx
This commit is contained in:
@@ -6,9 +6,27 @@ 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 { Switch } from "@/components/ui/switch";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Product } from "@/models/products";
|
||||
import { Package, RefreshCw } from "lucide-react";
|
||||
import { fetchProductData, updateProductStock } from "@/lib/productData";
|
||||
import { Package, RefreshCw, ChevronDown, CheckSquare, XSquare } from "lucide-react";
|
||||
import { fetchProductData, updateProductStock, saveProductData } from "@/lib/productData";
|
||||
import { toast } from "sonner";
|
||||
|
||||
export default function StockManagementPage() {
|
||||
@@ -18,6 +36,9 @@ export default function StockManagementPage() {
|
||||
const [editingStock, setEditingStock] = useState<Record<string, boolean>>({});
|
||||
const [stockValues, setStockValues] = useState<Record<string, number>>({});
|
||||
const [searchTerm, setSearchTerm] = useState<string>("");
|
||||
const [selectedProducts, setSelectedProducts] = useState<string[]>([]);
|
||||
const [isConfirmDialogOpen, setIsConfirmDialogOpen] = useState(false);
|
||||
const [bulkAction, setBulkAction] = useState<'enable' | 'disable' | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const authToken = document.cookie
|
||||
@@ -117,6 +138,162 @@ export default function StockManagementPage() {
|
||||
});
|
||||
};
|
||||
|
||||
const handleToggleStockTracking = 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 apiUrl = `${process.env.NEXT_PUBLIC_API_URL}/products/${product._id}`;
|
||||
|
||||
// Toggle the stock tracking status
|
||||
const newTrackingStatus = !product.stockTracking;
|
||||
|
||||
// For enabling tracking, we need to ensure there's a stock value
|
||||
const stockData = {
|
||||
stockTracking: newTrackingStatus,
|
||||
currentStock: product.currentStock || 0,
|
||||
lowStockThreshold: product.lowStockThreshold || 10,
|
||||
};
|
||||
|
||||
// Update product with new tracking status
|
||||
await saveProductData(
|
||||
apiUrl,
|
||||
stockData,
|
||||
authToken,
|
||||
"PUT"
|
||||
);
|
||||
|
||||
// Also update stock API to ensure consistency
|
||||
await updateProductStock(
|
||||
product._id,
|
||||
stockData,
|
||||
authToken
|
||||
);
|
||||
|
||||
// Update local state
|
||||
setProducts(products.map(p => {
|
||||
if (p._id === product._id) {
|
||||
return {
|
||||
...p,
|
||||
stockTracking: newTrackingStatus,
|
||||
currentStock: stockData.currentStock,
|
||||
lowStockThreshold: stockData.lowStockThreshold,
|
||||
};
|
||||
}
|
||||
return p;
|
||||
}));
|
||||
|
||||
toast.success(`Stock tracking ${newTrackingStatus ? 'enabled' : 'disabled'} for ${product.name}`);
|
||||
} catch (error) {
|
||||
console.error("Error toggling stock tracking:", error);
|
||||
toast.error(`Failed to ${product.stockTracking ? 'disable' : 'enable'} stock tracking`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBulkAction = async (action: 'enable' | 'disable') => {
|
||||
if (selectedProducts.length === 0) {
|
||||
toast.error("No products selected");
|
||||
return;
|
||||
}
|
||||
|
||||
setBulkAction(action);
|
||||
setIsConfirmDialogOpen(true);
|
||||
};
|
||||
|
||||
const executeBulkAction = async () => {
|
||||
const authToken = document.cookie
|
||||
.split("; ")
|
||||
.find((row) => row.startsWith("Authorization="))
|
||||
?.split("=")[1];
|
||||
|
||||
if (!authToken || !bulkAction) {
|
||||
setIsConfirmDialogOpen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const isEnabling = bulkAction === 'enable';
|
||||
const updatePromises = selectedProducts.map(async (productId) => {
|
||||
const product = products.find(p => p._id === productId);
|
||||
if (!product) return null;
|
||||
|
||||
const apiUrl = `${process.env.NEXT_PUBLIC_API_URL}/products/${productId}`;
|
||||
|
||||
const stockData = {
|
||||
stockTracking: isEnabling,
|
||||
currentStock: product.currentStock || 0,
|
||||
lowStockThreshold: product.lowStockThreshold || 10,
|
||||
};
|
||||
|
||||
// Update product with new tracking status
|
||||
await saveProductData(
|
||||
apiUrl,
|
||||
stockData,
|
||||
authToken,
|
||||
"PUT"
|
||||
);
|
||||
|
||||
// Also update stock API to ensure consistency
|
||||
await updateProductStock(
|
||||
productId,
|
||||
stockData,
|
||||
authToken
|
||||
);
|
||||
|
||||
return productId;
|
||||
});
|
||||
|
||||
await Promise.all(updatePromises);
|
||||
|
||||
// Update local state
|
||||
setProducts(products.map(p => {
|
||||
if (selectedProducts.includes(p._id as string)) {
|
||||
return {
|
||||
...p,
|
||||
stockTracking: isEnabling,
|
||||
};
|
||||
}
|
||||
return p;
|
||||
}));
|
||||
|
||||
setSelectedProducts([]);
|
||||
toast.success(`Stock tracking ${isEnabling ? 'enabled' : 'disabled'} for ${selectedProducts.length} products`);
|
||||
} catch (error) {
|
||||
console.error(`Error ${bulkAction}ing stock tracking:`, error);
|
||||
toast.error(`Failed to ${bulkAction} stock tracking`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setIsConfirmDialogOpen(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleSelectProduct = (productId: string) => {
|
||||
setSelectedProducts(prev =>
|
||||
prev.includes(productId)
|
||||
? prev.filter(id => id !== productId)
|
||||
: [...prev, productId]
|
||||
);
|
||||
};
|
||||
|
||||
const toggleSelectAll = () => {
|
||||
if (selectedProducts.length === filteredProducts.length) {
|
||||
setSelectedProducts([]);
|
||||
} else {
|
||||
setSelectedProducts(filteredProducts.map(p => p._id as string));
|
||||
}
|
||||
};
|
||||
|
||||
const getStockStatus = (product: Product) => {
|
||||
if (!product.stockTracking) return "Not Tracked";
|
||||
|
||||
@@ -150,10 +327,12 @@ export default function StockManagementPage() {
|
||||
<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 className="flex space-x-3">
|
||||
<Button onClick={() => router.push("/dashboard/products")}>
|
||||
<Package className="mr-2 h-4 w-4" />
|
||||
Manage Products
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-5 gap-4 mb-8">
|
||||
@@ -185,7 +364,28 @@ export default function StockManagementPage() {
|
||||
|
||||
<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-3">
|
||||
<h2 className="text-xl font-semibold">Inventory List</h2>
|
||||
{selectedProducts.length > 0 && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="ml-2">
|
||||
Bulk Actions <ChevronDown className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuItem onClick={() => handleBulkAction('enable')}>
|
||||
<CheckSquare className="mr-2 h-4 w-4" />
|
||||
Enable Tracking
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => handleBulkAction('disable')}>
|
||||
<XSquare className="mr-2 h-4 w-4" />
|
||||
Disable Tracking
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
placeholder="Search products..."
|
||||
@@ -207,24 +407,41 @@ export default function StockManagementPage() {
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[30px]">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="h-4 w-4 rounded border-gray-300"
|
||||
checked={selectedProducts.length > 0 && selectedProducts.length === filteredProducts.length}
|
||||
onChange={toggleSelectAll}
|
||||
/>
|
||||
</TableHead>
|
||||
<TableHead>Product</TableHead>
|
||||
<TableHead>Unit</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Current Stock</TableHead>
|
||||
<TableHead>Low Stock Threshold</TableHead>
|
||||
<TableHead>Track Stock</TableHead>
|
||||
<TableHead className="text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{loading ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="h-24 text-center">
|
||||
<TableCell colSpan={8} className="h-24 text-center">
|
||||
Loading...
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : filteredProducts.length > 0 ? (
|
||||
filteredProducts.map((product) => (
|
||||
<TableRow key={product._id}>
|
||||
<TableCell>
|
||||
<input
|
||||
type="checkbox"
|
||||
className="h-4 w-4 rounded border-gray-300"
|
||||
checked={selectedProducts.includes(product._id as string)}
|
||||
onChange={() => toggleSelectProduct(product._id as string)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="font-medium">{product.name}</TableCell>
|
||||
<TableCell>{product.unitType}</TableCell>
|
||||
<TableCell className={
|
||||
@@ -256,6 +473,12 @@ export default function StockManagementPage() {
|
||||
`${product.lowStockThreshold || 0} ${product.unitType}` :
|
||||
"N/A"}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Switch
|
||||
checked={product.stockTracking === true}
|
||||
onCheckedChange={() => handleToggleStockTracking(product)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{product.stockTracking && (
|
||||
editingStock[product._id as string] ? (
|
||||
@@ -280,7 +503,7 @@ export default function StockManagementPage() {
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell colSpan={6} className="h-24 text-center">
|
||||
<TableCell colSpan={8} className="h-24 text-center">
|
||||
No products found.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
@@ -289,6 +512,27 @@ export default function StockManagementPage() {
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AlertDialog open={isConfirmDialogOpen} onOpenChange={setIsConfirmDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{bulkAction === 'enable' ? 'Enable' : 'Disable'} Stock Tracking
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to {bulkAction === 'enable' ? 'enable' : 'disable'} stock tracking for {selectedProducts.length} selected products?
|
||||
{bulkAction === 'disable' && ' This will remove any stock tracking for these products.'}
|
||||
{bulkAction === 'enable' && ' This will enable stock tracking with initial values.'}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={executeBulkAction}>
|
||||
Confirm
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user