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 {
|
||||
fetchProductData,
|
||||
saveProductData,
|
||||
saveProductImage,
|
||||
deleteProductData,
|
||||
} from "@/lib/productData";
|
||||
import { ProductModal } from "@/components/modals/product-modal";
|
||||
@@ -105,8 +106,11 @@ export default function ProductsPage() {
|
||||
setProductData({ ...productData, pricing: updatedPricing });
|
||||
};
|
||||
|
||||
|
||||
// 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) => ({
|
||||
minQuantity: tier.minQuantity,
|
||||
pricePerUnit:
|
||||
@@ -118,7 +122,6 @@ export default function ProductsPage() {
|
||||
const productToSave: Product = {
|
||||
...data,
|
||||
pricing: adjustedPricing,
|
||||
image: data.image ?? "", // ✅ Prevents undefined error
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -134,6 +137,11 @@ export default function ProductsPage() {
|
||||
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) => {
|
||||
if (editing) {
|
||||
return prevProducts.map((product) =>
|
||||
@@ -177,7 +185,7 @@ export default function ProductsPage() {
|
||||
minQuantity: tier.minQuantity,
|
||||
pricePerUnit: tier.pricePerUnit,
|
||||
}))
|
||||
: [{ minQuantity: 1, pricePerUnit: 0 }], // Fallback if undefined
|
||||
: [{ minQuantity: 1, pricePerUnit: 0 }],
|
||||
});
|
||||
setEditing(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() {
|
||||
redirect("/dashboard")
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,31 @@
|
||||
"use client"
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, 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 React
|
||||
import { useState, useEffect } from "react";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
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> = ({
|
||||
open,
|
||||
@@ -25,59 +40,89 @@ export const ProductModal: React.FC<ProductModalProps> = ({
|
||||
handleRemoveTier,
|
||||
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(() => {
|
||||
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 file = e.target.files?.[0]
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) {
|
||||
setProductData({ ...productData, image: null })
|
||||
setImagePreview(null)
|
||||
return
|
||||
// no file selected
|
||||
setSelectedFile(null);
|
||||
setImagePreview(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const image = new Image()
|
||||
const objectUrl = URL.createObjectURL(file)
|
||||
// For preview
|
||||
const objectUrl = URL.createObjectURL(file);
|
||||
setSelectedFile(file);
|
||||
setImagePreview(objectUrl);
|
||||
|
||||
// Optionally, load the image to calculate dimensions
|
||||
const image = new Image();
|
||||
image.onload = () => {
|
||||
const aspectRatio = image.naturalWidth / image.naturalHeight
|
||||
const width = aspectRatio > 1 ? 300 : 200 * aspectRatio
|
||||
const height = aspectRatio > 1 ? 300 / aspectRatio : 200
|
||||
const aspectRatio = image.naturalWidth / image.naturalHeight;
|
||||
const width = aspectRatio > 1 ? 300 : 200 * aspectRatio;
|
||||
const height = aspectRatio > 1 ? 300 / aspectRatio : 200;
|
||||
setImageDimensions({ width, height });
|
||||
};
|
||||
image.src = objectUrl;
|
||||
};
|
||||
|
||||
setProductData({ ...productData, image: file })
|
||||
setImagePreview(objectUrl)
|
||||
setImageDimensions({ width, height })
|
||||
/**
|
||||
* 3) On 'Save', call the parent onSave(productData, selectedFile)
|
||||
*/
|
||||
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 = () => {
|
||||
onSave(productData)
|
||||
toast.success(editing ? "Product updated!" : "Product added!")
|
||||
onClose()
|
||||
}
|
||||
const handleAddCategory = (newCategory: { _id: string; name: string }) => {
|
||||
setLocalCategories((prev) => [...prev, newCategory]);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onClose}>
|
||||
<DialogContent className="max-w-6xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-base">{editing ? "Edit Product" : "Add Product"}</DialogTitle>
|
||||
<DialogTitle className="text-base">
|
||||
{editing ? "Edit Product" : "Add Product"}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-[2fr_1fr] gap-8 py-4">
|
||||
<ProductBasicInfo
|
||||
productData={productData}
|
||||
handleChange={handleChange}
|
||||
categories={categories}
|
||||
categories={localCategories}
|
||||
setProductData={setProductData}
|
||||
onAddCategory={handleAddCategory}
|
||||
/>
|
||||
|
||||
<div className="space-y-6">
|
||||
<ImageUpload
|
||||
imagePreview={imagePreview}
|
||||
@@ -97,19 +142,22 @@ export const ProductModal: React.FC<ProductModalProps> = ({
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSave}>{editing ? "Update" : "Create"}</Button>
|
||||
<Button onClick={handleSave}>
|
||||
{editing ? "Update" : "Create"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
const ProductBasicInfo: React.FC<{
|
||||
productData: ProductData
|
||||
handleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void
|
||||
categories: { _id: string; name: string }[]
|
||||
setProductData: React.Dispatch<React.SetStateAction<ProductData>>
|
||||
}> = ({ productData, handleChange, categories, setProductData }) => (
|
||||
productData: ProductData;
|
||||
handleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
|
||||
categories: { _id: string; name: string }[];
|
||||
setProductData: React.Dispatch<React.SetStateAction<ProductData>>;
|
||||
onAddCategory: (newCategory: { _id: string; name: string }) => void;
|
||||
}> = ({ productData, handleChange, categories, setProductData, onAddCategory }) => (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium">Product Name</label>
|
||||
@@ -134,19 +182,61 @@ const ProductBasicInfo: React.FC<{
|
||||
/>
|
||||
</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>
|
||||
)
|
||||
);
|
||||
|
||||
const CategorySelect: React.FC<{
|
||||
categories: { _id: string; name: string }[]
|
||||
value: string
|
||||
setProductData: React.Dispatch<React.SetStateAction<ProductData>>
|
||||
}> = ({ categories, value, setProductData }) => (
|
||||
<div>
|
||||
const CategorySelect: React.FC<CategorySelectProps> = ({
|
||||
categories,
|
||||
value,
|
||||
setProductData,
|
||||
onAddCategory,
|
||||
}) => {
|
||||
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>
|
||||
<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
|
||||
value={value || "placeholder"}
|
||||
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..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -168,15 +258,34 @@ const CategorySelect: React.FC<{
|
||||
))}
|
||||
</SelectContent>
|
||||
</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>
|
||||
);
|
||||
};
|
||||
|
||||
const UnitTypeSelect: React.FC<{
|
||||
value: string
|
||||
setProductData: React.Dispatch<React.SetStateAction<ProductData>>
|
||||
value: string;
|
||||
setProductData: React.Dispatch<React.SetStateAction<ProductData>>;
|
||||
}> = ({ value, setProductData }) => (
|
||||
<div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">Unit Type</label>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Select
|
||||
value={value || "placeholder"}
|
||||
onValueChange={(val) =>
|
||||
@@ -198,6 +307,10 @@ const UnitTypeSelect: React.FC<{
|
||||
<SelectItem value="kg">Kilograms (kg)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button type="button" variant="outline" size="sm" disabled>
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
Add
|
||||
</Button>
|
||||
</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) => {
|
||||
try {
|
||||
return await fetchData(url, {
|
||||
|
||||
@@ -4,7 +4,7 @@ import type React from "react"
|
||||
export interface ProductModalProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onSave: (productData: ProductData) => void
|
||||
onSave: (productData: ProductData, imageFile?: File | null) => void;
|
||||
productData: ProductData
|
||||
categories: Category[]
|
||||
editing: boolean
|
||||
|
||||
Reference in New Issue
Block a user