doc1
doc1
// MongoDB connection
mongoose.connect('mongodb://localhost:27017/farmconnect', { useNewUrlParser: true,
useUnifiedTopology: true });
app.listen(5000, () => {
console.log('Server is running on port 5000');
});
function ProductSellingPage() {
const [productName, setProductName] = useState("");
const [description, setDescription] = useState("");
const [price, setPrice] = useState("");
const [category, setCategory] = useState("");
const [quantity, setQuantity] = useState("");
const [image, setImage] = useState(null);
try {
const response = await fetch("http://localhost:5000/api/add-product", {
method: "POST",
body: formData,
});
const data = await response.json();
if (data.success) {
alert("Product added successfully!");
} else {
alert(data.message);
}
} catch (error) {
console.error("Error uploading product:", error);
}
};
return (
<div className="product-selling-page-container">
<form className="product-selling-form" onSubmit={handleSubmit}>
<h2>Sell Your Product</h2>
<input
type="text"
placeholder="Product Name"
value={productName}
onChange={(e) => setProductName(e.target.value)}
required
/>
<textarea
placeholder="Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
required
/>
<input
type="number"
placeholder="Price"
value={price}
onChange={(e) => setPrice(e.target.value)}
required
/>
<select value={category} onChange={(e) => setCategory(e.target.value)} required>
<option value="">Select Category</option>
<option value="fruits">Fruits</option>
<option value="vegetables">Vegetables</option>
<option value="grains">Grains</option>
<option value="dairy">Dairy</option>
<option value="others">Others</option>
</select>
<input
type="number"
placeholder="Quantity"
value={quantity}
onChange={(e) => setQuantity(e.target.value)}
required
/>
<input
type="file"
accept="image/*"
onChange={(e) => setImage(e.target.files[0])}
required
/>
<button type="submit">Submit Product</button>
</form>
</div>
);
}
useEffect(() => {
const fetchProducts = async () => {
const response = await fetch(`http://localhost:5000/api/products/${category}`);
const data = await response.json();
setProducts(data);
};
fetchProducts();
}, [category]);
return (
<div className="products-container">
<h2>{category.charAt(0).toUpperCase() + category.slice(1)} Products</h2>
<div className="products-list">
{products.map((product) => (
<div key={product._id} className="product-card">
<img src={`http://localhost:5000${product.imageUrl}`} alt={product.name} />
<h3>{product.name}</h3>
<p>{product.description}</p>
<p>Price: ₹{product.price}</p>
<p>Quantity: {product.quantity} kg</p>
</div>
))}
</div>
</div>
);
};
// Initialize express
const app = express();
app.use(cors());
app.use(bodyParser.json());
// MongoDB connection
mongoose.connect('mongodb://localhost:27017/farmerswebsite', {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log('MongoDB connected'))
.catch(err => console.log('MongoDB connection error:', err));
// Buyer Schema
const buyerSchema = new mongoose.Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
address: { type: String, required: true },
phoneNumber: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
// Password Validation
const validatePassword = (password) => {
const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/; // At least one letter, one number,
min 6 chars
return passwordRegex.test(password);
};
try {
// Validate phone number
if (!/^\d{10}$/.test(phoneNumber)) {
return res.status(400).json({ success: false, message: 'Phone number must be exactly 10 digits!' });
}
try {
// Check if the farmer already exists by email
const existingFarmer = await Farmer.findOne({ email });
if (existingFarmer) {
return res.status(400).json({ success: false, message: 'Farmer already exists with this email.' });
}
// Validate password
if (!validatePassword(password)) {
return res.status(400).json({ success: false, message: 'Password must be at least 6 characters long
and contain at least one letter and one number.' });
}
try {
// Find the buyer by email
const buyer = await Buyer.findOne({ email });
if (!buyer) {
return res.status(400).json({ success: false, message: 'Invalid email or password' });
}
try {
// Find the farmer by email
const farmer = await Farmer.findOne({ email });
if (!farmer) {
return res.status(400).json({ success: false, message: 'Invalid email or password' });
}
try {
const newProduct = new Product({ name, description, price, category, quantity, imageUrl,
farmerEmail });
await newProduct.save();
res.status(201).json({ success: true, message: 'Product added successfully' });
} catch (error) {
res.status(500).json({ success: false, message: 'Error adding product' });
}
});
// GET route for retrieving products by category
app.get('/api/products', async (req, res) => {
const { category } = req.query;
try {
const products = await Product.find({ category });
res.json({ success: true, products });
} catch (error) {
res.status(500).json({ success: false, message: 'Error fetching products' });
}
});
// // Initialize express
// const app = express();
// app.use(cors());
// app.use(bodyParser.json());
// app.use('/uploads', express.static('uploads')); // Serve static files from the 'uploads' directory
// // MongoDB connection
// mongoose.connect('mongodb://localhost:27017/farmerswebsite', {
// useNewUrlParser: true,
// useUnifiedTopology: true,
// }).then(() => console.log('MongoDB connected'))
// .catch(err => console.log('MongoDB connection error:', err));
// // Buyer Schema
// const buyerSchema = new mongoose.Schema({
// firstName: { type: String, required: true },
// lastName: { type: String, required: true },
// address: { type: String, required: true },
// phoneNumber: { type: String, required: true },
// email: { type: String, required: true, unique: true },
// password: { type: String, required: true },
// });
// // Farmer Schema
// const farmerSchema = new mongoose.Schema({
// firstName: { type: String, required: true },
// lastName: { type: String, required: true },
// email: { type: String, required: true, unique: true },
// password: { type: String, required: true },
// });
// try {
// const newProduct = new Product({
// name,
// description,
// price,
// unit,
// category,
// quantity,
// imageUrl,
// farmerDetails: JSON.parse(farmerDetails), // Parse farmerDetails from string
// });
// await newProduct.save();
// res.status(201).json({ success: true, message: 'Product added successfully' });
// } catch (error) {
// res.status(500).json({ success: false, message: 'Error adding product', error });
// }
// });
// try {
// const products = await Product.find(category ? { category } : {});
// res.json({ success: true, products });
// } catch (error) {
// res.status(500).json({ success: false, message: 'Error fetching products' });
// }
// });
// try {
// const products = await Product.find({ 'farmerDetails.email': email });
// res.json({ success: true, products });
// } catch (error) {
// res.status(500).json({ success: false, message: 'Error fetching products' });
// }
// });
// // If an image is uploaded, use the new image; otherwise, keep the old one
// const imageUrl = req.file ? req.file.path : undefined;
// try {
// const product = await Product.findById(productId);
// if (!product) {
// return res.status(404).json({ success: false, message: 'Product not found' });
// }
// await product.save();
// res.json({ success: true, message: 'Product updated successfully' });
// } catch (error) {
// res.status(500).json({ success: false, message: 'Error updating product', error });
// }
// });
// if (!deletedProduct) {
// return res.status(404).json({ success: false, message: 'Product not found' });
// }
// <div className="hero-section">
// <div className="hero-content">
// <h1>Empowering Farmers, Connecting You to Your Market</h1>
// <p>
// Sell your produce, connect with buyers, and grow your business with FarmConnect.
// </p>
// <button className="shop-now-btn" onClick={handleShopNowClick}>Get
Started</button>
// </div>
// </div>
// <div className="about-us-section">
// <div className="about-us-content">
// <h2>About Us</h2>
// <p><b>
// At FarmConnect, we empower farmers to directly connect with consumers,
enhancing their market reach. Our platform ensures that your high-quality agricultural products are
easily accessible, enabling you to grow your business while providing fresh produce to your
community.
// </b></p>
// </div>
// <img src={aboutImage} alt="About Us" className="about-us-image" />
// </div>
// <div className="subscription-section">
// <div className="subscription-content">
// <div className="subscription-image">
// <img src={subscriptionImage} alt="Subscription Benefits" />
// </div>
// <div className="subscription-text">
// <h2>Join Our Subscription Plan</h2>
// <p>Unlock exclusive benefits to maximize your farming potential!</p>
// <ul className="subscription-benefits">
// <li><b>Enjoy special offers on our services and tools.</b></li>
// <li><b>Connect with fellow farmers to share experiences and advice.</b></li>
// <li><b>Receive alerts on market trends to make informed decisions.</b></li>
// <li><b>Gain tools and information that enhance your productivity.</b></li>
// </ul>
// <button className="subscribe-btn">Subscribe Now</button>
// </div>
// </div>
// </div>
// </div>
// );
// };
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch (error) {
res.status(401).json({ message: 'Not authorized, token failed' });
}
}
if (!token) {
res.status(401).json({ message: 'Not authorized, no token' });
}
};
module.exports = { protect };
3. Add the Middleware to the Protected Route: Now, use this middleware to protect the route
where the farmer fetches their products.
js
Copy code
const { protect } = require('./middleware/authMiddleware');
const config = {
headers: {
Authorization: `Bearer ${token}`, // Send token in the Authorization header
},
};
fetchProducts();
}, []);
Explanation:
Backend:
o The protect middleware checks if a valid token is present in the request's
Authorization header.
o If valid, the middleware decodes the token to get the farmer's ID and attaches it to the
request object (req.user).
o The route handler for fetching products then uses the farmer's ID to retrieve only the
farmer's products.
Frontend:
o The token is stored after the farmer logs in.
o When fetching products for the farmer, the token is included in the request headers,
ensuring only authorized farmers can access their data.
By implementing this protection, only authenticated farmers can view their products on the "Your
Products" page.
const express = require('express');
// Initialize express
app.use(cors());
app.use(bodyParser.json());
// MongoDB connection
mongoose.connect('mongodb://localhost:27017/farmerswebsite', {
useNewUrlParser: true,
useUnifiedTopology: true,
// Buyer Schema
});
// Farmer Schema
});
// Password Validation
return passwordRegex.test(password);
};
try {
if (!/^\d{10}$/.test(phoneNumber)) {
return res.status(400).json({ success: false, message: 'Phone number must be exactly 10 digits!' });
if (existingBuyer) {
return res.status(400).json({ success: false, message: 'Buyer already exists with this email.' });
// Validate password
if (!validatePassword(password)) {
return res.status(400).json({ success: false, message: 'Password must be at least 6 characters long and
contain at least one letter and one number.' });
}
const newBuyer = new Buyer({ firstName, lastName, address, phoneNumber, email, password:
hashedPassword });
await newBuyer.save();
} catch (error) {
});
try {
if (!buyer) {
} catch (error) {
});
if (existingFarmer) {
return res.status(400).json({ success: false, message: 'Farmer already exists with this email.' });
// Validate password
if (!validatePassword(password)) {
return res.status(400).json({ success: false, message: 'Password must be at least 6 characters long and
contain at least one letter and one number.' });
const newFarmer = new Farmer({ firstName, lastName, email, password: hashedPassword });
await newFarmer.save();
} catch (error) {
});
try {
// Find the buyer by email
if (!buyer) {
if (!isMatch) {
} catch (error) {
});
try {
if (!farmer) {
if (!isMatch) {
} catch (error) {
});
app.listen(PORT, () => {
});
Cart.css
/* Cart.css */
.cart-page-container {
padding: 20px;
max-width: 800px;
margin: auto;
background-color: #f9f9f9;
border-radius: 8px;
.cart-page-container h1 {
text-align: center;
color: #333;
margin-bottom: 20px;
.cart-items {
display: flex;
flex-direction: column;
.cart-item {
display: flex;
background-color: #fff;
border-radius: 5px;
padding: 15px;
margin-bottom: 15px;
transition: transform 0.3s ease, box-shadow 0.3s ease;
.cart-item:hover {
transform: scale(1.02);
.cart-item-image {
.cart-item-details {
/* Button styling */
.cart-item button {
.cart-page-container p {
.quantity-controls {
.quantity-controls button {
.quantity-controls button:hover {
.cart-item-image {
object-fit: cover; /* Ensures the image fits well within the container */
Farmer login
// e.preventDefault();
// if (!/\S+@\S+\.\S+/.test(email)) {
// return;
// }
// setErrorMessage('');
// setLoading(true);
e.preventDefault();
try {
method: 'POST',
});
if (data.success) {
} else {
} catch (error) {
console.error(error);
};
// try {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// },
// });
// if (response.ok) {
// localStorage.setItem('farmerToken', data.token);
// localStorage.setItem('farmer', JSON.stringify(data.farmer));
// navigate('/farmer-dashboard');
// } else {
// }
// } catch (error) {
// // } finally {
// // setLoading(false);
// // }
// };
return (
<div
style={{
position: 'relative',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
backgroundImage: `url(${farmerLoginBackground})`,
backgroundSize: 'cover',
backgroundPosition: 'center',
backgroundRepeat: 'no-repeat',
}}
>
<div
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
zIndex: 1,
}}
></div>
<div
style={{
position: 'relative',
zIndex: 2,
textAlign: 'center',
color: '#fff',
}}
>
<h2
style={{
fontSize: '32px',
marginBottom: '20px',
}}
>
Farmer Login
</h2>
<form
onSubmit={handleLogin}
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}
>
<input
type="email"
placeholder="Email"
value={email}
style={{
margin: '10px',
padding: '10px',
width: '300px',
borderRadius: '5px',
backgroundColor: '#fff',
}}
required
/>
<input
type="password"
placeholder="Password"
value={password}
style={{
margin: '10px',
padding: '10px',
width: '300px',
borderRadius: '5px',
backgroundColor: '#fff',
}}
required
/>
{errorMessage && (
<p
style={{
color: 'red',
marginTop: '10px',
}}
>
{errorMessage}
</p>
)}
<button
type="submit"
style={{
width: '300px',
padding: '12px',
fontSize: '24px',
border: 'none',
borderRadius: '5px',
}}
disabled={loading}
>
</button>
</form>
</div>
</div>
);
};
// try {
// if (!buyer) {
// }
// // Check the password
// if (!isMatch) {
// }
// } catch (error) {
// }
// });
// try {
// if (!farmer) {
// }
// if (!isMatch) {
// }
// } catch (error) {
// console.error('Login error:', error);
// }
// });
import './ProductSellingPage.css';
function ProductSellingPage() {
farmerName: "",
location: "",
totalArea: "",
areaUnderCultivation: "",
cropCycle: "",
agricultureMethod: "",
});
};
};
// e.preventDefault();
// formData.append("name", productName);
// formData.append("description", description);
// formData.append("price", price);
// formData.append("category", category);
// formData.append("quantity", quantity);
// try {
// method: "POST",
// });
// if (data.success) {
// } else {
// }
// } catch (error) {
// }
// };
e.preventDefault();
const formData = new FormData();
formData.append("name", productName);
formData.append("description", description);
formData.append("price", price);
formData.append("category", category);
formData.append("quantity", quantity);
formData.append("unit", unit);
formData.append("productImage", imageFile);
formData.append("farmerDetails", JSON.stringify(farmerDetails));
try {
const token = 'your_jwt_secret'; // Retrieve your token from local storage or context
method: "POST",
headers: {
},
body: formData,
});
if (data.success) {
} else {
} catch (error) {
};
return (
<div className="product-selling-page-container">
<div className="form-container">
<label>Product Name:</label>
<input
type="text"
value={productName}
required
/>
<label>Description:</label>
<textarea
value={description}
required
/>
<input
type="number"
value={price}
required
/>
<label>Category:</label>
<select
value={category}
required
>
<option value="">Select Category</option>
<option value="fruits">Fruits</option>
<option value="vegetables">Vegetables</option>
<option value="grains">Grains</option>
</select>
<label>Quantity:</label>
<input
type="number"
value={quantity}
required
/>
<label>Unit:</label>
<select
value={unit}
required
>
<option value="dozen">Dozen</option>
</select>
<input
type="file"
accept="image/*"
onChange={handleImageUpload}
required
/>
<button type="submit" className="submit-button">
Submit Product
</button>
</form>
<form className="farmer-details-form">
<h2>Farmer Details</h2>
<label>Farmer Name:</label>
<input
type="text"
name="farmerName"
value={farmerDetails.farmerName}
onChange={handleFarmerDetailsChange}
required
/>
<label>Location:</label>
<input
type="text"
name="location"
placeholder="Enter location"
value={farmerDetails.location}
onChange={handleFarmerDetailsChange}
required
/>
<label>Total Area:</label>
<input
type="text"
name="totalArea"
value={farmerDetails.totalArea}
onChange={handleFarmerDetailsChange}
required
/>
<input
type="text"
name="areaUnderCultivation"
value={farmerDetails.areaUnderCultivation}
onChange={handleFarmerDetailsChange}
required
/>
<label>Crop Cycle:</label>
<input
type="text"
name="cropCycle"
value={farmerDetails.cropCycle}
onChange={handleFarmerDetailsChange}
required
/>
<label>Agriculture Method:</label>
<input
type="text"
name="agricultureMethod"
value={farmerDetails.agricultureMethod}
onChange={handleFarmerDetailsChange}
required
/>
</form>
</div>
</div>
);
// import './ProductSellingPage.css';
// function ProductSellingPage() {
// farmerName: "",
// location: "",
// totalArea: "",
// areaUnderCultivation: "",
// cropCycle: "",
// agricultureMethod: "",
// });
// };
// };
// e.preventDefault();
// const newProduct = {
// id: Date.now(),
// productName,
// description,
// price,
// category,
// quantity,
// unit,
// imageFile,
// farmerDetails
// };
// };
// return (
// <div className="product-selling-page-container">
// <div className="form-container">
// Submit Product
// </button>
// </form>
// </div>
// </div>
// );
// }
if (existingCartItem) {
existingCartItem.quantity += quantity;
await existingCartItem.save();
} else {
await newCartItem.save();
});
});
await CartItem.findByIdAndDelete(req.params.id);
});
import 'react-toastify/dist/ReactToastify.css';
useEffect(() => {
setCartItems(items);
}, []);
setCartItems(updatedItems);
localStorage.setItem('cartItems', JSON.stringify(updatedItems));
position: 'top-right',
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
});
};
);
setCartItems(updatedItems);
localStorage.setItem('cartItems', JSON.stringify(updatedItems));
};
return (
<>
<BuyerNavBar
/>
<div className="cart-page-container">
<h1>Your Cart</h1>
{cartItems.length === 0 ? (
):(
<div className="cart-items">
{cartItems.map(item => (
<div className="cart-item-details">
<h3>{item.name}</h3>
<span>{item.quantity}</span>
</div>
</div>
</div>
))}
</div>
)}
<ToastContainer />
</div>
</>
);
};
// Initialize express
app.use(cors());
app.use(bodyParser.json());
//MongoDB connection
mongoose.connect('mongodb://localhost:27017/farmerswebsite', {
useNewUrlParser: true,
useUnifiedTopology: true,
},
}
});
} else {
};
storage: storage,
fileFilter: fileFilter
});
// Buyer Schema
});
// Farmer Schema
});
farmerDetails: {
},
});
// Cart Schema
items: [
{
productId: { type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: true },
});
// Password Validation
return passwordRegex.test(password);
};
try {
if (!/^\d{10}$/.test(phoneNumber)) {
return res.status(400).json({ success: false, message: 'Phone number must be exactly 10 digits!' });
if (existingBuyer) {
return res.status(400).json({ success: false, message: 'Buyer already exists with this email.' });
// Validate password
if (!validatePassword(password)) {
return res.status(400).json({ success: false, message: 'Password must be at least 6 characters long and
contain at least one letter and one number.' });
const newBuyer = new Buyer({ firstName, lastName, address, phoneNumber, email, password:
hashedPassword });
await newBuyer.save();
} catch (error) {
});
// try {
// if (!buyer) {
// }
// } catch (error) {
// }
// });
return res.status(400).json({ success: false, message: 'All fields are required' });
try {
if (existingFarmer) {
return res.status(400).json({ success: false, message: 'Farmer already exists with this email.' });
// Validate password
if (!validatePassword(password)) {
return res.status(400).json({ success: false, message: 'Password must be at least 6 characters long and contain
at least one letter and one number.' });
const newFarmer = new Farmer({ firstName, lastName, email, password: hashedPassword });
await newFarmer.save();
} catch (error) {
});
const jwt = require('jsonwebtoken');
// if (!token) {
// return res.status(401).json({ success: false, message: 'Access token missing or invalid' });
// }
// try {
// req.user = decoded; // Attach decoded token data (like user id) to request object
// } catch (error) {
// }
// };
if (!token) {
if (err) {
}
console.log('Decoded Token:', user); // Log the token to verify its contents
req.user = user;
next();
});
};
try {
const buyer = await Buyer.findById(req.user.id); // Use the user ID from the decoded JWT
if (!buyer) {
} catch (error) {
});
try {
if (!buyer) {
if (!isMatch) {
}
// Generate JWT Token
const token = jwt.sign({ id: buyer._id, email: buyer.email }, JWT_SECRET, { expiresIn: '1h' });
} catch (error) {
});
try {
if (!farmer) {
if (!isMatch) {
const token = jwt.sign({ id: farmer._id, email: farmer.email }, JWT_SECRET, { expiresIn: '1h' });
} catch (error) {
});
try {
if (!buyer) {
} catch (error) {
});
// const imageUrl = req.file.path; // Get the image file path from multer
// try {
// name,
// description,
// price,
// unit,
// category,
// quantity,
// imageUrl,
// });
// await newProduct.save();
// } catch (error) {
// }
// });
const ensureFarmer = (req, res, next) => {
return res.status(403).json({ success: false, message: 'Only farmers can perform this action' });
next();
};
try {
// Ensure that only users with the role of 'farmer' can add products
return res.status(403).json({ success: false, message: 'Only farmers can add products' });
name,
description,
price,
unit,
category,
quantity,
imageUrl,
});
await newProduct.save();
} catch (error) {
console.error('Error adding product:', error);
res.status(500).json({ success: false, message: 'Error adding product', error: error.message });
});
try {
} catch (error) {
});
try {
} catch (error) {
});
// try {
// }
// } catch (error) {
// }
// });
try {
if (!buyer) {
} catch (error) {
});
// If an image is uploaded, use the new image; otherwise, keep the old one
try {
if (!product) {
return res.status(404).json({ success: false, message: 'Product not found' });
await product.save();
} catch (error) {
});
try {
if (!deletedProduct) {
} catch (error) {
res.status(500).json({ success: false, message: 'Error deleting product', error });
});
console.error(err.stack);
});
try {
const farmerId = req.user.id; // Assuming the farmer's ID is stored in the session or token
const farmer = await Farmer.findById(farmerId); // Query the database for farmer details
if (!farmer) {
} catch (error) {
});
try {
if (!cart) {
cart = new Cart({ userId: req.user.id, items: [] });
if (existingItem) {
existingItem.quantity += quantity;
} else {
cart.items.push({
productId: product._id,
name: product.name,
price: product.price,
quantity,
imageUrl: product.imageUrl
});
await cart.save();
} catch (error) {
res.status(500).json({ success: false, message: 'Error adding item to cart', error });
});
try {
if (!cart) {
} catch (error) {
});
try {
if (!cart) return res.status(404).json({ success: false, message: 'Cart not found' });
await cart.save();
} catch (error) {
res.status(500).json({ success: false, message: 'Error removing item from cart', error });
});
app.listen(PORT, () => {
});
token
try {
const buyer = await Buyer.findById(req.user.id); // Use the user ID from the decoded JWT
if (!buyer) {
} catch (error) {
});
if (!token) {
if (err) {
next();
});
};
User Authentication: Ensure you have a system to authenticate users and store their identifier (e.g., userID,
email) in localStorage when they log in.
Backend Storage (optional): If you're using a backend, you can store the cart in a database associated with
the user and fetch it using API requests instead of localStorage.
import "../styles/components/orderCard.css";
function getRandomInt(max) {
return (
<>
<img
src="https://res.cloudinary.com/dvuh4fz9d/image/upload/v1657615696/check_xyzqdd.png"
className="success-tick-img"
/>
</h3>
</h4>
</Link>
</div>
</>
);
};
// Buyer Schema
});
// const isSubscribed = false; // Replace with your logic for checking subscription status
// useEffect(() => {
// fetch(`http://localhost:5000/api/buyer-details?email=${buyerFromStorage.email}`)
// .then(data => {
// if (data.success) {
// setBuyer(data.buyer);
// } else {
// }
// })
// .catch(error => {
// });
// }
// setCartItems(savedCartItems);
// calculateTotalPrice(savedCartItems);
// }, []);
// setTotalPrice(total);
// };
// // Calculate delivery charge based on subscription status
// if (!buyer || !selectedAddress) {
// return;
// }
// navigate('/payment');
// };
// setSelectedAddress(buyer.address);
// };
// return (
// <>
// <BuyerNavBar />
// <div className="checkout-page-container">
// <h1>Checkout</h1>
// <div className="card-container">
// <div className="buyer-details-section">
// {buyer ? (
// <div className="buyer-details">
// <h2>Delivery Address</h2>
// <div className="address-option">
// <p><strong>Email:</strong> {buyer.email}</p>
// <p><strong>Address:</strong> {buyer.address}</p>
// </div>
// <div className="default-address-selection">
// <button
// onClick={handleDefaultAddressSelection}
// >
// </button>
// </div>
// </div>
// ):(
// )}
// </div>
// <div className="order-summary-section">
// <h2>Order Summary</h2>
// <div className="checkout-items">
// {cartItems.map(item => (
// <div className="checkout-item-details">
// <h3>{item.productId.name}</h3>
// <p>Quantity: {item.quantity}</p>
// </div>
// </div>
// ))}
// </div>
// <div className="price-details-card">
// <div className="price-detail">
// <p>Subtotal</p>
// <p>₹{totalPrice.toFixed(2)}</p>
// </div>
// <div className="price-detail">
// <p>Delivery Fee</p>
// </div>
// <p>Total Amount</p>
// <p>₹{(totalPrice + deliveryCharge).toFixed(2)}</p>
// </div>
// Proceed to Payment
// </button>
// </div>
// </div>
// </div>
// </div>
// </>
// );
// };