home and selligns page polished
This commit is contained in:
@@ -12,7 +12,7 @@ import Selling from "./pages/Selling";
|
|||||||
import Transactions from "./pages/Transactions";
|
import Transactions from "./pages/Transactions";
|
||||||
import Favorites from "./pages/Favorites";
|
import Favorites from "./pages/Favorites";
|
||||||
import ProductDetail from "./pages/ProductDetail";
|
import ProductDetail from "./pages/ProductDetail";
|
||||||
import SearchPage from "./pages/SearchPage"; // Make sure to import the SearchPage
|
import SearchPage from "./pages/SearchPage";
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
// Authentication state - initialize from localStorage if available
|
// Authentication state - initialize from localStorage if available
|
||||||
@@ -30,6 +30,11 @@ function App() {
|
|||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
|
||||||
|
// Product recommendation states
|
||||||
|
const [isGeneratingRecommendations, setIsGeneratingRecommendations] =
|
||||||
|
useState(false);
|
||||||
|
const [recommendations, setRecommendations] = useState([]);
|
||||||
|
|
||||||
// New verification states
|
// New verification states
|
||||||
const [verificationStep, setVerificationStep] = useState("initial"); // 'initial', 'code-sent', 'verifying'
|
const [verificationStep, setVerificationStep] = useState("initial"); // 'initial', 'code-sent', 'verifying'
|
||||||
const [tempUserData, setTempUserData] = useState(null);
|
const [tempUserData, setTempUserData] = useState(null);
|
||||||
@@ -51,8 +56,69 @@ function App() {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
sendSessionDataToServer();
|
if (isAuthenticated && user) {
|
||||||
}, []);
|
sendSessionDataToServer();
|
||||||
|
}
|
||||||
|
}, [isAuthenticated, user]);
|
||||||
|
|
||||||
|
// Generate product recommendations when user logs in
|
||||||
|
useEffect(() => {
|
||||||
|
if (isAuthenticated && user) {
|
||||||
|
generateProductRecommendations();
|
||||||
|
}
|
||||||
|
}, [isAuthenticated, user]);
|
||||||
|
|
||||||
|
// Generate product recommendations
|
||||||
|
const generateProductRecommendations = async () => {
|
||||||
|
try {
|
||||||
|
setIsGeneratingRecommendations(true);
|
||||||
|
|
||||||
|
// Add a short delay to simulate calculation time
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||||
|
|
||||||
|
console.log("Generating product recommendations for user:", user.ID);
|
||||||
|
|
||||||
|
// Make API call to get recommendations
|
||||||
|
const response = await fetch(
|
||||||
|
"http://localhost:3030/api/recommendations/generate",
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
userId: user.ID,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("Failed to generate recommendations");
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await response.json();
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
console.log(
|
||||||
|
"Recommendations generated successfully:",
|
||||||
|
result.recommendations,
|
||||||
|
);
|
||||||
|
setRecommendations(result.recommendations);
|
||||||
|
|
||||||
|
// Store recommendations in session storage for access across the app
|
||||||
|
sessionStorage.setItem(
|
||||||
|
"userRecommendations",
|
||||||
|
JSON.stringify(result.recommendations),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
console.error("Error generating recommendations:", result.message);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error generating product recommendations:", err);
|
||||||
|
} finally {
|
||||||
|
setIsGeneratingRecommendations(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Send verification code
|
// Send verification code
|
||||||
const sendVerificationCode = async (userData) => {
|
const sendVerificationCode = async (userData) => {
|
||||||
@@ -180,6 +246,7 @@ function App() {
|
|||||||
if (result.success) {
|
if (result.success) {
|
||||||
// Create user object from API response
|
// Create user object from API response
|
||||||
const newUser = {
|
const newUser = {
|
||||||
|
ID: result.userID || result.ID,
|
||||||
name: result.name || userData.name,
|
name: result.name || userData.name,
|
||||||
email: result.email || userData.email,
|
email: result.email || userData.email,
|
||||||
UCID: result.UCID || userData.ucid,
|
UCID: result.UCID || userData.ucid,
|
||||||
@@ -194,13 +261,17 @@ function App() {
|
|||||||
sessionStorage.setItem("user", JSON.stringify(newUser));
|
sessionStorage.setItem("user", JSON.stringify(newUser));
|
||||||
|
|
||||||
// After successful signup, send session data to server
|
// After successful signup, send session data to server
|
||||||
sendSessionDataToServer(); // Call it after signup
|
sendSessionDataToServer();
|
||||||
|
|
||||||
// Reset verification steps
|
// Reset verification steps
|
||||||
setVerificationStep("initial");
|
setVerificationStep("initial");
|
||||||
setTempUserData(null);
|
setTempUserData(null);
|
||||||
|
|
||||||
console.log("Signup completed successfully");
|
console.log("Signup completed successfully");
|
||||||
|
|
||||||
|
// Generate recommendations for the new user
|
||||||
|
generateProductRecommendations();
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
} else {
|
} else {
|
||||||
setError(result.message || "Failed to complete signup");
|
setError(result.message || "Failed to complete signup");
|
||||||
@@ -299,9 +370,11 @@ function App() {
|
|||||||
sessionStorage.setItem("isAuthenticated", "true");
|
sessionStorage.setItem("isAuthenticated", "true");
|
||||||
sessionStorage.setItem("user", JSON.stringify(userObj));
|
sessionStorage.setItem("user", JSON.stringify(userObj));
|
||||||
|
|
||||||
sessionStorage.getItem("user");
|
|
||||||
|
|
||||||
console.log("Login successful for:", userData.email);
|
console.log("Login successful for:", userData.email);
|
||||||
|
|
||||||
|
// Start generating recommendations with a slight delay
|
||||||
|
// This will happen in the useEffect, but we set a loading state to show to the user
|
||||||
|
setIsGeneratingRecommendations(true);
|
||||||
} else {
|
} else {
|
||||||
// Show error message for invalid credentials
|
// Show error message for invalid credentials
|
||||||
setError("Invalid email or password");
|
setError("Invalid email or password");
|
||||||
@@ -335,11 +408,12 @@ function App() {
|
|||||||
setUser(null);
|
setUser(null);
|
||||||
setVerificationStep("initial");
|
setVerificationStep("initial");
|
||||||
setTempUserData(null);
|
setTempUserData(null);
|
||||||
|
setRecommendations([]);
|
||||||
|
|
||||||
// Clear localStorage
|
// Clear localStorage
|
||||||
//
|
|
||||||
sessionStorage.removeItem("user");
|
sessionStorage.removeItem("user");
|
||||||
sessionStorage.removeItem("isAuthenticated");
|
sessionStorage.removeItem("isAuthenticated");
|
||||||
|
sessionStorage.removeItem("userRecommendations");
|
||||||
|
|
||||||
console.log("User logged out");
|
console.log("User logged out");
|
||||||
};
|
};
|
||||||
@@ -367,8 +441,6 @@ function App() {
|
|||||||
try {
|
try {
|
||||||
// Retrieve data from sessionStorage
|
// Retrieve data from sessionStorage
|
||||||
const user = JSON.parse(sessionStorage.getItem("user"));
|
const user = JSON.parse(sessionStorage.getItem("user"));
|
||||||
// const isAuthenticated =
|
|
||||||
// sessionStorage.getItem("isAuthenticated") === "true";
|
|
||||||
|
|
||||||
if (!user || !isAuthenticated) {
|
if (!user || !isAuthenticated) {
|
||||||
console.log("User is not authenticated");
|
console.log("User is not authenticated");
|
||||||
@@ -403,6 +475,13 @@ function App() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Loading overlay component
|
||||||
|
const LoadingOverlay = () => (
|
||||||
|
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
|
||||||
|
<div className="animate-spin rounded-full h-12 w-12 border-4 border-green-500 border-t-transparent"></div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
// Login component
|
// Login component
|
||||||
const LoginComponent = () => (
|
const LoginComponent = () => (
|
||||||
<div className="flex h-screen bg-white">
|
<div className="flex h-screen bg-white">
|
||||||
@@ -671,6 +750,9 @@ function App() {
|
|||||||
return (
|
return (
|
||||||
<Router>
|
<Router>
|
||||||
<div className="min-h-screen bg-gray-50">
|
<div className="min-h-screen bg-gray-50">
|
||||||
|
{/* Show loading overlay when generating recommendations */}
|
||||||
|
{isGeneratingRecommendations && <LoadingOverlay />}
|
||||||
|
|
||||||
{/* Only show navbar when authenticated */}
|
{/* Only show navbar when authenticated */}
|
||||||
{isAuthenticated && (
|
{isAuthenticated && (
|
||||||
<Navbar onLogout={handleLogout} userName={user?.name} />
|
<Navbar onLogout={handleLogout} userName={user?.name} />
|
||||||
@@ -687,7 +769,7 @@ function App() {
|
|||||||
element={
|
element={
|
||||||
<ProtectedRoute>
|
<ProtectedRoute>
|
||||||
<div className="container mx-auto px-4 py-6">
|
<div className="container mx-auto px-4 py-6">
|
||||||
<Home />
|
<Home recommendations={recommendations} />
|
||||||
</div>
|
</div>
|
||||||
</ProtectedRoute>
|
</ProtectedRoute>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,6 @@
|
|||||||
import { useState, useEffect } from "react";
|
|
||||||
import { Link, useNavigate } from "react-router-dom";
|
import { Link, useNavigate } from "react-router-dom";
|
||||||
import {
|
import { useState, useEffect, useRef } from "react";
|
||||||
Tag,
|
import { Tag, ChevronLeft, ChevronRight, Bookmark, Loader } from "lucide-react";
|
||||||
ChevronLeft,
|
|
||||||
ChevronRight,
|
|
||||||
Bookmark,
|
|
||||||
BookmarkCheck,
|
|
||||||
} from "lucide-react";
|
|
||||||
|
|
||||||
import FloatingAlert from "../components/FloatingAlert"; // adjust path if needed
|
import FloatingAlert from "../components/FloatingAlert"; // adjust path if needed
|
||||||
|
|
||||||
@@ -14,38 +8,50 @@ const Home = () => {
|
|||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [listings, setListings] = useState([]);
|
const [listings, setListings] = useState([]);
|
||||||
const [recommended, setRecommended] = useState([]);
|
const [recommended, setRecommended] = useState([]);
|
||||||
const [history, sethistory] = useState([]);
|
const [history, setHistory] = useState([]);
|
||||||
const [error, setError] = useState(null);
|
const [error, setError] = useState(null);
|
||||||
const [showAlert, setShowAlert] = useState(false);
|
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.
|
//After user data storing the session.
|
||||||
const storedUser = JSON.parse(sessionStorage.getItem("user"));
|
const storedUser = JSON.parse(sessionStorage.getItem("user"));
|
||||||
|
|
||||||
const toggleFavorite = async (id) => {
|
const toggleFavorite = async (id) => {
|
||||||
const response = await fetch(
|
try {
|
||||||
"http://localhost:3030/api/product/addFavorite",
|
const response = await fetch(
|
||||||
{
|
"http://localhost:3030/api/product/addFavorite",
|
||||||
method: "POST",
|
{
|
||||||
headers: {
|
method: "POST",
|
||||||
"Content-Type": "application/json",
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
userID: storedUser.ID,
|
||||||
|
productID: id,
|
||||||
|
}),
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
);
|
||||||
userID: storedUser.ID,
|
const data = await response.json();
|
||||||
productID: id,
|
if (data.success) {
|
||||||
}),
|
setShowAlert(true);
|
||||||
},
|
// Close alert after 3 seconds
|
||||||
);
|
setTimeout(() => setShowAlert(false), 3000);
|
||||||
const data = await response.json();
|
}
|
||||||
if (data.success) {
|
console.log(`Add Product -> Favorites: ${id}`);
|
||||||
setShowAlert(true);
|
} catch (error) {
|
||||||
|
console.error("Error adding favorite:", error);
|
||||||
}
|
}
|
||||||
console.log(`Add Product -> History: ${id}`);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const addHistory = async (id) => {
|
const addHistory = async (id) => {
|
||||||
const response = await fetch(
|
try {
|
||||||
"http://localhost:3030/api/history/addHistory",
|
await fetch("http://localhost:3030/api/history/addHistory", {
|
||||||
{
|
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
@@ -54,22 +60,23 @@ const Home = () => {
|
|||||||
userID: storedUser.ID,
|
userID: storedUser.ID,
|
||||||
productID: id,
|
productID: id,
|
||||||
}),
|
}),
|
||||||
},
|
});
|
||||||
);
|
} catch (error) {
|
||||||
|
console.error("Error adding to history:", error);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
function reloadPage() {
|
// Fetch recommended products
|
||||||
var doctTimestamp = new Date(performance.timing.domLoading).getTime();
|
|
||||||
var now = Date.now();
|
|
||||||
var tenSec = 10 * 1000;
|
|
||||||
if (now > doctTimestamp + tenSec) {
|
|
||||||
location.reload();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
useEffect(() => {
|
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 {
|
try {
|
||||||
|
recommendationsFetched.current = true; // Mark as fetched before the API call
|
||||||
|
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
"http://localhost:3030/api/engine/recommended",
|
"http://localhost:3030/api/engine/recommended",
|
||||||
{
|
{
|
||||||
@@ -82,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();
|
const data = await response.json();
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
setRecommended(
|
setRecommended(
|
||||||
data.data.map((product) => ({
|
data.data.map((product) => ({
|
||||||
id: product.ProductID,
|
id: product.ProductID,
|
||||||
title: product.ProductName, // Use the alias from SQL
|
title: product.ProductName,
|
||||||
price: product.Price,
|
price: product.Price,
|
||||||
category: product.Category, // Ensure this gets the category name
|
category: product.Category,
|
||||||
image: product.ProductImage, // Use the alias for image URL
|
image: product.ProductImage,
|
||||||
seller: product.SellerName, // Fetch seller name properly
|
seller: product.SellerName,
|
||||||
datePosted: product.DateUploaded, // Use the actual date
|
datePosted: product.DateUploaded,
|
||||||
isFavorite: false, // Default state
|
isFavorite: false,
|
||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
reloadPage();
|
|
||||||
} else {
|
} else {
|
||||||
throw new Error(data.message || "Error fetching products");
|
throw new Error(data.message || "Error fetching recommendations");
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error fetching products:", error);
|
console.error("Error fetching recommendations:", error);
|
||||||
setError(error.message);
|
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(() => {
|
useEffect(() => {
|
||||||
const fetchProducts = async () => {
|
const fetchProducts = async () => {
|
||||||
|
setIsLoading((prev) => ({ ...prev, listings: true }));
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
"http://localhost:3030/api/product/getProduct",
|
"http://localhost:3030/api/product/getProduct",
|
||||||
@@ -119,18 +132,17 @@ const Home = () => {
|
|||||||
if (!response.ok) throw new Error("Failed to fetch products");
|
if (!response.ok) throw new Error("Failed to fetch products");
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
setListings(
|
setListings(
|
||||||
data.data.map((product) => ({
|
data.data.map((product) => ({
|
||||||
id: product.ProductID,
|
id: product.ProductID,
|
||||||
title: product.ProductName, // Use the alias from SQL
|
title: product.ProductName,
|
||||||
price: product.Price,
|
price: product.Price,
|
||||||
category: product.Category, // Ensure this gets the category name
|
category: product.Category,
|
||||||
image: product.ProductImage, // Use the alias for image URL
|
image: product.ProductImage,
|
||||||
seller: product.SellerName, // Fetch seller name properly
|
seller: product.SellerName,
|
||||||
datePosted: product.DateUploaded, // Use the actual date
|
datePosted: product.DateUploaded,
|
||||||
isFavorite: false, // Default state
|
isFavorite: false,
|
||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
@@ -139,15 +151,24 @@ const Home = () => {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error fetching products:", error);
|
console.error("Error fetching products:", error);
|
||||||
setError(error.message);
|
setError(error.message);
|
||||||
|
} finally {
|
||||||
|
setIsLoading((prev) => ({ ...prev, listings: false }));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
fetchProducts();
|
fetchProducts();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Fetch user history
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchrecomProducts = async () => {
|
const fetchUserHistory = async () => {
|
||||||
// Get the user's data from localStorage
|
// Skip if already fetched or no user data
|
||||||
|
if (historyFetched.current || !storedUser || !storedUser.ID) return;
|
||||||
|
|
||||||
|
setIsLoading((prev) => ({ ...prev, history: true }));
|
||||||
try {
|
try {
|
||||||
|
historyFetched.current = true; // Mark as fetched before the API call
|
||||||
|
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
"http://localhost:3030/api/history/getHistory",
|
"http://localhost:3030/api/history/getHistory",
|
||||||
{
|
{
|
||||||
@@ -160,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();
|
const data = await response.json();
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
sethistory(
|
setHistory(
|
||||||
data.data.map((product) => ({
|
data.data.map((product) => ({
|
||||||
id: product.ProductID,
|
id: product.ProductID,
|
||||||
title: product.ProductName, // Use the alias from SQL
|
title: product.ProductName,
|
||||||
price: product.Price,
|
price: product.Price,
|
||||||
category: product.Category, // Ensure this gets the category name
|
category: product.Category,
|
||||||
image: product.ProductImage, // Use the alias for image URL
|
image: product.ProductImage,
|
||||||
seller: product.SellerName, // Fetch seller name properly
|
seller: product.SellerName,
|
||||||
datePosted: product.DateUploaded, // Use the actual date
|
datePosted: product.DateUploaded,
|
||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
throw new Error(data.message || "Error fetching products");
|
throw new Error(data.message || "Error fetching history");
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error fetching products:", error);
|
console.error("Error fetching history:", error);
|
||||||
setError(error.message);
|
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 = () => {
|
const handleSelling = () => {
|
||||||
navigate("/selling");
|
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 (
|
return (
|
||||||
<div className="flex flex-col min-h-screen">
|
<div className="flex flex-col min-h-screen">
|
||||||
<div className="flex-grow">
|
<div className="flex-grow">
|
||||||
{/* Hero Section with School Background */}
|
{/* Hero Section with School Background */}
|
||||||
<div className="relative py-12 px-4 mb-8 shadow-sm">
|
<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">
|
<div className="absolute inset-0 z-0 overflow-hidden bg-black bg-opacity-100">
|
||||||
<img
|
<img
|
||||||
src="../public/Ucalgary.png"
|
src="../public/Ucalgary.png"
|
||||||
alt="University of Calgary"
|
alt="University of Calgary"
|
||||||
className="w-full h-full object-cover object-bottom opacity-45"
|
className="w-full h-full object-cover object-bottom opacity-45"
|
||||||
/>
|
/>
|
||||||
{/* Dark overlay for better text readability */}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Content */}
|
|
||||||
<div className="max-w-2xl mx-auto text-center relative z-1">
|
<div className="max-w-2xl mx-auto text-center relative z-1">
|
||||||
<h1 className="text-3xl font-bold text-white mb-4">
|
<h1 className="text-3xl font-bold text-white mb-4">
|
||||||
Buy and Sell on Campus
|
Buy and Sell on Campus
|
||||||
@@ -223,290 +360,53 @@ const Home = () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Recent Listings */}
|
{/* Floating Alert */}
|
||||||
{showAlert && (
|
{showAlert && (
|
||||||
<FloatingAlert
|
<FloatingAlert
|
||||||
message="Product added to favorites!"
|
message="Product added to favorites!"
|
||||||
onClose={() => setShowAlert(false)}
|
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">
|
<h2 className="text-xl font-semibold text-gray-800 mb-4">
|
||||||
Recommendation
|
Recommended For You
|
||||||
</h2>
|
</h2>
|
||||||
|
</ScrollableProductList>
|
||||||
|
|
||||||
<div className="relative">
|
{/* Recent Listings Section */}
|
||||||
{/* Left Button - Overlaid on products */}
|
<ScrollableProductList
|
||||||
<button
|
containerId="listingsContainer"
|
||||||
onClick={() =>
|
products={listings}
|
||||||
document
|
isLoading={isLoading.listings}
|
||||||
.getElementById("RecomContainer")
|
addToHistory={true}
|
||||||
.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">
|
|
||||||
<h2 className="text-xl font-semibold text-gray-800 mb-4">
|
<h2 className="text-xl font-semibold text-gray-800 mb-4">
|
||||||
Recent Listings
|
Recent Listings
|
||||||
</h2>
|
</h2>
|
||||||
|
</ScrollableProductList>
|
||||||
<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>
|
|
||||||
|
|
||||||
{/* History Section */}
|
{/* History Section */}
|
||||||
{showAlert && (
|
{(history.length > 0 || isLoading.history) && (
|
||||||
<FloatingAlert
|
<ScrollableProductList
|
||||||
message="Product added to favorites!"
|
containerId="HistoryContainer"
|
||||||
onClose={() => setShowAlert(false)}
|
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>
|
</div>
|
||||||
|
|
||||||
{/* Footer - Added here */}
|
{/* Footer */}
|
||||||
<footer className="bg-gray-800 text-white py-6 mt-12">
|
<footer className="bg-gray-800 text-white py-6 mt-12">
|
||||||
<div className="container mx-auto px-4">
|
<div className="container mx-auto px-4">
|
||||||
<div className="flex flex-col md:flex-row justify-between items-center">
|
<div className="flex flex-col md:flex-row justify-between items-center">
|
||||||
|
|||||||
@@ -22,8 +22,7 @@ const Selling = () => {
|
|||||||
function reloadPage() {
|
function reloadPage() {
|
||||||
var doctTimestamp = new Date(performance.timing.domLoading).getTime();
|
var doctTimestamp = new Date(performance.timing.domLoading).getTime();
|
||||||
var now = Date.now();
|
var now = Date.now();
|
||||||
var tenSec = 10 * 1000;
|
if (now > doctTimestamp) {
|
||||||
if (now > doctTimestamp + tenSec) {
|
|
||||||
location.reload();
|
location.reload();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -81,7 +80,6 @@ const Selling = () => {
|
|||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error("Network response was not ok");
|
throw new Error("Network response was not ok");
|
||||||
}
|
}
|
||||||
|
|
||||||
const datajson = await response.json();
|
const datajson = await response.json();
|
||||||
setProducts(datajson.data);
|
setProducts(datajson.data);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -94,109 +92,132 @@ const Selling = () => {
|
|||||||
}, []); // Add userId to dependency array if it might change
|
}, []); // Add userId to dependency array if it might change
|
||||||
|
|
||||||
// When editing a product, save the original product properly
|
// When editing a product, save the original product properly
|
||||||
const handleEditProduct = (product) => {
|
const handleEditProduct = (product) => {
|
||||||
// Save the original product completely
|
// Save the original product completely
|
||||||
setOriginalProduct(product);
|
setOriginalProduct(product);
|
||||||
|
|
||||||
// Convert category ID to category name if needed
|
// Convert category ID to category name if needed
|
||||||
const categoryName = getCategoryNameById(product.CategoryID);
|
const categoryName = getCategoryNameById(product.CategoryID);
|
||||||
|
|
||||||
setEditingProduct({
|
setEditingProduct({
|
||||||
...product,
|
...product,
|
||||||
categories: categoryName ? [categoryName] : [],
|
categories: categoryName ? [categoryName] : [],
|
||||||
images: product.images || [], // Ensure images array exists
|
images: product.images || [], // Ensure images array exists
|
||||||
});
|
});
|
||||||
|
|
||||||
setShowForm(true);
|
setShowForm(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Then update the handleSaveProduct function to properly merge values
|
// Then update the handleSaveProduct function to properly merge values
|
||||||
const handleSaveProduct = async () => {
|
const handleSaveProduct = async () => {
|
||||||
if (!(editingProduct.categories || []).length) {
|
if (!(editingProduct.categories || []).length) {
|
||||||
alert("Please select at least one category");
|
alert("Please select at least one category");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const imagePaths = [];
|
const imagePaths = [];
|
||||||
|
|
||||||
// Handle images properly
|
// Handle images properly
|
||||||
if (editingProduct.images && editingProduct.images.length > 0) {
|
if (editingProduct.images && editingProduct.images.length > 0) {
|
||||||
// If there are new images uploaded (File objects)
|
// If there are new images uploaded (File objects)
|
||||||
const newImages = editingProduct.images.filter(img => img instanceof File);
|
const newImages = editingProduct.images.filter(
|
||||||
newImages.forEach((file) => {
|
(img) => img instanceof File,
|
||||||
const simulatedPath = `/public/uploads/${file.name}`;
|
);
|
||||||
imagePaths.push(simulatedPath);
|
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),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Also include any existing image URLs that are strings, not File objects
|
if (!response.ok) {
|
||||||
const existingImages = editingProduct.images.filter(img => typeof img === 'string');
|
const errorData = await response.text();
|
||||||
if (existingImages.length > 0) {
|
throw new Error(
|
||||||
imagePaths.push(...existingImages);
|
`${editingProduct.ProductID ? "Failed to update" : "Failed to add"} product: ${errorData}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} else if (originalProduct?.image_url) {
|
|
||||||
// If no new images but there was an original image URL
|
const data = await response.json();
|
||||||
imagePaths.push(originalProduct.image_url);
|
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}`);
|
||||||
}
|
}
|
||||||
|
};
|
||||||
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
|
// Handle product deletion
|
||||||
const handleDeleteProduct = async (productId) => {
|
const handleDeleteProduct = async (productId) => {
|
||||||
@@ -215,8 +236,8 @@ const handleSaveProduct = async () => {
|
|||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
console.log("deleteproodidt");
|
|
||||||
reloadPage();
|
reloadPage();
|
||||||
|
console.log("deleteproodidt");
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error("Network response was not ok");
|
throw new Error("Network response was not ok");
|
||||||
|
|||||||
Binary file not shown.
@@ -3,7 +3,7 @@ import mysql.connector
|
|||||||
from sklearn.metrics.pairwise import cosine_similarity
|
from sklearn.metrics.pairwise import cosine_similarity
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import logging
|
import logging
|
||||||
from unittest import result
|
import random
|
||||||
|
|
||||||
def database():
|
def database():
|
||||||
db_connection = mysql.connector.connect(
|
db_connection = mysql.connector.connect(
|
||||||
@@ -14,145 +14,257 @@ def database():
|
|||||||
)
|
)
|
||||||
return db_connection
|
return db_connection
|
||||||
|
|
||||||
def get_popular_products():
|
def delete_user_recommendations(user_id):
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def delete_user_recommendation(userID, Array):
|
|
||||||
db_con = database()
|
db_con = database()
|
||||||
cursor = db_con.cursor()
|
cursor = db_con.cursor()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
for item in Array:
|
cursor.execute("DELETE FROM Recommendation WHERE UserID = %s", (user_id,))
|
||||||
#Product ID starts form index 1
|
|
||||||
item_value = item + 1
|
|
||||||
print(item_value)
|
|
||||||
# Use parameterized queries to prevent SQL injection
|
|
||||||
cursor.execute(f"INTO Recommendation (UserID, RecommendedProductID) VALUES ({userID}, {item_value});")
|
|
||||||
|
|
||||||
db_con.commit()
|
db_con.commit()
|
||||||
|
print(f"Deleted existing recommendations for user {user_id}")
|
||||||
|
logging.info(f"Deleted existing recommendations for user {user_id}")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Error deleting recommendations for user {user_id}: {str(e)}")
|
||||||
|
db_con.rollback()
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
cursor.close()
|
||||||
|
db_con.close()
|
||||||
|
|
||||||
#results = cursor.fetchall()
|
def get_random_products(count=10, exclude_list=None):
|
||||||
#print(results)
|
"""Get random products from the database, excluding any in the exclude_list"""
|
||||||
except:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def get_all_products():
|
|
||||||
|
|
||||||
db_con = database()
|
db_con = database()
|
||||||
cursor = db_con.cursor()
|
cursor = db_con.cursor()
|
||||||
|
|
||||||
cursor.execute("SELECT CategoryID FROM Category")
|
try:
|
||||||
categories = cursor.fetchall()
|
if exclude_list and len(exclude_list) > 0:
|
||||||
|
# Convert exclude_list to string for SQL IN clause
|
||||||
|
exclude_str = ', '.join(map(str, exclude_list))
|
||||||
|
cursor.execute(f"SELECT ProductID FROM Product WHERE ProductID NOT IN ({exclude_str}) ORDER BY RAND() LIMIT {count}")
|
||||||
|
else:
|
||||||
|
cursor.execute(f"SELECT ProductID FROM Product ORDER BY RAND() LIMIT {count}")
|
||||||
|
|
||||||
select_clause = "SELECT p.ProductID"
|
random_products = [row[0] for row in cursor.fetchall()]
|
||||||
for category in categories:
|
return random_products
|
||||||
category_id = category[0]
|
|
||||||
select_clause += f", MAX(CASE WHEN pc.CategoryID = {category_id} THEN 1 ELSE 0 END) AS `Cat_{category_id}`"
|
|
||||||
|
|
||||||
final_query = f"""
|
except Exception as e:
|
||||||
{select_clause}
|
logging.error(f"Error getting random products: {str(e)}")
|
||||||
FROM Product p
|
return []
|
||||||
LEFT JOIN Product_Category pc ON p.ProductID = pc.ProductID
|
finally:
|
||||||
LEFT JOIN Category c ON pc.CategoryID = c.CategoryID
|
cursor.close()
|
||||||
GROUP BY p.ProductID;
|
db_con.close()
|
||||||
"""
|
|
||||||
|
|
||||||
cursor.execute(final_query)
|
def get_popular_products(count=10):
|
||||||
results = cursor.fetchall()
|
"""Get popular products based on history table frequency"""
|
||||||
|
db_con = database()
|
||||||
|
cursor = db_con.cursor()
|
||||||
|
|
||||||
final = []
|
try:
|
||||||
for row in results:
|
# Get products that appear most frequently in history
|
||||||
text_list = list(row)
|
cursor.execute("""
|
||||||
text_list.pop(0)
|
SELECT ProductID, COUNT(*) as count
|
||||||
final.append(text_list)
|
FROM History
|
||||||
|
GROUP BY ProductID
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT %s
|
||||||
|
""", (count,))
|
||||||
|
|
||||||
cursor.close()
|
popular_products = [row[0] for row in cursor.fetchall()]
|
||||||
db_con.close()
|
|
||||||
return final
|
# If not enough popular products, supplement with random ones
|
||||||
|
if len(popular_products) < count:
|
||||||
|
random_products = get_random_products(count - len(popular_products), popular_products)
|
||||||
|
popular_products.extend(random_products)
|
||||||
|
|
||||||
|
return popular_products
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Error getting popular products: {str(e)}")
|
||||||
|
return get_random_products(count) # Fallback to random products
|
||||||
|
finally:
|
||||||
|
cursor.close()
|
||||||
|
db_con.close()
|
||||||
|
|
||||||
|
def has_user_history_or_recommendations(user_id):
|
||||||
|
"""Check if user exists in History or Recommendation table"""
|
||||||
|
db_con = database()
|
||||||
|
cursor = db_con.cursor()
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Check if user has history
|
||||||
|
cursor.execute("SELECT COUNT(*) FROM History WHERE UserID = %s", (user_id,))
|
||||||
|
history_count = cursor.fetchone()[0]
|
||||||
|
|
||||||
|
# Check if user has recommendations
|
||||||
|
cursor.execute("SELECT COUNT(*) FROM Recommendation WHERE UserID = %s", (user_id,))
|
||||||
|
recommendation_count = cursor.fetchone()[0]
|
||||||
|
|
||||||
|
return history_count > 0 or recommendation_count > 0
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Error checking user history/recommendations: {str(e)}")
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
cursor.close()
|
||||||
|
db_con.close()
|
||||||
|
|
||||||
|
def get_all_products():
|
||||||
|
db_con = database()
|
||||||
|
cursor = db_con.cursor()
|
||||||
|
|
||||||
|
try:
|
||||||
|
cursor.execute("SELECT CategoryID FROM Category")
|
||||||
|
categories = cursor.fetchall()
|
||||||
|
|
||||||
|
select_clause = "SELECT p.ProductID"
|
||||||
|
for category in categories:
|
||||||
|
category_id = category[0]
|
||||||
|
select_clause += f", MAX(CASE WHEN pc.CategoryID = {category_id} THEN 1 ELSE 0 END) AS `Cat_{category_id}`"
|
||||||
|
|
||||||
|
final_query = f"""
|
||||||
|
{select_clause}
|
||||||
|
FROM Product p
|
||||||
|
LEFT JOIN Product_Category pc ON p.ProductID = pc.ProductID
|
||||||
|
LEFT JOIN Category c ON pc.CategoryID = c.CategoryID
|
||||||
|
GROUP BY p.ProductID;
|
||||||
|
"""
|
||||||
|
|
||||||
|
cursor.execute(final_query)
|
||||||
|
results = cursor.fetchall()
|
||||||
|
|
||||||
|
final = []
|
||||||
|
product_ids = []
|
||||||
|
for row in results:
|
||||||
|
text_list = list(row)
|
||||||
|
product_id = text_list.pop(0) # Save the product ID before removing it
|
||||||
|
final.append(text_list)
|
||||||
|
product_ids.append(product_id)
|
||||||
|
|
||||||
|
cursor.close()
|
||||||
|
db_con.close()
|
||||||
|
return final, product_ids # Return both feature vectors and product IDs
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Error getting all products: {str(e)}")
|
||||||
|
cursor.close()
|
||||||
|
db_con.close()
|
||||||
|
return [], []
|
||||||
|
|
||||||
def get_user_history(user_id):
|
def get_user_history(user_id):
|
||||||
db_con = database()
|
db_con = database()
|
||||||
cursor = db_con.cursor()
|
cursor = db_con.cursor()
|
||||||
|
|
||||||
cursor.execute("SELECT CategoryID FROM Category")
|
|
||||||
categories = cursor.fetchall()
|
|
||||||
|
|
||||||
select_clause = "SELECT p.ProductID"
|
|
||||||
for category in categories:
|
|
||||||
category_id = category[0] # get the uid of the catefory and then append that to the new column
|
|
||||||
select_clause += f", MAX(CASE WHEN pc.CategoryID = {category_id} THEN 1 ELSE 0 END) AS `Cat_{category_id}`"
|
|
||||||
|
|
||||||
final_query = f"""
|
|
||||||
{select_clause}
|
|
||||||
FROM Product p
|
|
||||||
LEFT JOIN Product_Category pc ON p.ProductID = pc.ProductID
|
|
||||||
LEFT JOIN Category c ON pc.CategoryID = c.CategoryID
|
|
||||||
where p.ProductID in (select ProductID from History where UserID = {user_id})
|
|
||||||
GROUP BY p.ProductID;
|
|
||||||
"""
|
|
||||||
|
|
||||||
cursor.execute(final_query)
|
|
||||||
results = cursor.fetchall()
|
|
||||||
final = []
|
|
||||||
for row in results:
|
|
||||||
text_list = list(row)
|
|
||||||
text_list.pop(0)
|
|
||||||
final.append(text_list)
|
|
||||||
|
|
||||||
cursor.close()
|
|
||||||
db_con.close()
|
|
||||||
return final
|
|
||||||
|
|
||||||
def get_recommendations(user_id, top_n=10):
|
|
||||||
try:
|
try:
|
||||||
|
cursor.execute("SELECT CategoryID FROM Category")
|
||||||
|
categories = cursor.fetchall()
|
||||||
|
|
||||||
|
select_clause = "SELECT p.ProductID"
|
||||||
|
for category in categories:
|
||||||
|
category_id = category[0] # get the uid of the category and then append that to the new column
|
||||||
|
select_clause += f", MAX(CASE WHEN pc.CategoryID = {category_id} THEN 1 ELSE 0 END) AS `Cat_{category_id}`"
|
||||||
|
|
||||||
|
final_query = f"""
|
||||||
|
{select_clause}
|
||||||
|
FROM Product p
|
||||||
|
LEFT JOIN Product_Category pc ON p.ProductID = pc.ProductID
|
||||||
|
LEFT JOIN Category c ON pc.CategoryID = c.CategoryID
|
||||||
|
where p.ProductID in (select ProductID from History where UserID = {user_id})
|
||||||
|
GROUP BY p.ProductID;
|
||||||
|
"""
|
||||||
|
|
||||||
|
cursor.execute(final_query)
|
||||||
|
results = cursor.fetchall()
|
||||||
|
final = []
|
||||||
|
for row in results:
|
||||||
|
text_list = list(row)
|
||||||
|
text_list.pop(0)
|
||||||
|
final.append(text_list)
|
||||||
|
|
||||||
|
cursor.close()
|
||||||
|
db_con.close()
|
||||||
|
return final
|
||||||
|
except Exception as e:
|
||||||
|
logging.error(f"Error getting user history: {str(e)}")
|
||||||
|
cursor.close()
|
||||||
|
db_con.close()
|
||||||
|
return []
|
||||||
|
|
||||||
|
def get_recommendations(user_id, top_n=5):
|
||||||
|
try:
|
||||||
|
# Always delete existing recommendations first
|
||||||
|
delete_user_recommendations(user_id)
|
||||||
|
|
||||||
|
# Check if user has history or recommendations
|
||||||
|
if not has_user_history_or_recommendations(user_id):
|
||||||
|
# Cold start: return random products
|
||||||
|
random_recs = get_random_products(top_n)
|
||||||
|
# Store these random recommendations
|
||||||
|
history_upload(user_id, random_recs)
|
||||||
|
|
||||||
|
# Add 5 more unique random products
|
||||||
|
additional_random = get_random_products(5, random_recs)
|
||||||
|
history_upload(user_id, additional_random)
|
||||||
|
|
||||||
|
return random_recs + additional_random
|
||||||
|
|
||||||
# Get all products and user history with their category vectors
|
# Get all products and user history with their category vectors
|
||||||
all_products = get_all_products()
|
all_product_features, all_product_ids = get_all_products()
|
||||||
user_history = get_user_history(user_id)
|
user_history = get_user_history(user_id)
|
||||||
# if not user_history:
|
|
||||||
# #Cold start: return popular products
|
if not user_history:
|
||||||
# return get_popular_products(top_n)
|
# User exists but has no history yet
|
||||||
|
popular_recs = get_popular_products(top_n)
|
||||||
|
history_upload(user_id, popular_recs)
|
||||||
|
|
||||||
|
# Add 5 more unique random products
|
||||||
|
additional_random = get_random_products(5, popular_recs)
|
||||||
|
history_upload(user_id, additional_random)
|
||||||
|
|
||||||
|
return popular_recs + additional_random
|
||||||
|
|
||||||
# Calculate similarity between all products and user history
|
# Calculate similarity between all products and user history
|
||||||
user_profile = np.mean(user_history, axis=0) # Average user preferences
|
user_profile = np.mean(user_history, axis=0) # Average user preferences
|
||||||
similarities = cosine_similarity([user_profile], all_products)
|
similarities = cosine_similarity([user_profile], all_product_features)
|
||||||
# finds the indices of the top N products that have the highest
|
print(similarities)
|
||||||
# cosine similarity with the user's profile and sorted from most similar to least similar.
|
|
||||||
|
# Get indices of the top N products sorted by similarity
|
||||||
product_indices = similarities[0].argsort()[-top_n:][::-1]
|
product_indices = similarities[0].argsort()[-top_n:][::-1]
|
||||||
print("product", product_indices)
|
|
||||||
|
|
||||||
# Get the recommended product IDs
|
# Get the actual product IDs using the indices
|
||||||
recommended_products = [all_products[i][0] for i in product_indices] # Product IDs
|
recommended_product_ids = [all_product_ids[i] for i in product_indices]
|
||||||
|
|
||||||
# Upload the recommendations to the database
|
# Upload the core recommendations to the database
|
||||||
history_upload(user_id, product_indices) # Pass the indices directly to history_upload
|
history_upload(user_id, recommended_product_ids)
|
||||||
|
|
||||||
|
# Add 5 more unique random products that aren't in the recommendations
|
||||||
|
additional_random = get_random_products(5, recommended_product_ids)
|
||||||
|
history_upload(user_id, additional_random)
|
||||||
|
|
||||||
|
# Return both the similarity-based recommendations and the random ones
|
||||||
|
return recommended_product_ids + additional_random
|
||||||
|
|
||||||
# Return recommended product IDs
|
|
||||||
return recommended_products
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logging.error(f"Recommendation error for user {user_id}: {str(e)}")
|
logging.error(f"Recommendation error for user {user_id}: {str(e)}")
|
||||||
# return get_popular_products(top_n) # Fallback to popular products
|
# Fallback to random products
|
||||||
|
random_products = get_random_products(top_n + 5)
|
||||||
|
return random_products
|
||||||
|
|
||||||
def history_upload(userID, anrr):
|
def history_upload(userID, products):
|
||||||
|
"""Upload product recommendations to the database"""
|
||||||
db_con = database()
|
db_con = database()
|
||||||
cursor = db_con.cursor()
|
cursor = db_con.cursor()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
for item in anrr:
|
for product_id in products:
|
||||||
#Product ID starts form index 1
|
|
||||||
item_value = item + 1
|
|
||||||
print(item_value)
|
|
||||||
# Use parameterized queries to prevent SQL injection
|
# Use parameterized queries to prevent SQL injection
|
||||||
cursor.execute(f"INSERT INTO Recommendation (UserID, RecommendedProductID) VALUES ({userID}, {item_value});")
|
cursor.execute("INSERT INTO Recommendation (UserID, RecommendedProductID) VALUES (%s, %s)",
|
||||||
|
(userID, product_id))
|
||||||
|
|
||||||
# Commit the changes
|
# Commit the changes
|
||||||
db_con.commit()
|
db_con.commit()
|
||||||
|
|
||||||
# If you need results, you'd typically fetch them after a SELECT query
|
|
||||||
#results = cursor.fetchall()
|
|
||||||
#print(results)
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error: {e}")
|
logging.error(f"Error uploading recommendations: {str(e)}")
|
||||||
db_con.rollback()
|
db_con.rollback()
|
||||||
finally:
|
finally:
|
||||||
# Close the cursor and connection
|
# Close the cursor and connection
|
||||||
|
|||||||
Reference in New Issue
Block a user