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";
|
} from "@/lib/productData";
|
||||||
import { ProductModal } from "@/components/modals/product-modal";
|
import { ProductModal } from "@/components/modals/product-modal";
|
||||||
import ProductTable from "@/components/tables/product-table";
|
import ProductTable from "@/components/tables/product-table";
|
||||||
|
import { Category } from "@/models/categories"
|
||||||
|
|
||||||
|
|
||||||
export default function ProductsPage() {
|
export default function ProductsPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [products, setProducts] = useState<Product[]>([]);
|
const [products, setProducts] = useState<Product[]>([]);
|
||||||
const [categories, setCategories] = useState<any[]>([]);
|
const [categories, setCategories] = useState<Category[]>([]);
|
||||||
const [loading, setLoading] = useState<boolean>(true);
|
const [loading, setLoading] = useState<boolean>(true);
|
||||||
const [modalOpen, setModalOpen] = useState<boolean>(false);
|
const [modalOpen, setModalOpen] = useState<boolean>(false);
|
||||||
const [editing, setEditing] = useState<boolean>(false);
|
const [editing, setEditing] = useState<boolean>(false);
|
||||||
@@ -47,14 +49,8 @@ export default function ProductsPage() {
|
|||||||
const fetchDataAsync = async () => {
|
const fetchDataAsync = async () => {
|
||||||
try {
|
try {
|
||||||
const [fetchedProducts, fetchedCategories] = await Promise.all([
|
const [fetchedProducts, fetchedCategories] = await Promise.all([
|
||||||
fetchProductData(
|
fetchProductData(`${process.env.NEXT_PUBLIC_API_URL}/products`, authToken),
|
||||||
`${process.env.NEXT_PUBLIC_API_URL}/products`,
|
fetchProductData(`${process.env.NEXT_PUBLIC_API_URL}/categories`, authToken),
|
||||||
authToken
|
|
||||||
),
|
|
||||||
fetchProductData(
|
|
||||||
`${process.env.NEXT_PUBLIC_API_URL}/categories`,
|
|
||||||
authToken
|
|
||||||
),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
console.log("Fetched Products:", fetchedProducts);
|
console.log("Fetched Products:", fetchedProducts);
|
||||||
@@ -207,7 +203,12 @@ export default function ProductsPage() {
|
|||||||
// Get category name by ID
|
// Get category name by ID
|
||||||
const getCategoryNameById = (categoryId: string): string => {
|
const getCategoryNameById = (categoryId: string): string => {
|
||||||
const category = categories.find((cat) => cat._id === categoryId);
|
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 (
|
return (
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ export default function Layout({ children }: LayoutProps) {
|
|||||||
<div className={`flex h-screen ${theme === "dark" ? "dark" : ""}`}>
|
<div className={`flex h-screen ${theme === "dark" ? "dark" : ""}`}>
|
||||||
<Sidebar />
|
<Sidebar />
|
||||||
<div className="w-full flex flex-1 flex-col">
|
<div className="w-full flex flex-1 flex-col">
|
||||||
<main className="flex-1 overflow-auto p-6 dak:bg-[#0F0F12]">{children}</main>
|
<main className="flex-1 overflow-auto p-6 dark:bg-[#0F0F12]">{children}</main>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import Link from "next/link"
|
import Link from "next/link"
|
||||||
import type { LucideIcon } from "lucide-react"
|
import type { LucideIcon } from "lucide-react"
|
||||||
import type React from "react" // Added import for React
|
import type React from "react"
|
||||||
|
|
||||||
interface NavItemProps {
|
interface NavItemProps {
|
||||||
href: string
|
href: string
|
||||||
|
|||||||
@@ -8,7 +8,9 @@ import { Textarea } from "@/components/ui/textarea";
|
|||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
SelectContent,
|
SelectContent,
|
||||||
|
SelectGroup,
|
||||||
SelectItem,
|
SelectItem,
|
||||||
|
SelectLabel,
|
||||||
SelectTrigger,
|
SelectTrigger,
|
||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
@@ -21,10 +23,10 @@ import { Plus } from "lucide-react";
|
|||||||
import { apiRequest } from "@/lib/storeHelper";
|
import { apiRequest } from "@/lib/storeHelper";
|
||||||
|
|
||||||
type CategorySelectProps = {
|
type CategorySelectProps = {
|
||||||
categories: { _id: string; name: string }[];
|
categories: { _id: string; name: string; parentId?: string }[];
|
||||||
value: string;
|
value: string;
|
||||||
setProductData: React.Dispatch<React.SetStateAction<ProductData>>;
|
setProductData: React.Dispatch<React.SetStateAction<ProductData>>;
|
||||||
onAddCategory: (newCategory: { _id: string; name: string }) => void;
|
onAddCategory: (newCategory: { _id: string; name: string; parentId?: string }) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const ProductModal: React.FC<ProductModalProps> = ({
|
export const ProductModal: React.FC<ProductModalProps> = ({
|
||||||
@@ -101,7 +103,7 @@ export const ProductModal: React.FC<ProductModalProps> = ({
|
|||||||
onClose();
|
onClose();
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleAddCategory = (newCategory: { _id: string; name: string }) => {
|
const handleAddCategory = (newCategory: { _id: string; name: string; parentId?: string }) => {
|
||||||
setLocalCategories((prev) => [...prev, newCategory]);
|
setLocalCategories((prev) => [...prev, newCategory]);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -167,9 +169,9 @@ export const ProductModal: React.FC<ProductModalProps> = ({
|
|||||||
const ProductBasicInfo: React.FC<{
|
const ProductBasicInfo: React.FC<{
|
||||||
productData: ProductData;
|
productData: ProductData;
|
||||||
handleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
|
handleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
|
||||||
categories: { _id: string; name: string }[];
|
categories: { _id: string; name: string; parentId?: string }[];
|
||||||
setProductData: React.Dispatch<React.SetStateAction<ProductData>>;
|
setProductData: React.Dispatch<React.SetStateAction<ProductData>>;
|
||||||
onAddCategory: (newCategory: { _id: string; name: string }) => void;
|
onAddCategory: (newCategory: { _id: string; name: string; parentId?: string }) => void;
|
||||||
}> = ({ productData, handleChange, categories, setProductData, onAddCategory }) => (
|
}> = ({ productData, handleChange, categories, setProductData, onAddCategory }) => (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
@@ -205,6 +207,7 @@ const ProductBasicInfo: React.FC<{
|
|||||||
<UnitTypeSelect
|
<UnitTypeSelect
|
||||||
value={productData.unitType}
|
value={productData.unitType}
|
||||||
setProductData={setProductData}
|
setProductData={setProductData}
|
||||||
|
categories={categories}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -213,80 +216,65 @@ const CategorySelect: React.FC<CategorySelectProps> = ({
|
|||||||
categories,
|
categories,
|
||||||
value,
|
value,
|
||||||
setProductData,
|
setProductData,
|
||||||
onAddCategory,
|
|
||||||
}) => {
|
}) => {
|
||||||
const [isAddingCategory, setIsAddingCategory] = useState(false);
|
const [selectedMainCategory, setSelectedMainCategory] = useState<string>("");
|
||||||
const [newCategoryName, setNewCategoryName] = useState("");
|
|
||||||
|
|
||||||
const handleAddCategory = async () => {
|
// Get root categories (those without parentId)
|
||||||
if (!newCategoryName.trim()) {
|
const rootCategories = categories.filter(cat => !cat.parentId);
|
||||||
toast.error("Category name cannot be empty");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
// Get subcategories for a given parent
|
||||||
const response = await apiRequest("/categories", "POST", { name: newCategoryName });
|
const getSubcategories = (parentId: string) =>
|
||||||
const newCategory = response.data;
|
categories.filter(cat => cat.parentId === parentId);
|
||||||
setProductData((prev) => ({ ...prev, category: newCategory._id }));
|
|
||||||
onAddCategory(newCategory);
|
|
||||||
setIsAddingCategory(false);
|
|
||||||
setNewCategoryName("");
|
|
||||||
toast.success("New category added successfully");
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Failed to add new category:", error);
|
|
||||||
toast.error("Failed to add new category");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-sm font-medium">Category</label>
|
<label className="text-sm font-medium">Category</label>
|
||||||
<div className="flex items-center space-x-2">
|
<div className="space-y-2">
|
||||||
{isAddingCategory ? (
|
{/* Main Category Select */}
|
||||||
<Input
|
|
||||||
value={newCategoryName}
|
|
||||||
onChange={(e) => setNewCategoryName(e.target.value)}
|
|
||||||
placeholder="New category name"
|
|
||||||
className="flex-grow h-9 text-sm"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<Select
|
<Select
|
||||||
value={value || "placeholder"}
|
value={selectedMainCategory}
|
||||||
onValueChange={(val) =>
|
onValueChange={(val) => {
|
||||||
setProductData((prev) => ({
|
setSelectedMainCategory(val);
|
||||||
...prev,
|
setProductData((prev) => ({ ...prev, category: "" }));
|
||||||
category: val === "placeholder" ? "" : val,
|
}}
|
||||||
}))
|
|
||||||
}
|
|
||||||
>
|
>
|
||||||
<SelectTrigger className={"h-9 text-sm"}>
|
<SelectTrigger className="h-9 text-sm">
|
||||||
<SelectValue placeholder="Select category..." />
|
<SelectValue placeholder="Select main category..." />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="placeholder">Select category...</SelectItem>
|
<SelectItem value="uncategorized">Select main category...</SelectItem>
|
||||||
{categories.map((cat) => (
|
{rootCategories.map((cat) => (
|
||||||
<SelectItem key={cat._id} value={cat._id}>
|
<SelectItem key={cat._id} value={cat._id}>
|
||||||
{cat.name}
|
{cat.name}
|
||||||
</SelectItem>
|
</SelectItem>
|
||||||
))}
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
)}
|
|
||||||
<Button
|
{/* Subcategory Select */}
|
||||||
type="button"
|
{selectedMainCategory && selectedMainCategory !== "uncategorized" && (
|
||||||
variant="outline"
|
<Select
|
||||||
size="sm"
|
value={value || "uncategorized"}
|
||||||
onClick={() => {
|
onValueChange={(val) =>
|
||||||
if (isAddingCategory) {
|
setProductData((prev) => ({
|
||||||
handleAddCategory();
|
...prev,
|
||||||
} else {
|
category: val === "uncategorized" ? "" : val,
|
||||||
setIsAddingCategory(true);
|
}))
|
||||||
}
|
}
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<Plus className="w-4 h-4 mr-1" />
|
<SelectTrigger className="h-9 text-sm">
|
||||||
{isAddingCategory ? "Save" : "Add"}
|
<SelectValue placeholder="Select subcategory (optional)..." />
|
||||||
</Button>
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="uncategorized">No subcategory</SelectItem>
|
||||||
|
{getSubcategories(selectedMainCategory).map((subCat) => (
|
||||||
|
<SelectItem key={subCat._id} value={subCat._id}>
|
||||||
|
{subCat.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -295,7 +283,8 @@ const CategorySelect: React.FC<CategorySelectProps> = ({
|
|||||||
const UnitTypeSelect: React.FC<{
|
const UnitTypeSelect: React.FC<{
|
||||||
value: string;
|
value: string;
|
||||||
setProductData: React.Dispatch<React.SetStateAction<ProductData>>;
|
setProductData: React.Dispatch<React.SetStateAction<ProductData>>;
|
||||||
}> = ({ value, setProductData }) => (
|
categories: { _id: string; name: string; parentId?: string }[];
|
||||||
|
}> = ({ value, setProductData, categories }) => (
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<label className="text-sm font-medium">Unit Type</label>
|
<label className="text-sm font-medium">Unit Type</label>
|
||||||
<div className="flex items-center space-x-2">
|
<div className="flex items-center space-x-2">
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Home, Package, Box, Truck, Settings } from "lucide-react"
|
import { Home, Package, Box, Truck, Settings, FolderTree } from "lucide-react"
|
||||||
|
|
||||||
export const sidebarConfig = [
|
export const sidebarConfig = [
|
||||||
{
|
{
|
||||||
@@ -12,6 +12,7 @@ export const sidebarConfig = [
|
|||||||
title: "Management",
|
title: "Management",
|
||||||
items: [
|
items: [
|
||||||
{ name: "Products", href: "/dashboard/products", icon: Box },
|
{ name: "Products", href: "/dashboard/products", icon: Box },
|
||||||
|
{ name: "Categories", href: "/dashboard/categories", icon: FolderTree},
|
||||||
{ name: "Shipping", href: "/dashboard/shipping", icon: Truck },
|
{ name: "Shipping", href: "/dashboard/shipping", icon: Truck },
|
||||||
{ name: "Storefront", href: "/dashboard/storefront", icon: Settings },
|
{ name: "Storefront", href: "/dashboard/storefront", icon: Settings },
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ export async function fetchServer<T = unknown>(
|
|||||||
if (!authToken) redirect('/login');
|
if (!authToken) redirect('/login');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
console.log(`${endpoint}`)
|
||||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`, {
|
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`, {
|
||||||
...options,
|
...options,
|
||||||
headers: {
|
headers: {
|
||||||
@@ -29,7 +30,7 @@ export async function fetchServer<T = unknown>(
|
|||||||
|
|
||||||
return res.json();
|
return res.json();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Server request to ${endpoint} failed:`, error);
|
//console.error(`Server request to ${endpoint} failed:`, error);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -16,7 +16,6 @@ export const apiRequest = async <T = any>(endpoint: string, method: string = "GE
|
|||||||
throw new Error("No authentication token found");
|
throw new Error("No authentication token found");
|
||||||
}
|
}
|
||||||
|
|
||||||
// ✅ API Request Options
|
|
||||||
const options: RequestInit = {
|
const options: RequestInit = {
|
||||||
method,
|
method,
|
||||||
headers: {
|
headers: {
|
||||||
@@ -41,7 +40,6 @@ export const apiRequest = async <T = any>(endpoint: string, method: string = "GE
|
|||||||
throw new Error(`Failed to ${method} ${endpoint}: ${errorMessage}`);
|
throw new Error(`Failed to ${method} ${endpoint}: ${errorMessage}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ✅ Return JSON response
|
|
||||||
return res;
|
return res;
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
if (error instanceof Error) {
|
if (error instanceof Error) {
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { clsx, type ClassValue } from "clsx";
|
import { clsx, type ClassValue } from "clsx";
|
||||||
import { twMerge } from "tailwind-merge";
|
import { twMerge } from "tailwind-merge";
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Utility function for merging Tailwind CSS class names with conditional logic.
|
* Utility function for merging Tailwind CSS class names with conditional logic.
|
||||||
* @param inputs - Class values to merge.
|
* @param inputs - Class values to merge.
|
||||||
|
|||||||
@@ -3,11 +3,11 @@ import type React from "react"
|
|||||||
|
|
||||||
export interface ProductModalProps {
|
export interface ProductModalProps {
|
||||||
open: boolean
|
open: boolean
|
||||||
onClose: () => void
|
|
||||||
onSave: (productData: ProductData, imageFile?: File | null) => void;
|
|
||||||
productData: ProductData
|
productData: ProductData
|
||||||
categories: Category[]
|
categories: Category[]
|
||||||
editing: boolean
|
editing: boolean
|
||||||
|
onClose: () => void
|
||||||
|
onSave: (productData: ProductData, imageFile?: File | null) => void;
|
||||||
handleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void
|
handleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void
|
||||||
handleTieredPricingChange: (e: React.ChangeEvent<HTMLInputElement>, index: number) => void
|
handleTieredPricingChange: (e: React.ChangeEvent<HTMLInputElement>, index: number) => void
|
||||||
handleAddTier: () => void
|
handleAddTier: () => void
|
||||||
|
|||||||
5
models/categories.ts
Normal file
5
models/categories.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
export interface Category {
|
||||||
|
_id: string;
|
||||||
|
name: string;
|
||||||
|
parentId?: string
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user