Merge branch 'mann-Branch'
This commit is contained in:
@@ -1,12 +1,6 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Link, useNavigate } from "react-router-dom";
|
||||
import {
|
||||
Tag,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Bookmark,
|
||||
BookmarkCheck,
|
||||
} from "lucide-react";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { Tag, ChevronLeft, ChevronRight, Bookmark, Loader } from "lucide-react";
|
||||
|
||||
import FloatingAlert from "../components/FloatingAlert"; // adjust path if needed
|
||||
|
||||
@@ -14,38 +8,50 @@ const Home = () => {
|
||||
const navigate = useNavigate();
|
||||
const [listings, setListings] = useState([]);
|
||||
const [recommended, setRecommended] = useState([]);
|
||||
const [history, sethistory] = useState([]);
|
||||
const [history, setHistory] = useState([]);
|
||||
const [error, setError] = useState(null);
|
||||
const [showAlert, setShowAlert] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState({
|
||||
recommendations: true,
|
||||
listings: true,
|
||||
history: true,
|
||||
});
|
||||
const recommendationsFetched = useRef(false);
|
||||
const historyFetched = useRef(false);
|
||||
|
||||
//After user data storing the session.
|
||||
const storedUser = JSON.parse(sessionStorage.getItem("user"));
|
||||
|
||||
const toggleFavorite = async (id) => {
|
||||
const response = await fetch(
|
||||
"http://localhost:3030/api/product/addFavorite",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
try {
|
||||
const response = await fetch(
|
||||
"http://localhost:3030/api/product/addFavorite",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
userID: storedUser.ID,
|
||||
productID: id,
|
||||
}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
userID: storedUser.ID,
|
||||
productID: id,
|
||||
}),
|
||||
},
|
||||
);
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
setShowAlert(true);
|
||||
);
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
setShowAlert(true);
|
||||
// Close alert after 3 seconds
|
||||
setTimeout(() => setShowAlert(false), 3000);
|
||||
}
|
||||
console.log(`Add Product -> Favorites: ${id}`);
|
||||
} catch (error) {
|
||||
console.error("Error adding favorite:", error);
|
||||
}
|
||||
console.log(`Add Product -> History: ${id}`);
|
||||
};
|
||||
|
||||
const addHistory = async (id) => {
|
||||
const response = await fetch(
|
||||
"http://localhost:3030/api/history/addHistory",
|
||||
{
|
||||
try {
|
||||
await fetch("http://localhost:3030/api/history/addHistory", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
@@ -54,23 +60,23 @@ const Home = () => {
|
||||
userID: storedUser.ID,
|
||||
productID: id,
|
||||
}),
|
||||
},
|
||||
);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error adding to history:", error);
|
||||
}
|
||||
};
|
||||
|
||||
function reloadPage() {
|
||||
var doctTimestamp = new Date(performance.timing.domLoading).getTime();
|
||||
var now = Date.now();
|
||||
var tenSec = 10 * 1000;
|
||||
if (now > doctTimestamp + tenSec) {
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
reloadPage();
|
||||
|
||||
// Fetch recommended products
|
||||
useEffect(() => {
|
||||
const fetchrecomProducts = async () => {
|
||||
const fetchRecommendedProducts = async () => {
|
||||
// Skip if already fetched or no user data
|
||||
if (recommendationsFetched.current || !storedUser || !storedUser.ID)
|
||||
return;
|
||||
|
||||
setIsLoading((prev) => ({ ...prev, recommendations: true }));
|
||||
try {
|
||||
recommendationsFetched.current = true; // Mark as fetched before the API call
|
||||
|
||||
const response = await fetch(
|
||||
"http://localhost:3030/api/engine/recommended",
|
||||
{
|
||||
@@ -83,36 +89,42 @@ const Home = () => {
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!response.ok) throw new Error("Failed to fetch products");
|
||||
if (!response.ok) throw new Error("Failed to fetch recommendations");
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
setRecommended(
|
||||
data.data.map((product) => ({
|
||||
id: product.ProductID,
|
||||
title: product.ProductName, // Use the alias from SQL
|
||||
title: product.ProductName,
|
||||
price: product.Price,
|
||||
category: product.Category, // Ensure this gets the category name
|
||||
image: product.ProductImage, // Use the alias for image URL
|
||||
seller: product.SellerName, // Fetch seller name properly
|
||||
datePosted: product.DateUploaded, // Use the actual date
|
||||
isFavorite: false, // Default state
|
||||
category: product.Category,
|
||||
image: product.ProductImage,
|
||||
seller: product.SellerName,
|
||||
datePosted: product.DateUploaded,
|
||||
isFavorite: false,
|
||||
})),
|
||||
);
|
||||
reloadPage();
|
||||
} else {
|
||||
throw new Error(data.message || "Error fetching products");
|
||||
throw new Error(data.message || "Error fetching recommendations");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching products:", error);
|
||||
console.error("Error fetching recommendations:", error);
|
||||
setError(error.message);
|
||||
// Reset the flag if there's an error so it can try again
|
||||
recommendationsFetched.current = false;
|
||||
} finally {
|
||||
setIsLoading((prev) => ({ ...prev, recommendations: false }));
|
||||
}
|
||||
};
|
||||
fetchrecomProducts();
|
||||
}, []);
|
||||
|
||||
fetchRecommendedProducts();
|
||||
}, [storedUser]); // Keep dependency
|
||||
|
||||
// Fetch all products
|
||||
useEffect(() => {
|
||||
const fetchProducts = async () => {
|
||||
setIsLoading((prev) => ({ ...prev, listings: true }));
|
||||
try {
|
||||
const response = await fetch(
|
||||
"http://localhost:3030/api/product/getProduct",
|
||||
@@ -120,18 +132,17 @@ const Home = () => {
|
||||
if (!response.ok) throw new Error("Failed to fetch products");
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setListings(
|
||||
data.data.map((product) => ({
|
||||
id: product.ProductID,
|
||||
title: product.ProductName, // Use the alias from SQL
|
||||
title: product.ProductName,
|
||||
price: product.Price,
|
||||
category: product.Category, // Ensure this gets the category name
|
||||
image: product.ProductImage, // Use the alias for image URL
|
||||
seller: product.SellerName, // Fetch seller name properly
|
||||
datePosted: product.DateUploaded, // Use the actual date
|
||||
isFavorite: false, // Default state
|
||||
category: product.Category,
|
||||
image: product.ProductImage,
|
||||
seller: product.SellerName,
|
||||
datePosted: product.DateUploaded,
|
||||
isFavorite: false,
|
||||
})),
|
||||
);
|
||||
} else {
|
||||
@@ -140,15 +151,24 @@ const Home = () => {
|
||||
} catch (error) {
|
||||
console.error("Error fetching products:", error);
|
||||
setError(error.message);
|
||||
} finally {
|
||||
setIsLoading((prev) => ({ ...prev, listings: false }));
|
||||
}
|
||||
};
|
||||
|
||||
fetchProducts();
|
||||
}, []);
|
||||
|
||||
// Fetch user history
|
||||
useEffect(() => {
|
||||
const fetchrecomProducts = async () => {
|
||||
// Get the user's data from localStorage
|
||||
const fetchUserHistory = async () => {
|
||||
// Skip if already fetched or no user data
|
||||
if (historyFetched.current || !storedUser || !storedUser.ID) return;
|
||||
|
||||
setIsLoading((prev) => ({ ...prev, history: true }));
|
||||
try {
|
||||
historyFetched.current = true; // Mark as fetched before the API call
|
||||
|
||||
const response = await fetch(
|
||||
"http://localhost:3030/api/history/getHistory",
|
||||
{
|
||||
@@ -161,52 +181,168 @@ const Home = () => {
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!response.ok) throw new Error("Failed to fetch products");
|
||||
if (!response.ok) throw new Error("Failed to fetch history");
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
sethistory(
|
||||
setHistory(
|
||||
data.data.map((product) => ({
|
||||
id: product.ProductID,
|
||||
title: product.ProductName, // Use the alias from SQL
|
||||
title: product.ProductName,
|
||||
price: product.Price,
|
||||
category: product.Category, // Ensure this gets the category name
|
||||
image: product.ProductImage, // Use the alias for image URL
|
||||
seller: product.SellerName, // Fetch seller name properly
|
||||
datePosted: product.DateUploaded, // Use the actual date
|
||||
category: product.Category,
|
||||
image: product.ProductImage,
|
||||
seller: product.SellerName,
|
||||
datePosted: product.DateUploaded,
|
||||
})),
|
||||
);
|
||||
} else {
|
||||
throw new Error(data.message || "Error fetching products");
|
||||
throw new Error(data.message || "Error fetching history");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching products:", error);
|
||||
console.error("Error fetching history:", error);
|
||||
setError(error.message);
|
||||
// Reset the flag if there's an error so it can try again
|
||||
historyFetched.current = false;
|
||||
} finally {
|
||||
setIsLoading((prev) => ({ ...prev, history: false }));
|
||||
}
|
||||
};
|
||||
fetchrecomProducts();
|
||||
}, []);
|
||||
|
||||
fetchUserHistory();
|
||||
}, [storedUser]); // Keep dependency
|
||||
|
||||
const handleSelling = () => {
|
||||
navigate("/selling");
|
||||
};
|
||||
|
||||
// Loading indicator component
|
||||
const LoadingSection = () => (
|
||||
<div className="flex justify-center items-center h-48">
|
||||
<Loader className="animate-spin text-emerald-600 h-8 w-8" />
|
||||
</div>
|
||||
);
|
||||
|
||||
// Product card component to reduce duplication
|
||||
const ProductCard = ({ product, addToHistory = false }) => (
|
||||
<Link
|
||||
key={product.id}
|
||||
to={`/product/${product.id}`}
|
||||
onClick={addToHistory ? () => addHistory(product.id) : undefined}
|
||||
className="bg-white border border-gray-200 hover:shadow-md transition-shadow w-70 flex-shrink-0 relative"
|
||||
>
|
||||
<div className="relative">
|
||||
<img
|
||||
src={product.image}
|
||||
alt={product.title}
|
||||
className="w-full h-48 object-cover"
|
||||
/>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
toggleFavorite(product.id);
|
||||
}}
|
||||
className="absolute top-0 right-0 p-2 rounded-bl-md bg-emerald-600 hover:bg-emerald-500 transition shadow-sm"
|
||||
>
|
||||
<Bookmark className="text-white w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-4">
|
||||
<h3 className="text-lg font-medium text-gray-800 leading-tight">
|
||||
{product.title}
|
||||
</h3>
|
||||
<span className="font-semibold text-emerald-600 block mt-1">
|
||||
${product.price}
|
||||
</span>
|
||||
|
||||
<div className="flex items-center text-sm text-gray-500 mt-2">
|
||||
<Tag className="h-4 w-4 mr-1" />
|
||||
<span>{product.category}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between items-center pt-2 border-t border-gray-100 mt-3">
|
||||
<span className="text-xs text-gray-500">{product.datePosted}</span>
|
||||
<span className="text-sm font-medium text-gray-700">
|
||||
{product.seller}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
|
||||
// Scrollable product list component to reduce duplication
|
||||
const ScrollableProductList = ({
|
||||
containerId,
|
||||
products,
|
||||
children,
|
||||
isLoading,
|
||||
addToHistory = false,
|
||||
}) => (
|
||||
<div className="relative py-4">
|
||||
{children}
|
||||
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() =>
|
||||
document
|
||||
.getElementById(containerId)
|
||||
.scrollBy({ left: -400, behavior: "smooth" })
|
||||
}
|
||||
className="absolute left-0 top-1/2 transform -translate-y-1/2 bg-gray-800 bg-opacity-70 text-white p-4 rounded-full z-20 hidden md:flex items-center justify-center w-12 h-12"
|
||||
>
|
||||
<ChevronLeft size={24} />
|
||||
</button>
|
||||
|
||||
<div
|
||||
id={containerId}
|
||||
className="overflow-x-auto whitespace-nowrap flex space-x-6 scroll-smooth scrollbar-hide px-10 pl-0 rounded min-h-[250px]"
|
||||
>
|
||||
{isLoading ? (
|
||||
<LoadingSection />
|
||||
) : products.length > 0 ? (
|
||||
products.map((product) => (
|
||||
<ProductCard
|
||||
key={product.id}
|
||||
product={product}
|
||||
addToHistory={addToHistory}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<div className="flex justify-center items-center w-full h-48 text-gray-500">
|
||||
No products available
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() =>
|
||||
document
|
||||
.getElementById(containerId)
|
||||
.scrollBy({ left: 400, behavior: "smooth" })
|
||||
}
|
||||
className="absolute right-0 top-1/2 transform -translate-y-1/2 bg-gray-800 bg-opacity-70 text-white p-4 rounded-full z-20 hidden md:flex items-center justify-center w-12 h-12"
|
||||
>
|
||||
<ChevronRight size={24} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col min-h-screen">
|
||||
<div className="flex-grow">
|
||||
{/* Hero Section with School Background */}
|
||||
<div className="relative py-12 px-4 mb-8 shadow-sm">
|
||||
{/* Background Image - Positioned at bottom */}
|
||||
<div className="absolute inset-0 z-0 overflow-hidden bg-black bg-opacity-100">
|
||||
<img
|
||||
src="../public/Ucalgary.png"
|
||||
alt="University of Calgary"
|
||||
className="w-full h-full object-cover object-bottom opacity-50"
|
||||
className="w-full h-full object-cover object-bottom opacity-45"
|
||||
/>
|
||||
{/* Dark overlay for better text readability */}
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="max-w-2xl mx-auto text-center relative z-1">
|
||||
<h1 className="text-3xl font-bold text-white mb-4">
|
||||
Buy and Sell on Campus
|
||||
@@ -217,297 +353,60 @@ const Home = () => {
|
||||
</p>
|
||||
<button
|
||||
onClick={handleSelling}
|
||||
className="bg-emerald-500 hover:bg-emerald-600 text-white font-medium py-2 px-6 focus:outline-none focus:ring-2 focus:ring-emerald-400 transition-colors"
|
||||
className="bg-emerald-600 hover:bg-emerald-700 text-white font-medium py-2 px-6 focus:outline-none focus:ring-2 focus:ring-emerald-400 transition-colors"
|
||||
>
|
||||
Post an Item
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Recent Listings */}
|
||||
{/* Floating Alert */}
|
||||
{showAlert && (
|
||||
<FloatingAlert
|
||||
message="Product added to favorites!"
|
||||
onClose={() => setShowAlert(false)}
|
||||
/>
|
||||
)}
|
||||
<div className="relative py-4">
|
||||
|
||||
{/* Recommendations Section */}
|
||||
<ScrollableProductList
|
||||
containerId="RecomContainer"
|
||||
products={recommended}
|
||||
isLoading={isLoading.recommendations}
|
||||
addToHistory={true}
|
||||
>
|
||||
<h2 className="text-xl font-semibold text-gray-800 mb-4">
|
||||
Recommendation
|
||||
Recommended For You
|
||||
</h2>
|
||||
</ScrollableProductList>
|
||||
|
||||
<div className="relative">
|
||||
{/* Left Button - Overlaid on products */}
|
||||
<button
|
||||
onClick={() =>
|
||||
document
|
||||
.getElementById("RecomContainer")
|
||||
.scrollBy({ left: -400, behavior: "smooth" })
|
||||
}
|
||||
className="absolute left-0 top-1/2 transform -translate-y-1/2 bg-gray-800 bg-opacity-70 text-white p-4 rounded-full z-20 hidden md:flex items-center justify-center w-12 h-12"
|
||||
>
|
||||
<ChevronLeft size={24} />{" "}
|
||||
</button>
|
||||
|
||||
{/* Scrollable Listings Container */}
|
||||
<div
|
||||
id="RecomContainer"
|
||||
className="overflow-x-auto whitespace-nowrap flex space-x-6 scroll-smooth scrollbar-hide px-10 pl-0 rounded"
|
||||
>
|
||||
{recommended.map((recommended) => (
|
||||
<Link
|
||||
key={recommended.id}
|
||||
to={`/product/${recommended.id}`}
|
||||
onClick={() => addHistory(recommended.id)}
|
||||
className="bg-white border border-gray-200 hover:shadow-md transition-shadow w-70 flex-shrink-0 relative"
|
||||
>
|
||||
<div className="relative">
|
||||
<img
|
||||
src={recommended.image}
|
||||
alt={recommended.title}
|
||||
className="w-full h-48 object-cover"
|
||||
/>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
toggleFavorite(recommended.id);
|
||||
}}
|
||||
className="absolute top-0 right-0 p-2 rounded-bl-md bg-emerald-600 hover:bg-emerald-500 transition shadow-sm"
|
||||
>
|
||||
<Bookmark className="text-white w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-4">
|
||||
<h3 className="text-lg font-medium text-gray-800 leading-tight">
|
||||
{recommended.title}
|
||||
</h3>
|
||||
<span className="font-semibold text-emerald-600 block mt-1">
|
||||
${recommended.price}
|
||||
</span>
|
||||
|
||||
<div className="flex items-center text-sm text-gray-500 mt-2">
|
||||
<Tag className="h-4 w-4 mr-1" />
|
||||
<span>{recommended.category}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between items-center pt-2 border-t border-gray-100 mt-3">
|
||||
<span className="text-xs text-gray-500">
|
||||
{recommended.datePosted}
|
||||
</span>
|
||||
<span className="text-sm font-medium text-gray-700">
|
||||
{recommended.seller}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Right Button - Overlaid on products */}
|
||||
<button
|
||||
onClick={() =>
|
||||
document
|
||||
.getElementById("RecomContainer")
|
||||
.scrollBy({ left: 400, behavior: "smooth" })
|
||||
}
|
||||
className="absolute right-0 top-1/2 transform -translate-y-1/2 bg-gray-800 bg-opacity-70 text-white p-4 rounded-full z-20 hidden md:flex items-center justify-center w-12 h-12"
|
||||
>
|
||||
<ChevronRight size={24} />{" "}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Recent Listings */}
|
||||
{showAlert && (
|
||||
<FloatingAlert
|
||||
message="Product added to favorites!"
|
||||
onClose={() => setShowAlert(false)}
|
||||
/>
|
||||
)}
|
||||
<div className="relative py-4">
|
||||
{/* Recent Listings Section */}
|
||||
<ScrollableProductList
|
||||
containerId="listingsContainer"
|
||||
products={listings}
|
||||
isLoading={isLoading.listings}
|
||||
addToHistory={true}
|
||||
>
|
||||
<h2 className="text-xl font-semibold text-gray-800 mb-4">
|
||||
Recent Listings
|
||||
</h2>
|
||||
|
||||
<div className="relative">
|
||||
{/* Left Button - Overlaid on products */}
|
||||
<button
|
||||
onClick={() =>
|
||||
document
|
||||
.getElementById("listingsContainer")
|
||||
.scrollBy({ left: -400, behavior: "smooth" })
|
||||
}
|
||||
className="absolute left-0 top-1/2 transform -translate-y-1/2 bg-gray-800 bg-opacity-70 text-white p-4 rounded-full z-20 hidden md:flex items-center justify-center w-12 h-12"
|
||||
>
|
||||
<ChevronLeft size={24} />{" "}
|
||||
</button>
|
||||
|
||||
{/* Scrollable Listings Container */}
|
||||
<div
|
||||
id="listingsContainer"
|
||||
className="overflow-x-auto whitespace-nowrap flex space-x-6 scroll-smooth scrollbar-hide px-10 pl-0"
|
||||
>
|
||||
{listings.map((listing) => (
|
||||
<Link
|
||||
key={listing.id}
|
||||
to={`/product/${listing.id}`}
|
||||
className="bg-white border border-gray-200 hover:shadow-md transition-shadow w-70 flex-shrink-0 relative"
|
||||
>
|
||||
<div className="relative">
|
||||
<img
|
||||
src={listing.image}
|
||||
alt={listing.title}
|
||||
onClick={() => addHistory(listing.id)}
|
||||
className="w-full h-48 object-cover"
|
||||
/>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
toggleFavorite(listing.id);
|
||||
}}
|
||||
className="absolute top-0 right-0 p-2 rounded-bl-md bg-emerald-600 hover:bg-emerald-500 transition shadow-sm"
|
||||
>
|
||||
<Bookmark className="text-white w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-4">
|
||||
<h3 className="text-lg font-medium text-gray-800 leading-tight">
|
||||
{listing.title}
|
||||
</h3>
|
||||
<span className="font-semibold text-emerald-600 block mt-1">
|
||||
${listing.price}
|
||||
</span>
|
||||
|
||||
<div className="flex items-center text-sm text-gray-500 mt-2">
|
||||
<Tag className="h-4 w-4 mr-1" />
|
||||
<span>{listing.category}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between items-center pt-2 border-t border-gray-100 mt-3">
|
||||
<span className="text-xs text-gray-500">
|
||||
{listing.datePosted}
|
||||
</span>
|
||||
<span className="text-sm font-medium text-gray-700">
|
||||
{listing.seller}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Right Button - Overlaid on products */}
|
||||
<button
|
||||
onClick={() =>
|
||||
document
|
||||
.getElementById("listingsContainer")
|
||||
.scrollBy({ left: 400, behavior: "smooth" })
|
||||
}
|
||||
className="absolute right-0 top-1/2 transform -translate-y-1/2 bg-gray-800 bg-opacity-70 text-white p-4 rounded-full z-20 hidden md:flex items-center justify-center w-12 h-12"
|
||||
>
|
||||
<ChevronRight size={24} />{" "}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</ScrollableProductList>
|
||||
|
||||
{/* History Section */}
|
||||
{showAlert && (
|
||||
<FloatingAlert
|
||||
message="Product added to favorites!"
|
||||
onClose={() => setShowAlert(false)}
|
||||
/>
|
||||
{(history.length > 0 || isLoading.history) && (
|
||||
<ScrollableProductList
|
||||
containerId="HistoryContainer"
|
||||
products={history}
|
||||
isLoading={isLoading.history}
|
||||
>
|
||||
<h2 className="text-xl font-semibold text-gray-800 mb-4">
|
||||
Your Browsing History
|
||||
</h2>
|
||||
</ScrollableProductList>
|
||||
)}
|
||||
<div className="relative py-4">
|
||||
<h2 className="text-xl font-semibold text-gray-800 mb-4">History</h2>
|
||||
|
||||
<div className="relative">
|
||||
{/* Left Button - Overlaid on products */}
|
||||
<button
|
||||
onClick={() =>
|
||||
document
|
||||
.getElementById("HistoryContainer")
|
||||
.scrollBy({ left: -400, behavior: "smooth" })
|
||||
}
|
||||
className="absolute left-0 top-1/2 transform -translate-y-1/2 bg-gray-800 bg-opacity-70 text-white p-4 rounded-full z-20 hidden md:flex items-center justify-center w-12 h-12"
|
||||
>
|
||||
<ChevronLeft size={24} />{" "}
|
||||
</button>
|
||||
|
||||
{/* Scrollable Listings Container */}
|
||||
<div
|
||||
id="HistoryContainer"
|
||||
className="overflow-x-auto whitespace-nowrap flex space-x-6 scroll-smooth scrollbar-hide px-10 pl-0"
|
||||
>
|
||||
{history.map((history) => (
|
||||
<Link
|
||||
key={history.id}
|
||||
to={`/product/${history.id}`}
|
||||
className="bg-white border border-gray-200 hover:shadow-md transition-shadow w-70 flex-shrink-0 relative"
|
||||
>
|
||||
<div className="relative">
|
||||
<img
|
||||
src={history.image}
|
||||
alt={history.title}
|
||||
className="w-full h-48 object-cover"
|
||||
/>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
toggleFavorite(history.id);
|
||||
}}
|
||||
className="absolute top-0 right-0 p-2 rounded-bl-md bg-emerald-600 hover:bg-emerald-500 transition shadow-sm"
|
||||
>
|
||||
<Bookmark className="text-white w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-4">
|
||||
<h3 className="text-lg font-medium text-gray-800 leading-tight">
|
||||
{history.title}
|
||||
</h3>
|
||||
<span className="font-semibold text-emerald-600 block mt-1">
|
||||
${history.price}
|
||||
</span>
|
||||
|
||||
<div className="flex items-center text-sm text-gray-500 mt-2">
|
||||
<Tag className="h-4 w-4 mr-1" />
|
||||
<span>{history.category}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-between items-center pt-2 border-t border-gray-100 mt-3">
|
||||
<span className="text-xs text-gray-500">
|
||||
{history.datePosted}
|
||||
</span>
|
||||
<span className="text-sm font-medium text-gray-700">
|
||||
{history.seller}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Right Button - Overlaid on products */}
|
||||
<button
|
||||
onClick={() =>
|
||||
document
|
||||
.getElementById("HistoryContainer")
|
||||
.scrollBy({ left: 400, behavior: "smooth" })
|
||||
}
|
||||
className="absolute right-0 top-1/2 transform -translate-y-1/2 bg-gray-800 bg-opacity-70 text-white p-4 rounded-full z-20 hidden md:flex items-center justify-center w-12 h-12"
|
||||
>
|
||||
<ChevronRight size={24} />{" "}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer - Added here */}
|
||||
{/* Footer */}
|
||||
<footer className="bg-gray-800 text-white py-6 mt-12">
|
||||
<div className="container mx-auto px-4">
|
||||
<div className="flex flex-col md:flex-row justify-between items-center">
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useParams, Link } from "react-router-dom";
|
||||
import {
|
||||
Heart,
|
||||
ArrowLeft,
|
||||
Tag,
|
||||
User,
|
||||
@@ -26,7 +25,6 @@ const ProductDetail = () => {
|
||||
reviews: null,
|
||||
submit: null,
|
||||
});
|
||||
const [isFavorite, setIsFavorite] = useState(false);
|
||||
const [showContactOptions, setShowContactOptions] = useState(false);
|
||||
const [currentImage, setCurrentImage] = useState(0);
|
||||
const [reviews, setReviews] = useState([]);
|
||||
@@ -52,7 +50,6 @@ const ProductDetail = () => {
|
||||
if (data.success) {
|
||||
setShowAlert(true);
|
||||
}
|
||||
console.log(`Add Product -> History: ${id}`);
|
||||
};
|
||||
|
||||
const [reviewForm, setReviewForm] = useState({
|
||||
@@ -248,7 +245,7 @@ const ProductDetail = () => {
|
||||
if (loading.product) {
|
||||
return (
|
||||
<div className="flex justify-center items-center h-screen">
|
||||
<div className="animate-spin h-32 w-32 border-t-2 border-green-500"></div>
|
||||
<div className="animate-spin h-32 w-32 border-t-2 border-emerald-600"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -262,7 +259,7 @@ const ProductDetail = () => {
|
||||
<p className="text-gray-600">{error.product}</p>
|
||||
<Link
|
||||
to="/"
|
||||
className="mt-4 inline-block bg-green-500 text-white px-4 py-2 hover:bg-green-600"
|
||||
className="mt-4 inline-block bg-emerald-600 text-white px-4 py-2 hover:bg-emerald-700"
|
||||
>
|
||||
Back to Listings
|
||||
</Link>
|
||||
@@ -279,7 +276,7 @@ const ProductDetail = () => {
|
||||
<h2 className="text-2xl text-red-500 mb-4">Product Not Found</h2>
|
||||
<Link
|
||||
to="/"
|
||||
className="mt-4 inline-block bg-green-500 text-white px-4 py-2 hover:bg-green-600"
|
||||
className="mt-4 inline-block bg-emerald-600 text-white px-4 py-2 hover:bg-emerald-700"
|
||||
>
|
||||
Back to Listings
|
||||
</Link>
|
||||
@@ -291,15 +288,15 @@ const ProductDetail = () => {
|
||||
// Render product details
|
||||
return (
|
||||
<div className="max-w-6xl mx-auto px-4 py-8">
|
||||
<div className="mb-6">
|
||||
{/* <div className="mb-6">
|
||||
<Link
|
||||
to="/search"
|
||||
className="flex items-center text-green-600 hover:text-green-700"
|
||||
className="flex items-center text-emerald-700 hover:text-emerald-700"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-1" />
|
||||
<span>Back</span>
|
||||
</Link>
|
||||
</div>
|
||||
</div> */}
|
||||
{showAlert && (
|
||||
<FloatingAlert
|
||||
message="Product added to favorites!"
|
||||
@@ -351,7 +348,7 @@ const ProductDetail = () => {
|
||||
{product.images.map((image, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={`bg-white border ${currentImage === index ? "border-green-500 border-2" : "border-gray-200"} min-w-[100px] cursor-pointer`}
|
||||
className={`bg-white border ${currentImage === index ? "border-emerald-600 border-2" : "border-gray-200"} min-w-[100px] cursor-pointer`}
|
||||
onClick={() => selectImage(index)}
|
||||
>
|
||||
<img
|
||||
@@ -381,13 +378,13 @@ const ProductDetail = () => {
|
||||
e.preventDefault();
|
||||
toggleFavorite(product.ProductID);
|
||||
}}
|
||||
className="top-0 p-2 rounded-bl-md bg-emerald-600 hover:bg-emerald-500 transition shadow-sm"
|
||||
className="top-0 p-2 rounded-bl-md bg-emerald-700 hover:bg-emerald-600 transition shadow-sm"
|
||||
>
|
||||
<Bookmark className="text-white w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="text-2xl font-bold text-green-600 mb-4">
|
||||
<div className="text-2xl font-bold text-emerald-700 mb-4">
|
||||
$
|
||||
{typeof product.Price === "number"
|
||||
? product.Price.toFixed(2)
|
||||
@@ -418,7 +415,7 @@ const ProductDetail = () => {
|
||||
<div className="relative">
|
||||
<button
|
||||
onClick={() => setShowContactOptions(!showContactOptions)}
|
||||
className="w-full bg-green-500 hover:bg-green-600 text-white font-medium py-3 px-4 mb-3"
|
||||
className="w-full bg-emerald-700 hover:bg-emerald-700 text-white font-medium py-3 px-4 mb-3"
|
||||
>
|
||||
Contact Seller
|
||||
</button>
|
||||
@@ -430,7 +427,7 @@ const ProductDetail = () => {
|
||||
href={`tel:${product.SellerPhone}`}
|
||||
className="flex items-center gap-2 p-3 hover:bg-gray-50 border-b border-gray-100"
|
||||
>
|
||||
<Phone className="h-5 w-5 text-green-500" />
|
||||
<Phone className="h-5 w-5 text-emerald-600" />
|
||||
<span>Call Seller</span>
|
||||
</a>
|
||||
)}
|
||||
@@ -440,7 +437,7 @@ const ProductDetail = () => {
|
||||
href={`mailto:${product.SellerEmail}`}
|
||||
className="flex items-center gap-2 p-3 hover:bg-gray-50"
|
||||
>
|
||||
<Mail className="h-5 w-5 text-green-500" />
|
||||
<Mail className="h-5 w-5 text-emerald-600" />
|
||||
<span>Email Seller</span>
|
||||
</a>
|
||||
)}
|
||||
@@ -477,7 +474,7 @@ const ProductDetail = () => {
|
||||
<div className="bg-white border border-gray-200 p-6">
|
||||
{loading.reviews ? (
|
||||
<div className="flex justify-center py-8">
|
||||
<div className="animate-spin h-8 w-8 border-t-2 border-green-500"></div>
|
||||
<div className="animate-spin h-8 w-8 border-t-2 border-emerald-600"></div>
|
||||
</div>
|
||||
) : error.reviews ? (
|
||||
<div className="text-red-500 mb-4">
|
||||
@@ -524,7 +521,7 @@ const ProductDetail = () => {
|
||||
<div className="mt-4">
|
||||
<button
|
||||
onClick={() => setShowReviewForm(true)}
|
||||
className="bg-green-500 hover:bg-green-600 text-white font-medium py-2 px-4"
|
||||
className="bg-emerald-600 hover:bg-emerald-700 text-white font-medium py-2 px-4"
|
||||
>
|
||||
Write a Review
|
||||
</button>
|
||||
@@ -582,7 +579,7 @@ const ProductDetail = () => {
|
||||
id="comment"
|
||||
value={reviewForm.comment}
|
||||
onChange={handleReviewInputChange}
|
||||
className="w-full p-3 border border-gray-300 focus:outline-none focus:border-green-500"
|
||||
className="w-full p-3 border border-gray-300 focus:outline-none focus:border-emerald-600"
|
||||
rows="4"
|
||||
required
|
||||
></textarea>
|
||||
@@ -598,7 +595,7 @@ const ProductDetail = () => {
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="px-4 py-2 bg-green-500 text-white hover:bg-green-600"
|
||||
className="px-4 py-2 bg-emerald-600 text-white hover:bg-emerald-700"
|
||||
disabled={loading.submitting}
|
||||
>
|
||||
{loading.submitting ? "Submitting..." : "Submit Review"}
|
||||
|
||||
@@ -1,95 +1,264 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import ProductForm from "../components/ProductForm";
|
||||
import { useLocation, Link } from "react-router-dom";
|
||||
import { X, ChevronLeft, Plus, Trash2 } from "lucide-react";
|
||||
|
||||
const Selling = () => {
|
||||
// State to store user's products
|
||||
const [products, setProducts] = useState([]);
|
||||
// State to control when editing form is shown
|
||||
const [showForm, setShowForm] = useState(false);
|
||||
// State to store the product being edited (or empty for new product)
|
||||
const storedUser = JSON.parse(sessionStorage.getItem("user"));
|
||||
const [categories, setCategories] = useState([]);
|
||||
const [categoryMapping, setCategoryMapping] = useState({});
|
||||
const [selectedCategory, setSelectedCategory] = useState("");
|
||||
const [originalProduct, setOriginalProduct] = useState(null);
|
||||
|
||||
const [editingProduct, setEditingProduct] = useState({
|
||||
name: "",
|
||||
price: "",
|
||||
description: "",
|
||||
categories: [],
|
||||
status: "Unsold",
|
||||
images: [],
|
||||
});
|
||||
|
||||
function reloadPage() {
|
||||
var doctTimestamp = new Date(performance.timing.domLoading).getTime();
|
||||
var now = Date.now();
|
||||
if (now > doctTimestamp) {
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch categories from API
|
||||
useEffect(() => {
|
||||
const fetchCategories = async () => {
|
||||
try {
|
||||
const response = await fetch("http://localhost:3030/api/category");
|
||||
if (!response.ok) throw new Error("Failed to fetch categories");
|
||||
|
||||
const responseJson = await response.json();
|
||||
const data = responseJson.data;
|
||||
|
||||
// Create an array of category names for the dropdown
|
||||
const categoryNames = [];
|
||||
const mapping = {};
|
||||
|
||||
// Process the data properly to avoid rendering objects
|
||||
Object.entries(data).forEach(([id, name]) => {
|
||||
// Make sure each category name is a string
|
||||
const categoryName = String(name);
|
||||
categoryNames.push(categoryName);
|
||||
mapping[categoryName] = parseInt(id);
|
||||
});
|
||||
|
||||
setCategories(categoryNames);
|
||||
setCategoryMapping(mapping);
|
||||
} catch (error) {
|
||||
console.error("Error fetching categories:", error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchCategories();
|
||||
}, []);
|
||||
|
||||
// Simulate fetching products from API/database on component mount
|
||||
useEffect(() => {
|
||||
// This would be replaced with a real API call
|
||||
const fetchProducts = async () => {
|
||||
// Mock data
|
||||
const mockProducts = [
|
||||
{
|
||||
id: "1",
|
||||
name: "Vintage Camera",
|
||||
price: "299.99",
|
||||
description: "A beautiful vintage film camera in excellent condition",
|
||||
categories: ["Electronics", "Art & Collectibles"],
|
||||
status: "Unsold",
|
||||
images: ["/public/Pictures/Dell1.jpg"],
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
name: "Leather Jacket",
|
||||
price: "149.50",
|
||||
description: "Genuine leather jacket, worn only a few times",
|
||||
categories: ["Clothing"],
|
||||
status: "Unsold",
|
||||
images: [],
|
||||
},
|
||||
];
|
||||
try {
|
||||
// Replace with your actual API endpoint
|
||||
const response = await fetch(
|
||||
"http://localhost:3030/api/product/myProduct",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
userID: storedUser.ID,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
setProducts(mockProducts);
|
||||
if (!response.ok) {
|
||||
throw new Error("Network response was not ok");
|
||||
}
|
||||
const datajson = await response.json();
|
||||
setProducts(datajson.data);
|
||||
} catch (error) {
|
||||
console.error("Error fetching products:", error);
|
||||
// You might want to set an error state here
|
||||
}
|
||||
};
|
||||
|
||||
fetchProducts();
|
||||
}, []);
|
||||
}, []); // Add userId to dependency array if it might change
|
||||
|
||||
// Handle creating or updating a product
|
||||
const handleSaveProduct = () => {
|
||||
if (editingProduct.id) {
|
||||
// Update existing product
|
||||
setProducts(
|
||||
products.map((p) => (p.id === editingProduct.id ? editingProduct : p)),
|
||||
);
|
||||
} else {
|
||||
// Create new product
|
||||
const newProduct = {
|
||||
...editingProduct,
|
||||
id: Date.now().toString(), // Generate a temporary ID
|
||||
};
|
||||
setProducts([...products, newProduct]);
|
||||
// When editing a product, save the original product properly
|
||||
const handleEditProduct = (product) => {
|
||||
// Save the original product completely
|
||||
setOriginalProduct(product);
|
||||
|
||||
// Convert category ID to category name if needed
|
||||
const categoryName = getCategoryNameById(product.CategoryID);
|
||||
|
||||
setEditingProduct({
|
||||
...product,
|
||||
categories: categoryName ? [categoryName] : [],
|
||||
images: product.images || [], // Ensure images array exists
|
||||
});
|
||||
|
||||
setShowForm(true);
|
||||
};
|
||||
|
||||
// Then update the handleSaveProduct function to properly merge values
|
||||
const handleSaveProduct = async () => {
|
||||
if (!(editingProduct.categories || []).length) {
|
||||
alert("Please select at least one category");
|
||||
return;
|
||||
}
|
||||
|
||||
// Reset form and hide it
|
||||
setShowForm(false);
|
||||
setEditingProduct({
|
||||
name: "",
|
||||
price: "",
|
||||
description: "",
|
||||
categories: [],
|
||||
status: "Unsold",
|
||||
images: [],
|
||||
});
|
||||
try {
|
||||
const imagePaths = [];
|
||||
|
||||
// Handle images properly
|
||||
if (editingProduct.images && editingProduct.images.length > 0) {
|
||||
// If there are new images uploaded (File objects)
|
||||
const newImages = editingProduct.images.filter(
|
||||
(img) => img instanceof File,
|
||||
);
|
||||
newImages.forEach((file) => {
|
||||
const simulatedPath = `/public/uploads/${file.name}`;
|
||||
imagePaths.push(simulatedPath);
|
||||
});
|
||||
|
||||
// Also include any existing image URLs that are strings, not File objects
|
||||
const existingImages = editingProduct.images.filter(
|
||||
(img) => typeof img === "string",
|
||||
);
|
||||
if (existingImages.length > 0) {
|
||||
imagePaths.push(...existingImages);
|
||||
}
|
||||
} else if (originalProduct?.image_url) {
|
||||
// If no new images but there was an original image URL
|
||||
imagePaths.push(originalProduct.image_url);
|
||||
}
|
||||
|
||||
const categoryName = (editingProduct.categories || [])[0];
|
||||
const categoryID =
|
||||
categoryMapping[categoryName] || originalProduct?.CategoryID || 1;
|
||||
|
||||
// Create payload with proper fallback to original values
|
||||
const payload = {
|
||||
name:
|
||||
editingProduct.Name ||
|
||||
editingProduct.name ||
|
||||
originalProduct?.Name ||
|
||||
"",
|
||||
price: parseFloat(
|
||||
editingProduct.Price ||
|
||||
editingProduct.price ||
|
||||
originalProduct?.Price ||
|
||||
0,
|
||||
),
|
||||
qty: 1,
|
||||
userID: storedUser.ID,
|
||||
description:
|
||||
editingProduct.Description ||
|
||||
editingProduct.description ||
|
||||
originalProduct?.Description ||
|
||||
"",
|
||||
category: categoryID,
|
||||
images:
|
||||
imagePaths.length > 0
|
||||
? imagePaths
|
||||
: originalProduct?.image_url
|
||||
? [originalProduct.image_url]
|
||||
: [],
|
||||
};
|
||||
|
||||
console.log("Sending payload:", payload);
|
||||
|
||||
const endpoint = editingProduct.ProductID
|
||||
? `http://localhost:3030/api/product/update/${editingProduct.ProductID}`
|
||||
: "http://localhost:3030/api/product/addProduct";
|
||||
|
||||
const method = editingProduct.ProductID ? "PUT" : "POST";
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.text();
|
||||
throw new Error(
|
||||
`${editingProduct.ProductID ? "Failed to update" : "Failed to add"} product: ${errorData}`,
|
||||
);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
console.log("Product saved:", data);
|
||||
|
||||
// Reset form and hide it
|
||||
setShowForm(false);
|
||||
setEditingProduct({
|
||||
name: "",
|
||||
price: "",
|
||||
description: "",
|
||||
categories: [],
|
||||
images: [],
|
||||
});
|
||||
|
||||
setOriginalProduct(null); // reset original as well
|
||||
|
||||
reloadPage();
|
||||
} catch (error) {
|
||||
console.error("Error saving product:", error);
|
||||
alert(`Error saving product: ${error.message}`);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle product deletion
|
||||
const handleDeleteProduct = (productId) => {
|
||||
if (window.confirm("Are you sure you want to delete this product?")) {
|
||||
setProducts(products.filter((p) => p.id !== productId));
|
||||
const handleDeleteProduct = async (productId) => {
|
||||
try {
|
||||
// Replace with your actual API endpoint
|
||||
const response = await fetch(
|
||||
"http://localhost:3030/api/product/delProduct",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
userID: storedUser.ID,
|
||||
productID: productId,
|
||||
}),
|
||||
},
|
||||
);
|
||||
reloadPage();
|
||||
console.log("deleteproodidt");
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Network response was not ok");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching products:", error);
|
||||
// You might want to set an error state here
|
||||
}
|
||||
};
|
||||
|
||||
// Handle editing a product
|
||||
const handleEditProduct = (product) => {
|
||||
setEditingProduct({
|
||||
...product,
|
||||
images: product.images || [], // Ensure images array exists
|
||||
});
|
||||
setShowForm(true);
|
||||
// Helper function to get category name from ID
|
||||
const getCategoryNameById = (categoryId) => {
|
||||
if (!categoryId || !categoryMapping) return null;
|
||||
|
||||
// Find the category name by ID
|
||||
for (const [name, id] of Object.entries(categoryMapping)) {
|
||||
if (id === categoryId) {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
// Handle adding a new product
|
||||
@@ -99,12 +268,54 @@ const Selling = () => {
|
||||
price: "",
|
||||
description: "",
|
||||
categories: [],
|
||||
status: "Unsold",
|
||||
images: [],
|
||||
});
|
||||
setShowForm(true);
|
||||
};
|
||||
|
||||
const addCategory = () => {
|
||||
if (
|
||||
selectedCategory &&
|
||||
!(editingProduct.categories || []).includes(selectedCategory)
|
||||
) {
|
||||
setEditingProduct((prev) => ({
|
||||
...prev,
|
||||
categories: [...(prev.categories || []), selectedCategory],
|
||||
}));
|
||||
setSelectedCategory("");
|
||||
}
|
||||
};
|
||||
|
||||
const removeCategory = (categoryToRemove) => {
|
||||
setEditingProduct((prev) => ({
|
||||
...prev,
|
||||
categories: (prev.categories || []).filter(
|
||||
(cat) => cat !== categoryToRemove,
|
||||
),
|
||||
}));
|
||||
};
|
||||
|
||||
const markAsSold = async () => {
|
||||
// This would call an API to move the product to the transaction table
|
||||
try {
|
||||
// API call would go here
|
||||
console.log(
|
||||
"Moving product to transaction table:",
|
||||
editingProduct.ProductID,
|
||||
);
|
||||
|
||||
// Toggle the sold status in the UI
|
||||
setEditingProduct((prev) => ({
|
||||
...prev,
|
||||
isSold: !prev.isSold,
|
||||
}));
|
||||
|
||||
// You would add your API call here to update the backend
|
||||
} catch (error) {
|
||||
console.error("Error marking product as sold:", error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-4 max-w-6xl">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
@@ -120,12 +331,279 @@ const Selling = () => {
|
||||
</div>
|
||||
|
||||
{showForm ? (
|
||||
<ProductForm
|
||||
editingProduct={editingProduct}
|
||||
setEditingProduct={setEditingProduct}
|
||||
onSave={handleSaveProduct}
|
||||
onCancel={() => setShowForm(false)}
|
||||
/>
|
||||
<div className="bg-white border border-gray-200 shadow-md p-6">
|
||||
{/* Back Button */}
|
||||
<button
|
||||
onClick={() => setShowForm(false)}
|
||||
className="mb-4 text-emerald-600 hover:text-emerald-800 flex items-center gap-1"
|
||||
>
|
||||
<ChevronLeft size={16} />
|
||||
<span>Back to Listings</span>
|
||||
</button>
|
||||
|
||||
<h3 className="text-xl font-bold text-gray-800 mb-6 border-b border-gray-200 pb-3">
|
||||
{editingProduct?.ProductID
|
||||
? "Edit Your Product"
|
||||
: "List a New Product"}
|
||||
</h3>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{/* Product Name */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Product Name
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={editingProduct.Name || editingProduct.name || ""}
|
||||
onChange={(e) =>
|
||||
setEditingProduct({
|
||||
...editingProduct,
|
||||
Name: e.target.value,
|
||||
name: e.target.value,
|
||||
})
|
||||
}
|
||||
className="w-full px-3 py-2 border border-gray-300 focus:border-emerald-500 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Price */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Price ($)
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
value={editingProduct.Price || editingProduct.price || ""}
|
||||
onChange={(e) =>
|
||||
setEditingProduct({
|
||||
...editingProduct,
|
||||
Price: e.target.value,
|
||||
price: e.target.value,
|
||||
})
|
||||
}
|
||||
className="w-full px-3 py-2 border border-gray-300 focus:border-emerald-500 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Sold Status */}
|
||||
<div className="md:col-span-2">
|
||||
<div className="flex items-center mt-2">
|
||||
{editingProduct.isSold && (
|
||||
<span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
|
||||
Sold
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Categories */}
|
||||
<div className="md:col-span-2">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Categories
|
||||
</label>
|
||||
<div className="flex gap-2">
|
||||
<select
|
||||
value={selectedCategory}
|
||||
onChange={(e) => setSelectedCategory(e.target.value)}
|
||||
className="flex-1 px-3 py-2 border border-gray-300 focus:border-emerald-500 focus:outline-none"
|
||||
>
|
||||
<option value="" disabled>
|
||||
Select a category
|
||||
</option>
|
||||
{categories
|
||||
.filter(
|
||||
(cat) => !(editingProduct.categories || []).includes(cat),
|
||||
)
|
||||
.map((category, index) => (
|
||||
<option key={index} value={category}>
|
||||
{category}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
onClick={addCategory}
|
||||
disabled={!selectedCategory}
|
||||
className="px-3 py-2 bg-emerald-600 text-white hover:bg-emerald-700 disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center gap-1"
|
||||
>
|
||||
<Plus size={16} />
|
||||
<span>Add</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Selected Categories */}
|
||||
{(editingProduct.categories || []).length > 0 ? (
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{(editingProduct.categories || []).map((category, index) => (
|
||||
<span
|
||||
key={index}
|
||||
className="inline-flex items-center px-2 py-1 bg-emerald-100 text-emerald-800"
|
||||
>
|
||||
{category}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeCategory(category)}
|
||||
className="ml-1 text-emerald-600 hover:text-emerald-800"
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
Please select at least one category
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div className="md:col-span-2">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Description
|
||||
</label>
|
||||
<textarea
|
||||
value={
|
||||
editingProduct.Description || editingProduct.description || ""
|
||||
}
|
||||
onChange={(e) =>
|
||||
setEditingProduct({
|
||||
...editingProduct,
|
||||
Description: e.target.value,
|
||||
description: e.target.value,
|
||||
})
|
||||
}
|
||||
rows="4"
|
||||
className="w-full px-3 py-2 border border-gray-300 focus:border-emerald-500 focus:outline-none"
|
||||
placeholder="Describe your product in detail..."
|
||||
></textarea>
|
||||
</div>
|
||||
|
||||
{/* Image Upload */}
|
||||
<div className="md:col-span-2">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Product Images <span className="text-gray-500">(Max 5)</span>
|
||||
</label>
|
||||
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
onChange={(e) => {
|
||||
const files = Array.from(e.target.files).slice(0, 5);
|
||||
setEditingProduct((prev) => ({
|
||||
...prev,
|
||||
images: [...(prev.images || []), ...files].slice(0, 5),
|
||||
}));
|
||||
}}
|
||||
className="hidden"
|
||||
id="image-upload"
|
||||
/>
|
||||
<label
|
||||
htmlFor="image-upload"
|
||||
className="block w-full p-3 border border-gray-300 bg-gray-50 text-center cursor-pointer hover:bg-gray-100"
|
||||
>
|
||||
<span className="text-emerald-600 font-medium">
|
||||
Click to upload images
|
||||
</span>
|
||||
</label>
|
||||
|
||||
{/* Image previews */}
|
||||
{(editingProduct.images || []).length > 0 && (
|
||||
<div className="mt-3">
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<p className="text-sm text-gray-600">
|
||||
{editingProduct.images.length}{" "}
|
||||
{editingProduct.images.length === 1 ? "image" : "images"}{" "}
|
||||
selected
|
||||
</p>
|
||||
<button
|
||||
onClick={() =>
|
||||
setEditingProduct((prev) => ({ ...prev, images: [] }))
|
||||
}
|
||||
className="text-sm text-red-600 hover:text-red-800 flex items-center gap-1"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
<span>Clear all</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{editingProduct.images.map((img, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
className="relative w-20 h-20 border border-gray-200 overflow-hidden"
|
||||
>
|
||||
<img
|
||||
src={URL.createObjectURL(img)}
|
||||
alt={`Product ${idx + 1}`}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
<button
|
||||
onClick={() => {
|
||||
const updated = [...editingProduct.images];
|
||||
updated.splice(idx, 1);
|
||||
setEditingProduct((prev) => ({
|
||||
...prev,
|
||||
images: updated,
|
||||
}));
|
||||
}}
|
||||
className="absolute top-0 right-0 bg-white bg-opacity-80 w-6 h-6 flex items-center justify-center text-gray-700 hover:text-red-600"
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Show current image if editing */}
|
||||
{editingProduct.image_url && (
|
||||
<div className="mt-3">
|
||||
<p className="text-sm text-gray-600 mb-2">Current image:</p>
|
||||
<div className="relative w-20 h-20 border border-gray-200 overflow-hidden">
|
||||
<img
|
||||
src={editingProduct.image_url}
|
||||
alt="Current product"
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="mt-6 flex justify-end gap-3 border-t border-gray-200 pt-4">
|
||||
<button
|
||||
onClick={() => setShowForm(false)}
|
||||
className="bg-gray-100 text-gray-700 px-4 py-2 hover:bg-gray-200 rounded-md"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
|
||||
{editingProduct.ProductID && (
|
||||
<button
|
||||
onClick={markAsSold}
|
||||
className={`px-4 py-2 rounded-md transition-colors ${
|
||||
editingProduct.isSold
|
||||
? "bg-green-600 text-white hover:bg-green-700"
|
||||
: "bg-red-600 text-white hover:bg-red-700"
|
||||
}`}
|
||||
>
|
||||
Mark as {editingProduct.isSold ? "Available" : "Sold"}
|
||||
</button>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={handleSaveProduct}
|
||||
className="bg-emerald-600 text-white px-6 py-2 hover:bg-emerald-700 rounded-md"
|
||||
>
|
||||
{editingProduct.ProductID ? "Update Product" : "Add Product"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{products.length === 0 ? (
|
||||
@@ -143,75 +621,72 @@ const Selling = () => {
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{products.map((product) => (
|
||||
<div
|
||||
key={product.id}
|
||||
className="border-2 border-gray-200 overflow-hidden hover:shadow-md transition-shadow"
|
||||
<Link
|
||||
key={product.ProductID}
|
||||
to={`/product/${product.ProductID}`}
|
||||
>
|
||||
<div className="h-48 bg-gray-200 flex items-center justify-center">
|
||||
{product.images && product.images.length > 0 ? (
|
||||
<img
|
||||
src={product.images[0] || ""}
|
||||
alt={product.name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="text-gray-400">No image</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="p-4">
|
||||
<div className="flex justify-between items-start">
|
||||
<h3 className="text-lg font-semibold text-gray-800">
|
||||
{product.name}
|
||||
</h3>
|
||||
<span
|
||||
className={`px-2 py-1 text-xs ${
|
||||
product.status === "Sold"
|
||||
? "bg-gray-200 text-gray-700"
|
||||
: "bg-emerald-100 text-emerald-800"
|
||||
}`}
|
||||
>
|
||||
{product.status}
|
||||
</span>
|
||||
<div className="border-2 border-gray-200 overflow-hidden hover:shadow-md transition-shadow">
|
||||
<div className="h-48 bg-gray-200 flex items-center justify-center">
|
||||
{product.image_url && product.image_url.length > 0 ? (
|
||||
<img
|
||||
src={product.image_url || ""}
|
||||
alt={product.Name}
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="text-gray-400">No image</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-emerald-600 font-bold mt-1">
|
||||
${product.price}
|
||||
</p>
|
||||
|
||||
{product.categories && product.categories.length > 0 && (
|
||||
<div className="mt-2 flex flex-wrap gap-1">
|
||||
{product.categories.map((category) => (
|
||||
<span
|
||||
key={category}
|
||||
className="text-xs bg-gray-100 text-gray-600 px-2 py-1 "
|
||||
>
|
||||
{category}
|
||||
</span>
|
||||
))}
|
||||
<div className="p-4">
|
||||
<div className="flex justify-between items-start">
|
||||
<h3 className="text-lg font-semibold text-gray-800">
|
||||
{product.Name}
|
||||
</h3>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-gray-500 text-sm mt-2 line-clamp-2">
|
||||
{product.description}
|
||||
</p>
|
||||
<p className="text-emerald-600 font-bold mt-1">
|
||||
${product.Price}
|
||||
</p>
|
||||
|
||||
<div className="mt-4 flex justify-end gap-2">
|
||||
<button
|
||||
onClick={() => handleDeleteProduct(product.id)}
|
||||
className="text-red-600 hover:text-red-800"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleEditProduct(product)}
|
||||
className="text-emerald-600 hover:text-emerald-800 font-medium"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
{product.CategoryID && (
|
||||
<div className="mt-2 flex flex-wrap gap-1">
|
||||
<span className="text-xs bg-gray-100 text-gray-600 px-2 py-1">
|
||||
{getCategoryNameById(product.CategoryID) ||
|
||||
product.CategoryID}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-gray-500 text-sm mt-2 line-clamp-2">
|
||||
{product.Description}
|
||||
</p>
|
||||
|
||||
<div className="mt-4 flex justify-end gap-2">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
handleDeleteProduct(product.ProductID);
|
||||
}}
|
||||
className="text-red-600 hover:text-red-800"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
handleEditProduct(product);
|
||||
}}
|
||||
className="text-emerald-600 hover:text-emerald-800 font-medium"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user