This commit is contained in:
Mann Patel
2025-04-19 10:22:16 -06:00
parent dee6e3ce10
commit d169c9ba58
7 changed files with 135 additions and 127 deletions

View File

@@ -1,34 +1,22 @@
const db = require("../utils/database"); const db = require("../utils/database");
exports.addProduct = async (req, res) => { exports.addProduct = async (req, res) => {
const { userID, name, price, qty, description, category, images } = req.body; const { userID, name, price, stockQty, Description } = req.body;
console.log(userID);
try { try {
// Use parameterized query to prevent SQL injection
const [result] = await db.execute( const [result] = await db.execute(
`INSERT INTO Product (Name, Price, StockQuantity, UserID, Description, CategoryID) VALUES (?, ?, ?, ?, ?, ?)`, `INSERT INTO Favorites (UserID, ProductID) VALUES (?, ?)`,
[name, price, qty, userID, description, category], [userID, productID],
); );
const productID = result.insertId;
if (images && images.length > 0) {
const imageInsertPromises = images.map((imagePath) =>
db.execute(`INSERT INTO Image_URL (URL, ProductID) VALUES (?, ?)`, [
imagePath,
productID,
]),
);
await Promise.all(imageInsertPromises); //perallel
}
res.json({ res.json({
success: true, success: true,
message: "Product and images added successfully", message: "Product added to favorites successfully",
}); });
} catch (error) { } catch (error) {
console.error("Error adding product or images:", error); console.error("Error adding favorite product:", error);
console.log(error); return res.json({ error: "Could not add favorite product" });
return res.json({ error: "Could not add product or images" });
} }
}; };
@@ -72,6 +60,49 @@ exports.removeFavorite = async (req, res) => {
} }
}; };
exports.myProduct = async (req, res) => {
const { userID } = req.body;
try {
const [favorites] = await db.execute(
`
SELECT
p.ProductID,
p.Name,
p.Description,
p.Price,
p.CategoryID,
p.UserID,
p.Date,
u.Name AS SellerName,
MIN(i.URL) AS image_url
FROM Product p
JOIN User u ON p.UserID = u.UserID
LEFT JOIN Image_URL i ON p.ProductID = i.ProductID
WHERE p.UserID = ?
GROUP BY
p.ProductID,
p.Name,
p.Description,
p.Price,
p.CategoryID,
p.UserID,
p.Date,
u.Name;
`,
[userID],
);
res.json({
success: true,
favorites: favorites,
});
} catch (error) {
console.error("Error retrieving favorites:", error);
res.status(500).json({ error: "Could not retrieve favorite products" });
}
};
exports.getFavorites = async (req, res) => { exports.getFavorites = async (req, res) => {
const { userID } = req.body; const { userID } = req.body;

View File

@@ -7,6 +7,7 @@ const {
getAllProducts, getAllProducts,
getProductById, getProductById,
addProduct, addProduct,
myProduct,
} = require("../controllers/product"); } = require("../controllers/product");
const router = express.Router(); const router = express.Router();
@@ -20,6 +21,7 @@ router.post("/addFavorite", addFavorite);
router.post("/getFavorites", getFavorites); router.post("/getFavorites", getFavorites);
router.post("/delFavorite", removeFavorite); router.post("/delFavorite", removeFavorite);
router.post("/myProduct", myProduct);
router.post("/addProduct", addProduct); router.post("/addProduct", addProduct);
router.get("/getProduct", getAllProducts); router.get("/getProduct", getAllProducts);
router.get("/:id", getProductById); // Simplified route router.get("/:id", getProductById); // Simplified route

View File

@@ -30,8 +30,6 @@ function App() {
const [error, setError] = useState(""); const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [userId, setUserId] = useState(null);
// 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);
@@ -384,8 +382,6 @@ function App() {
isAuthenticated, isAuthenticated,
}; };
console.log("Sending user data to the server:", requestData);
// Send data to Python server (replace with your actual server URL) // Send data to Python server (replace with your actual server URL)
const response = await fetch("http://0.0.0.0:5000/api/user/session", { const response = await fetch("http://0.0.0.0:5000/api/user/session", {
method: "POST", method: "POST",

View File

@@ -1,5 +1,5 @@
import React, { useState } from "react"; import React, { useState, useEffect } from "react";
import { X, ChevronLeft, Plus, Trash2, Check } from "lucide-react"; import { X, ChevronLeft, Plus, Trash2 } from "lucide-react";
const ProductForm = ({ const ProductForm = ({
editingProduct, editingProduct,
@@ -8,46 +8,42 @@ const ProductForm = ({
onCancel, onCancel,
}) => { }) => {
const [selectedCategory, setSelectedCategory] = useState(""); const [selectedCategory, setSelectedCategory] = useState("");
const [categories, setCategories] = useState([]);
const [categoryMapping, setCategoryMapping] = useState({});
const storedUser = JSON.parse(sessionStorage.getItem("user")); const storedUser = JSON.parse(sessionStorage.getItem("user"));
const categories = [ // Fetch categories from API
"Electronics", useEffect(() => {
"Clothing", const fetchCategories = async () => {
"Home & Garden", try {
"Toys & Games", const response = await fetch("http://localhost:3030/api/category");
"Books", if (!response.ok) throw new Error("Failed to fetch categories");
"Sports & Outdoors",
"Automotive",
"Beauty & Personal Care",
"Health & Wellness",
"Jewelry",
"Art & Collectibles",
"Food & Beverages",
"Office Supplies",
"Pet Supplies",
"Music & Instruments",
"Other",
];
// Map category names to their respective IDs const responseJson = await response.json();
const categoryMapping = { const data = responseJson.data;
Electronics: 1,
Clothing: 2, // Create an array of category names for the dropdown
"Home & Garden": 3, // Transform the object into an array of category names
"Toys & Games": 4, const categoryNames = [];
Books: 5, const mapping = {};
"Sports & Outdoors": 6,
Automotive: 7, // Process the data properly to avoid rendering objects
"Beauty & Personal Care": 8, Object.entries(data).forEach(([id, name]) => {
"Health & Wellness": 9, // Make sure each category name is a string
Jewelry: 10, const categoryName = String(name);
"Art & Collectibles": 11, categoryNames.push(categoryName);
"Food & Beverages": 12, mapping[categoryName] = parseInt(id);
"Office Supplies": 13, });
"Pet Supplies": 14,
"Music & Instruments": 15, setCategories(categoryNames);
Other: 16, setCategoryMapping(mapping);
}; } catch (error) {
console.error("Error fetching categories:", error);
}
};
fetchCategories();
}, []);
const handleSave = async () => { const handleSave = async () => {
// Check if the user has selected at least one category // Check if the user has selected at least one category
@@ -61,13 +57,9 @@ const ProductForm = ({
const imagePaths = []; const imagePaths = [];
// If we have files to upload, we'd handle the image upload here // If we have files to upload, we'd handle the image upload here
// This is a placeholder for where you'd implement image uploads
// For now, we'll simulate the API expecting paths:
if (editingProduct.images && editingProduct.images.length > 0) { if (editingProduct.images && editingProduct.images.length > 0) {
// Simulating image paths for demo purposes // Simulating image paths for demo purposes
// In a real implementation, you would upload these files first editingProduct.images.forEach((file) => {
// and then use the returned paths
editingProduct.images.forEach((file, index) => {
const simulatedPath = `/public/uploads/${file.name}`; const simulatedPath = `/public/uploads/${file.name}`;
imagePaths.push(simulatedPath); imagePaths.push(simulatedPath);
}); });
@@ -75,13 +67,13 @@ const ProductForm = ({
// Get the category ID from the first selected category // Get the category ID from the first selected category
const categoryName = (editingProduct.categories || [])[0]; const categoryName = (editingProduct.categories || [])[0];
const categoryID = categoryMapping[categoryName] || 3; // Default to 3 if not found const categoryID = categoryMapping[categoryName] || 1; // Default to 3 if not found
// Prepare payload according to API expectations // Prepare payload according to API expectations
const payload = { const payload = {
name: editingProduct.name || "", name: editingProduct.name || "",
price: parseFloat(editingProduct.price) || 0, price: parseFloat(editingProduct.price) || 0,
qty: 1, // Hardcoded as per your requirement qty: 1,
userID: storedUser.ID, userID: storedUser.ID,
description: editingProduct.description || "", description: editingProduct.description || "",
category: categoryID, category: categoryID,
@@ -115,6 +107,24 @@ const ProductForm = ({
} }
}; };
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.id);
// 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);
}
};
const addCategory = () => { const addCategory = () => {
if ( if (
selectedCategory && selectedCategory &&
@@ -137,13 +147,6 @@ const ProductForm = ({
})); }));
}; };
const toggleSoldStatus = () => {
setEditingProduct((prev) => ({
...prev,
isSold: !prev.isSold,
}));
};
return ( return (
<div className="bg-white border border-gray-200 shadow-md p-6"> <div className="bg-white border border-gray-200 shadow-md p-6">
{/* Back Button */} {/* Back Button */}
@@ -196,18 +199,8 @@ const ProductForm = ({
{/* Sold Status */} {/* Sold Status */}
<div className="md:col-span-2"> <div className="md:col-span-2">
<div className="flex items-center mt-2"> <div className="flex items-center mt-2">
<input
type="checkbox"
id="soldStatus"
checked={editingProduct.isSold || false}
onChange={toggleSoldStatus}
className="w-4 h-4 text-emerald-600 rounded focus:ring-emerald-500"
/>
<label htmlFor="soldStatus" className="ml-2 text-sm text-gray-700">
Mark as {editingProduct.isSold ? "Available" : "Sold"}
</label>
{editingProduct.isSold && ( {editingProduct.isSold && (
<span className="ml-2 inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800"> <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800">
Sold Sold
</span> </span>
)} )}
@@ -232,8 +225,8 @@ const ProductForm = ({
.filter( .filter(
(cat) => !(editingProduct.categories || []).includes(cat), (cat) => !(editingProduct.categories || []).includes(cat),
) )
.map((category) => ( .map((category, index) => (
<option key={category} value={category}> <option key={index} value={category}>
{category} {category}
</option> </option>
))} ))}
@@ -252,9 +245,9 @@ const ProductForm = ({
{/* Selected Categories */} {/* Selected Categories */}
{(editingProduct.categories || []).length > 0 ? ( {(editingProduct.categories || []).length > 0 ? (
<div className="mt-2 flex flex-wrap gap-2"> <div className="mt-2 flex flex-wrap gap-2">
{(editingProduct.categories || []).map((category) => ( {(editingProduct.categories || []).map((category, index) => (
<span <span
key={category} key={index}
className="inline-flex items-center px-2 py-1 bg-emerald-100 text-emerald-800" className="inline-flex items-center px-2 py-1 bg-emerald-100 text-emerald-800"
> >
{category} {category}
@@ -375,33 +368,33 @@ const ProductForm = ({
</div> </div>
{/* Actions */} {/* Actions */}
<div className="mt-6 flex justify-between border-t border-gray-200 pt-4"> <div className="mt-6 flex justify-end gap-3 border-t border-gray-200 pt-4">
<button <button
onClick={toggleSoldStatus} onClick={onCancel}
className={`flex items-center gap-1 px-4 py-2 rounded-md transition-colors ${ className="bg-gray-100 text-gray-700 px-4 py-2 hover:bg-gray-200 rounded-md"
editingProduct.isSold
? "bg-green-100 text-green-700 hover:bg-green-200"
: "bg-red-100 text-red-700 hover:bg-red-200"
}`}
> >
<Check size={16} /> Cancel
<span>Mark as {editingProduct.isSold ? "Available" : "Sold"}</span>
</button> </button>
<div className="flex gap-3"> {editingProduct.id && (
<button <button
onClick={onCancel} onClick={markAsSold}
className="bg-gray-100 text-gray-700 px-4 py-2 hover:bg-gray-200 rounded-md" 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"
}`}
> >
Cancel Mark as {editingProduct.isSold ? "Available" : "Sold"}
</button> </button>
<button )}
onClick={handleSave}
className="bg-emerald-600 text-white px-6 py-2 hover:bg-emerald-700 rounded-md" <button
> onClick={handleSave}
{editingProduct.id ? "Update Product" : "Add Product"} className="bg-emerald-600 text-white px-6 py-2 hover:bg-emerald-700 rounded-md"
</button> >
</div> {editingProduct.id ? "Update Product" : "Add Product"}
</button>
</div> </div>
</div> </div>
); );

View File

@@ -12,7 +12,6 @@ const Selling = () => {
price: "", price: "",
description: "", description: "",
categories: [], categories: [],
status: "Unsold",
images: [], images: [],
}); });
@@ -28,7 +27,6 @@ const Selling = () => {
price: "299.99", price: "299.99",
description: "A beautiful vintage film camera in excellent condition", description: "A beautiful vintage film camera in excellent condition",
categories: ["Electronics", "Art & Collectibles"], categories: ["Electronics", "Art & Collectibles"],
status: "Unsold",
images: ["/public/Pictures/Dell1.jpg"], images: ["/public/Pictures/Dell1.jpg"],
}, },
{ {
@@ -37,7 +35,6 @@ const Selling = () => {
price: "149.50", price: "149.50",
description: "Genuine leather jacket, worn only a few times", description: "Genuine leather jacket, worn only a few times",
categories: ["Clothing"], categories: ["Clothing"],
status: "Unsold",
images: [], images: [],
}, },
]; ];
@@ -71,7 +68,6 @@ const Selling = () => {
price: "", price: "",
description: "", description: "",
categories: [], categories: [],
status: "Unsold",
images: [], images: [],
}); });
}; };
@@ -99,7 +95,6 @@ const Selling = () => {
price: "", price: "",
description: "", description: "",
categories: [], categories: [],
status: "Unsold",
images: [], images: [],
}); });
setShowForm(true); setShowForm(true);
@@ -164,15 +159,6 @@ const Selling = () => {
<h3 className="text-lg font-semibold text-gray-800"> <h3 className="text-lg font-semibold text-gray-800">
{product.name} {product.name}
</h3> </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> </div>
<p className="text-emerald-600 font-bold mt-1"> <p className="text-emerald-600 font-bold mt-1">