Updates
This commit is contained in:
13
app/_document.tsx
Normal file
13
app/_document.tsx
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { Html, Head, Main, NextScript } from "next/document";
|
||||||
|
|
||||||
|
export default function Document() {
|
||||||
|
return (
|
||||||
|
<Html lang="en">
|
||||||
|
<Head />
|
||||||
|
<body>
|
||||||
|
<Main />
|
||||||
|
<NextScript />
|
||||||
|
</body>
|
||||||
|
</Html>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ import { Plus } from "lucide-react";
|
|||||||
import {
|
import {
|
||||||
fetchProductData,
|
fetchProductData,
|
||||||
saveProductData,
|
saveProductData,
|
||||||
|
saveProductImage,
|
||||||
deleteProductData,
|
deleteProductData,
|
||||||
} from "@/lib/productData";
|
} from "@/lib/productData";
|
||||||
import { ProductModal } from "@/components/modals/product-modal";
|
import { ProductModal } from "@/components/modals/product-modal";
|
||||||
@@ -105,8 +106,11 @@ export default function ProductsPage() {
|
|||||||
setProductData({ ...productData, pricing: updatedPricing });
|
setProductData({ ...productData, pricing: updatedPricing });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
// Save product data after modal form submission
|
// Save product data after modal form submission
|
||||||
const handleSaveProduct = async (data: Product) => {
|
const handleSaveProduct = async (data: Product, file?: File | null) => {
|
||||||
|
console.log("handleSaveProduct:", data, file);
|
||||||
|
|
||||||
const adjustedPricing = data.pricing.map((tier) => ({
|
const adjustedPricing = data.pricing.map((tier) => ({
|
||||||
minQuantity: tier.minQuantity,
|
minQuantity: tier.minQuantity,
|
||||||
pricePerUnit:
|
pricePerUnit:
|
||||||
@@ -118,7 +122,6 @@ export default function ProductsPage() {
|
|||||||
const productToSave: Product = {
|
const productToSave: Product = {
|
||||||
...data,
|
...data,
|
||||||
pricing: adjustedPricing,
|
pricing: adjustedPricing,
|
||||||
image: data.image ?? "", // ✅ Prevents undefined error
|
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -134,6 +137,11 @@ export default function ProductsPage() {
|
|||||||
editing ? "PUT" : "POST"
|
editing ? "PUT" : "POST"
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (file) {
|
||||||
|
await saveProductImage(`${process.env.NEXT_PUBLIC_API_URL}/products/${savedProduct._id}/image`, file, authToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update state with the saved product
|
||||||
setProducts((prevProducts) => {
|
setProducts((prevProducts) => {
|
||||||
if (editing) {
|
if (editing) {
|
||||||
return prevProducts.map((product) =>
|
return prevProducts.map((product) =>
|
||||||
@@ -177,7 +185,7 @@ export default function ProductsPage() {
|
|||||||
minQuantity: tier.minQuantity,
|
minQuantity: tier.minQuantity,
|
||||||
pricePerUnit: tier.pricePerUnit,
|
pricePerUnit: tier.pricePerUnit,
|
||||||
}))
|
}))
|
||||||
: [{ minQuantity: 1, pricePerUnit: 0 }], // Fallback if undefined
|
: [{ minQuantity: 1, pricePerUnit: 0 }],
|
||||||
});
|
});
|
||||||
setEditing(true);
|
setEditing(true);
|
||||||
setModalOpen(true);
|
setModalOpen(true);
|
||||||
|
|||||||
13
app/error.tsx
Normal file
13
app/error.tsx
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
export default function Error({ error, reset }: { error: Error; reset: () => void }) {
|
||||||
|
return (
|
||||||
|
<div className="h-screen flex flex-col items-center justify-center">
|
||||||
|
<h1 className="text-2xl font-semibold text-red-500">Something went wrong!</h1>
|
||||||
|
<p className="text-gray-500">{error.message}</p>
|
||||||
|
<button className="mt-4 px-4 py-2 bg-blue-600 text-white rounded" onClick={() => reset()}>
|
||||||
|
Try Again
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,4 +3,3 @@ import { redirect } from "next/navigation"
|
|||||||
export default function Home() {
|
export default function Home() {
|
||||||
redirect("/dashboard")
|
redirect("/dashboard")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,31 @@
|
|||||||
"use client"
|
"use client";
|
||||||
|
|
||||||
import { useState, useEffect } from "react"
|
import { useState, useEffect } from "react";
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
|
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
|
||||||
import { Button } from "@/components/ui/button"
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input"
|
import { Input } from "@/components/ui/input";
|
||||||
import { Textarea } from "@/components/ui/textarea"
|
import { Textarea } from "@/components/ui/textarea";
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
import {
|
||||||
import { ImageUpload } from "@/components/forms/image-upload"
|
Select,
|
||||||
import { PricingTiers } from "@/components/forms/pricing-tiers"
|
SelectContent,
|
||||||
import type { ProductModalProps, ProductData } from "@/lib/types"
|
SelectItem,
|
||||||
import { toast } from "sonner"
|
SelectTrigger,
|
||||||
import type React from "react" // Import React
|
SelectValue,
|
||||||
|
} from "@/components/ui/select";
|
||||||
|
import { ImageUpload } from "@/components/forms/image-upload";
|
||||||
|
import { PricingTiers } from "@/components/forms/pricing-tiers";
|
||||||
|
import type { ProductModalProps, ProductData } from "@/lib/types";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
import type React from "react";
|
||||||
|
import { Plus } from "lucide-react";
|
||||||
|
import { apiRequest } from "@/lib/storeHelper";
|
||||||
|
|
||||||
|
type CategorySelectProps = {
|
||||||
|
categories: { _id: string; name: string }[];
|
||||||
|
value: string;
|
||||||
|
setProductData: React.Dispatch<React.SetStateAction<ProductData>>;
|
||||||
|
onAddCategory: (newCategory: { _id: string; name: string }) => void;
|
||||||
|
};
|
||||||
|
|
||||||
export const ProductModal: React.FC<ProductModalProps> = ({
|
export const ProductModal: React.FC<ProductModalProps> = ({
|
||||||
open,
|
open,
|
||||||
@@ -25,59 +40,89 @@ export const ProductModal: React.FC<ProductModalProps> = ({
|
|||||||
handleRemoveTier,
|
handleRemoveTier,
|
||||||
setProductData,
|
setProductData,
|
||||||
}) => {
|
}) => {
|
||||||
const [imagePreview, setImagePreview] = useState<string | null>(null)
|
/**
|
||||||
const [imageDimensions, setImageDimensions] = useState({ width: 300, height: 200 })
|
* 1) Store the selected file *separately* from productData.image
|
||||||
|
*/
|
||||||
|
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||||
|
const [imagePreview, setImagePreview] = useState<string | null>(null);
|
||||||
|
const [imageDimensions, setImageDimensions] = useState({ width: 300, height: 200 });
|
||||||
|
const [localCategories, setLocalCategories] = useState(categories);
|
||||||
|
|
||||||
|
// If productData.image is a *URL* (string), show it as a default preview
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (productData.image && typeof productData.image === "string") {
|
if (productData.image && typeof productData.image === "string") {
|
||||||
setImagePreview(productData.image)
|
setImagePreview(productData.image);
|
||||||
}
|
}
|
||||||
}, [productData.image])
|
}, [productData.image]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setLocalCategories(categories);
|
||||||
|
}, [categories]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 2) When user selects a file, store it and create an objectURL for preview
|
||||||
|
*/
|
||||||
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
const file = e.target.files?.[0]
|
const file = e.target.files?.[0];
|
||||||
if (!file) {
|
if (!file) {
|
||||||
setProductData({ ...productData, image: null })
|
// no file selected
|
||||||
setImagePreview(null)
|
setSelectedFile(null);
|
||||||
return
|
setImagePreview(null);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const image = new Image()
|
// For preview
|
||||||
const objectUrl = URL.createObjectURL(file)
|
const objectUrl = URL.createObjectURL(file);
|
||||||
|
setSelectedFile(file);
|
||||||
|
setImagePreview(objectUrl);
|
||||||
|
|
||||||
|
// Optionally, load the image to calculate dimensions
|
||||||
|
const image = new Image();
|
||||||
image.onload = () => {
|
image.onload = () => {
|
||||||
const aspectRatio = image.naturalWidth / image.naturalHeight
|
const aspectRatio = image.naturalWidth / image.naturalHeight;
|
||||||
const width = aspectRatio > 1 ? 300 : 200 * aspectRatio
|
const width = aspectRatio > 1 ? 300 : 200 * aspectRatio;
|
||||||
const height = aspectRatio > 1 ? 300 / aspectRatio : 200
|
const height = aspectRatio > 1 ? 300 / aspectRatio : 200;
|
||||||
|
setImageDimensions({ width, height });
|
||||||
|
};
|
||||||
|
image.src = objectUrl;
|
||||||
|
};
|
||||||
|
|
||||||
setProductData({ ...productData, image: file })
|
/**
|
||||||
setImagePreview(objectUrl)
|
* 3) On 'Save', call the parent onSave(productData, selectedFile)
|
||||||
setImageDimensions({ width, height })
|
*/
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (!productData.category) {
|
||||||
|
toast.error("Please select or add a category");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
image.src = objectUrl
|
onSave(productData, selectedFile);
|
||||||
}
|
toast.success(editing ? "Product updated!" : "Product added!");
|
||||||
|
onClose();
|
||||||
|
};
|
||||||
|
|
||||||
const handleSave = () => {
|
const handleAddCategory = (newCategory: { _id: string; name: string }) => {
|
||||||
onSave(productData)
|
setLocalCategories((prev) => [...prev, newCategory]);
|
||||||
toast.success(editing ? "Product updated!" : "Product added!")
|
};
|
||||||
onClose()
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Dialog open={open} onOpenChange={onClose}>
|
<Dialog open={open} onOpenChange={onClose}>
|
||||||
<DialogContent className="max-w-6xl">
|
<DialogContent className="max-w-6xl">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle className="text-base">{editing ? "Edit Product" : "Add Product"}</DialogTitle>
|
<DialogTitle className="text-base">
|
||||||
|
{editing ? "Edit Product" : "Add Product"}
|
||||||
|
</DialogTitle>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-[2fr_1fr] gap-8 py-4">
|
<div className="grid grid-cols-1 lg:grid-cols-[2fr_1fr] gap-8 py-4">
|
||||||
<ProductBasicInfo
|
<ProductBasicInfo
|
||||||
productData={productData}
|
productData={productData}
|
||||||
handleChange={handleChange}
|
handleChange={handleChange}
|
||||||
categories={categories}
|
categories={localCategories}
|
||||||
setProductData={setProductData}
|
setProductData={setProductData}
|
||||||
|
onAddCategory={handleAddCategory}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<ImageUpload
|
<ImageUpload
|
||||||
imagePreview={imagePreview}
|
imagePreview={imagePreview}
|
||||||
@@ -97,19 +142,22 @@ export const ProductModal: React.FC<ProductModalProps> = ({
|
|||||||
<Button variant="outline" onClick={onClose}>
|
<Button variant="outline" onClick={onClose}>
|
||||||
Cancel
|
Cancel
|
||||||
</Button>
|
</Button>
|
||||||
<Button onClick={handleSave}>{editing ? "Update" : "Create"}</Button>
|
<Button onClick={handleSave}>
|
||||||
|
{editing ? "Update" : "Create"}
|
||||||
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
)
|
);
|
||||||
}
|
};
|
||||||
|
|
||||||
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 }[];
|
||||||
setProductData: React.Dispatch<React.SetStateAction<ProductData>>
|
setProductData: React.Dispatch<React.SetStateAction<ProductData>>;
|
||||||
}> = ({ productData, handleChange, categories, setProductData }) => (
|
onAddCategory: (newCategory: { _id: string; name: string }) => void;
|
||||||
|
}> = ({ productData, handleChange, categories, setProductData, onAddCategory }) => (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<label className="text-sm font-medium">Product Name</label>
|
<label className="text-sm font-medium">Product Name</label>
|
||||||
@@ -134,19 +182,61 @@ const ProductBasicInfo: React.FC<{
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<CategorySelect categories={categories} value={productData.category} setProductData={setProductData} />
|
<CategorySelect
|
||||||
|
categories={categories}
|
||||||
|
value={productData.category}
|
||||||
|
setProductData={setProductData}
|
||||||
|
onAddCategory={onAddCategory}
|
||||||
|
/>
|
||||||
|
|
||||||
<UnitTypeSelect value={productData.unitType} setProductData={setProductData} />
|
<UnitTypeSelect
|
||||||
|
value={productData.unitType}
|
||||||
|
setProductData={setProductData}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
|
|
||||||
const CategorySelect: React.FC<{
|
const CategorySelect: React.FC<CategorySelectProps> = ({
|
||||||
categories: { _id: string; name: string }[]
|
categories,
|
||||||
value: string
|
value,
|
||||||
setProductData: React.Dispatch<React.SetStateAction<ProductData>>
|
setProductData,
|
||||||
}> = ({ categories, value, setProductData }) => (
|
onAddCategory,
|
||||||
<div>
|
}) => {
|
||||||
|
const [isAddingCategory, setIsAddingCategory] = useState(false);
|
||||||
|
const [newCategoryName, setNewCategoryName] = useState("");
|
||||||
|
|
||||||
|
const handleAddCategory = async () => {
|
||||||
|
if (!newCategoryName.trim()) {
|
||||||
|
toast.error("Category name cannot be empty");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await apiRequest("/categories", "POST", { name: newCategoryName });
|
||||||
|
const newCategory = response.data;
|
||||||
|
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 (
|
||||||
|
<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">
|
||||||
|
{isAddingCategory ? (
|
||||||
|
<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={value || "placeholder"}
|
||||||
onValueChange={(val) =>
|
onValueChange={(val) =>
|
||||||
@@ -156,7 +246,7 @@ const CategorySelect: React.FC<{
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<SelectTrigger className="h-9 text-sm">
|
<SelectTrigger className={"h-9 text-sm"}>
|
||||||
<SelectValue placeholder="Select category..." />
|
<SelectValue placeholder="Select category..." />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
@@ -168,15 +258,34 @@ const CategorySelect: React.FC<{
|
|||||||
))}
|
))}
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
)}
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => {
|
||||||
|
if (isAddingCategory) {
|
||||||
|
handleAddCategory();
|
||||||
|
} else {
|
||||||
|
setIsAddingCategory(true);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Plus className="w-4 h-4 mr-1" />
|
||||||
|
{isAddingCategory ? "Save" : "Add"}
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
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 }) => (
|
}> = ({ value, setProductData }) => (
|
||||||
<div>
|
<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">
|
||||||
<Select
|
<Select
|
||||||
value={value || "placeholder"}
|
value={value || "placeholder"}
|
||||||
onValueChange={(val) =>
|
onValueChange={(val) =>
|
||||||
@@ -198,6 +307,10 @@ const UnitTypeSelect: React.FC<{
|
|||||||
<SelectItem value="kg">Kilograms (kg)</SelectItem>
|
<SelectItem value="kg">Kilograms (kg)</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
<Button type="button" variant="outline" size="sm" disabled>
|
||||||
|
<Plus className="w-4 h-4 mr-1" />
|
||||||
|
Add
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
)
|
</div>
|
||||||
|
);
|
||||||
@@ -34,6 +34,25 @@ export const saveProductData = async (
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const saveProductImage = async(url: string, file:File, authToken: string) => {
|
||||||
|
try{
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("file", file);
|
||||||
|
|
||||||
|
return await fetchData(url, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${authToken}`,
|
||||||
|
//"Content-Type": "multipart/form-data",
|
||||||
|
},
|
||||||
|
body: formData,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error uploading image:", error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const deleteProductData = async (url: string, authToken: string) => {
|
export const deleteProductData = async (url: string, authToken: string) => {
|
||||||
try {
|
try {
|
||||||
return await fetchData(url, {
|
return await fetchData(url, {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import type React from "react"
|
|||||||
export interface ProductModalProps {
|
export interface ProductModalProps {
|
||||||
open: boolean
|
open: boolean
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
onSave: (productData: ProductData) => void
|
onSave: (productData: ProductData, imageFile?: File | null) => void;
|
||||||
productData: ProductData
|
productData: ProductData
|
||||||
categories: Category[]
|
categories: Category[]
|
||||||
editing: boolean
|
editing: boolean
|
||||||
|
|||||||
Reference in New Issue
Block a user