Update frontend to allow categories
This commit is contained in:
282
app/dashboard/categories/page.tsx
Normal file
282
app/dashboard/categories/page.tsx
Normal file
@@ -0,0 +1,282 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import Layout from "@/components/layout/layout";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Plus, Pencil, Trash2, ChevronRight, ChevronDown } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { apiRequest } from "@/lib/storeHelper";
|
||||
import type { Category } from "@/models/categories";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
export default function CategoriesPage() {
|
||||
const [categories, setCategories] = useState<Category[]>([]);
|
||||
const [newCategoryName, setNewCategoryName] = useState("");
|
||||
const [selectedParentId, setSelectedParentId] = useState<string>("");
|
||||
const [editingCategory, setEditingCategory] = useState<Category | null>(null);
|
||||
const [categoryToDelete, setCategoryToDelete] = useState<Category | null>(null);
|
||||
|
||||
const rootCategories = categories.filter(cat => !cat.parentId);
|
||||
|
||||
const getSubcategories = (parentId: string) =>
|
||||
categories.filter(cat => cat.parentId === parentId);
|
||||
|
||||
useEffect(() => {
|
||||
fetchCategories();
|
||||
}, []);
|
||||
|
||||
const fetchCategories = async () => {
|
||||
try {
|
||||
const fetchedCategories = await apiRequest("/categories", "GET");
|
||||
setCategories(fetchedCategories);
|
||||
} catch (error) {
|
||||
toast.error("Failed to fetch categories");
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddCategory = async () => {
|
||||
if (!newCategoryName.trim()) {
|
||||
toast.error("Category name cannot be empty");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await apiRequest("/categories", "POST", {
|
||||
name: newCategoryName,
|
||||
parentId: selectedParentId || undefined,
|
||||
});
|
||||
|
||||
setCategories([...categories, response]);
|
||||
setNewCategoryName("");
|
||||
setSelectedParentId("");
|
||||
toast.success("Category added successfully");
|
||||
} catch (error) {
|
||||
toast.error("Failed to add category");
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdateCategory = async (categoryId: string, newName: string) => {
|
||||
try {
|
||||
const response = await apiRequest(`/categories/${categoryId}`, "PUT", {
|
||||
name: newName,
|
||||
});
|
||||
|
||||
setCategories(categories.map(cat =>
|
||||
cat._id === categoryId ? { ...cat, name: newName } : cat
|
||||
));
|
||||
setEditingCategory(null);
|
||||
toast.success("Category updated successfully");
|
||||
} catch (error) {
|
||||
toast.error("Failed to update category");
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteConfirm = async () => {
|
||||
if (!categoryToDelete) return;
|
||||
|
||||
try {
|
||||
await apiRequest(`/categories/${categoryToDelete._id}`, "DELETE");
|
||||
setCategories(categories.filter(cat => cat._id !== categoryToDelete._id));
|
||||
toast.success("Category deleted successfully");
|
||||
setCategoryToDelete(null);
|
||||
} catch (error) {
|
||||
console.error("Failed to delete category:", error);
|
||||
toast.error("Failed to delete category");
|
||||
}
|
||||
};
|
||||
|
||||
const renderCategoryItem = (category: Category, level: number = 0) => {
|
||||
const subcategories = getSubcategories(category._id);
|
||||
const hasSubcategories = subcategories.length > 0;
|
||||
const isEditing = editingCategory?._id === category._id;
|
||||
|
||||
return (
|
||||
<div key={category._id} className="space-y-1">
|
||||
<div
|
||||
className={`group flex items-center p-2 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors
|
||||
${isEditing ? 'bg-gray-100 dark:bg-gray-800' : ''}`}
|
||||
style={{ marginLeft: `${level * 24}px` }}
|
||||
>
|
||||
{hasSubcategories && (
|
||||
<ChevronRight className="h-4 w-4 mr-2 text-muted-foreground" />
|
||||
)}
|
||||
<div className="flex-1 flex items-center space-x-2">
|
||||
{isEditing ? (
|
||||
<Input
|
||||
value={editingCategory?.name || ""}
|
||||
onChange={(e) => setEditingCategory(prev => prev ? { ...prev, name: e.target.value } : prev)}
|
||||
className="h-8 max-w-[200px]"
|
||||
autoFocus
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && editingCategory) {
|
||||
handleUpdateCategory(category._id, editingCategory.name);
|
||||
} else if (e.key === 'Escape') {
|
||||
setEditingCategory(null);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<span className="text-sm font-medium">{category.name}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center space-x-1 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
{isEditing ? (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 px-2 text-green-600 hover:text-green-700 hover:bg-green-50"
|
||||
onClick={() => editingCategory && handleUpdateCategory(category._id, editingCategory.name)}
|
||||
>
|
||||
Save
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 px-2"
|
||||
onClick={() => setEditingCategory(null)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 w-8 p-0 text-blue-500 hover:text-blue-600 hover:bg-blue-50"
|
||||
onClick={() => setEditingCategory(category)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 w-8 p-0 text-red-500 hover:text-red-600 hover:bg-red-50"
|
||||
onClick={() => setCategoryToDelete(category)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{subcategories.map(subcat => renderCategoryItem(subcat, level + 1))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<div className="max-w-4xl mx-auto space-y-6 p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-3xl font-bold tracking-tight">Categories</h1>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-xl font-semibold">Add New Category</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-end gap-4">
|
||||
<div className="flex-1 space-y-2">
|
||||
<label className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
|
||||
Category Name
|
||||
</label>
|
||||
<Input
|
||||
value={newCategoryName}
|
||||
onChange={(e) => setNewCategoryName(e.target.value)}
|
||||
placeholder="Enter category name"
|
||||
className="h-9"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 space-y-2">
|
||||
<label className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
|
||||
Parent Category
|
||||
</label>
|
||||
<Select
|
||||
value={selectedParentId || "none"}
|
||||
onValueChange={setSelectedParentId}
|
||||
>
|
||||
<SelectTrigger className="h-9">
|
||||
<SelectValue placeholder="Select parent category" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">No parent (root category)</SelectItem>
|
||||
{categories.map((cat) => (
|
||||
<SelectItem key={cat._id} value={cat._id}>
|
||||
{cat.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button onClick={handleAddCategory} className="h-9">
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Add Category
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-xl font-semibold">Category List</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-1">
|
||||
{rootCategories.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">
|
||||
No categories yet. Add your first category above.
|
||||
</p>
|
||||
) : (
|
||||
rootCategories.map(category => renderCategoryItem(category))
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<AlertDialog open={!!categoryToDelete} onOpenChange={() => setCategoryToDelete(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This will permanently delete the category "{categoryToDelete?.name}"
|
||||
{getSubcategories(categoryToDelete?._id || "").length > 0 &&
|
||||
" and all its subcategories"}. This action cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDeleteConfirm}
|
||||
className="bg-red-500 hover:bg-red-600"
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
@@ -14,11 +14,13 @@ import {
|
||||
} from "@/lib/productData";
|
||||
import { ProductModal } from "@/components/modals/product-modal";
|
||||
import ProductTable from "@/components/tables/product-table";
|
||||
import { Category } from "@/models/categories"
|
||||
|
||||
|
||||
export default function ProductsPage() {
|
||||
const router = useRouter();
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
const [categories, setCategories] = useState<any[]>([]);
|
||||
const [categories, setCategories] = useState<Category[]>([]);
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [modalOpen, setModalOpen] = useState<boolean>(false);
|
||||
const [editing, setEditing] = useState<boolean>(false);
|
||||
@@ -47,14 +49,8 @@ export default function ProductsPage() {
|
||||
const fetchDataAsync = async () => {
|
||||
try {
|
||||
const [fetchedProducts, fetchedCategories] = await Promise.all([
|
||||
fetchProductData(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/products`,
|
||||
authToken
|
||||
),
|
||||
fetchProductData(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/categories`,
|
||||
authToken
|
||||
),
|
||||
fetchProductData(`${process.env.NEXT_PUBLIC_API_URL}/products`, authToken),
|
||||
fetchProductData(`${process.env.NEXT_PUBLIC_API_URL}/categories`, authToken),
|
||||
]);
|
||||
|
||||
console.log("Fetched Products:", fetchedProducts);
|
||||
@@ -207,7 +203,12 @@ export default function ProductsPage() {
|
||||
// Get category name by ID
|
||||
const getCategoryNameById = (categoryId: string): string => {
|
||||
const category = categories.find((cat) => cat._id === categoryId);
|
||||
return category ? category.name : "Unknown Category";
|
||||
if (!category) return "Unknown Category";
|
||||
if (category.parentId) {
|
||||
const parent = categories.find((cat) => cat._id === category.parentId);
|
||||
return parent ? `${parent.name} > ${category.name}` : category.name;
|
||||
}
|
||||
return category.name;
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
Reference in New Issue
Block a user