Merge branch 'main' into mannBranch

This commit is contained in:
Mann Patel
2025-03-23 18:31:10 -06:00
committed by GitHub
6 changed files with 358 additions and 359 deletions

View File

@@ -22,4 +22,8 @@
``` ```
### Database ### Database
1. To Create the DB use the command bellow
```Bash
python3 ./SQL_code/init-db.py
```
- MySql Version 9.2.0 - MySql Version 9.2.0

View File

@@ -36,7 +36,6 @@ CREATE TABLE Product (
StockQuantity INT, StockQuantity INT,
UserID INT, UserID INT,
Description TEXT, Description TEXT,
Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
CategoryID INT NOT NULL, CategoryID INT NOT NULL,
Date DATETIME DEFAULT CURRENT_TIMESTAMP, Date DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (UserID) REFERENCES User (UserID), FOREIGN KEY (UserID) REFERENCES User (UserID),
@@ -121,304 +120,276 @@ CREATE TABLE AuthVerification (
Authenticated BOOLEAN DEFAULT FALSE, Authenticated BOOLEAN DEFAULT FALSE,
Date DATETIME DEFAULT CURRENT_TIMESTAMP Date DATETIME DEFAULT CURRENT_TIMESTAMP
); );
-- -- Insert sample categories
-- Insert sample categories -- INSERT INTO
INSERT INTO -- Category (CategoryID, Name)
Category (CategoryID, Name) -- VALUES
VALUES -- (1, 'Electronics'),
(1, 'Electronics'), -- (2, 'Clothing'),
(2, 'Clothing'), -- (3, 'Books'),
(3, 'Books'), -- (4, 'Home & Garden'),
(4, 'Home & Garden'), -- (5, 'Sports & Outdoors');
(5, 'Sports & Outdoors'); -- -- -- USER CRUD OPERATIONS
-- -- -- Create User (INSERT)
-- USER CRUD OPERATIONS -- -- INSERT INTO
-- Create User (INSERT) -- -- User (Name, Email, UCID, Password, Phone, Address)
INSERT INTO -- -- VALUES
User (Name, Email, UCID, Password, Phone, Address) -- -- (
VALUES -- -- 'John Doe',
( -- -- 'john@example.com',
'John Doe', -- -- 'UC123456',
'john@example.com', -- -- 'hashed_password_here',
'UC123456', -- -- '555-123-4567',
'hashed_password_here', -- -- '123 Main St'
'555-123-4567', -- -- );
'123 Main St' -- -- -- Set user role
); -- -- INSERT INTO
-- -- UserRole (UserID, Client, Admin)
-- Set user role -- -- VALUES
INSERT INTO -- -- (LAST_INSERT_ID (), TRUE, FALSE);
UserRole (UserID, Client, Admin) -- -- -- Read User (SELECT)
VALUES -- -- SELECT
(LAST_INSERT_ID (), TRUE, FALSE); -- -- u.*,
-- -- ur.Client,
-- Read User (SELECT) -- -- ur.Admin
SELECT -- -- FROM
u.*, -- -- User u
ur.Client, -- -- JOIN UserRole ur ON u.UserID = ur.UserID
ur.Admin -- -- WHERE
FROM -- -- u.UserID = 1;
User u -- -- -- Update User (UPDATE)
JOIN UserRole ur ON u.UserID = ur.UserID -- -- UPDATE User
WHERE -- -- SET
u.UserID = 1; -- -- Name = 'John Smith',
-- -- Phone = '555-987-6543',
-- Update User (UPDATE) -- -- Address = '456 Elm St'
UPDATE User -- -- WHERE
SET -- -- UserID = 1;
Name = 'John Smith', -- -- -- Update User Role
Phone = '555-987-6543', -- -- UPDATE UserRole
Address = '456 Elm St' -- -- SET
WHERE -- -- Admin = TRUE
UserID = 1; -- -- WHERE
-- -- UserID = 1;
-- Update User Role -- -- -- PRODUCT CRUD OPERATIONS
UPDATE UserRole -- -- -- Create Product (INSERT)
SET -- -- INSERT INTO
Admin = TRUE -- -- Product (
WHERE -- -- ProductID,
UserID = 1; -- -- Name,
-- -- Price,
-- PRODUCT CRUD OPERATIONS -- -- StockQuantity,
-- Create Product (INSERT) -- -- UserID,
INSERT INTO -- -- Description,
Product ( -- -- CategoryID
ProductID, -- -- )
Name, -- -- VALUES
Price, -- -- (
StockQuantity, -- -- 1,
UserID, -- -- 'Smartphone',
Description, -- -- 599.99,
CategoryID -- -- 50,
) -- -- 1,
VALUES -- -- 'Latest model smartphone with amazing features',
( -- -- 1
1, -- -- );
'Smartphone', -- -- -- Add product images with the placeholder URL
599.99, -- -- INSERT INTO
50, -- -- Image_URL (URL, ProductID)
1, -- -- VALUES
'Latest model smartphone with amazing features', -- -- ('https://picsum.photos/id/237/200/300', 1),
1 -- -- ('https://picsum.photos/id/237/200/300', 1);
); -- -- -- Create another product for recommendations
-- -- INSERT INTO
-- Add product images with the placeholder URL -- -- Product (
INSERT INTO -- -- ProductID,
Image_URL (URL, ProductID) -- -- Name,
VALUES -- -- Price,
('https://picsum.photos/id/237/200/300', 1), -- -- StockQuantity,
('https://picsum.photos/id/237/200/300', 1); -- -- UserID,
-- -- Description,
-- Create another product for recommendations -- -- CategoryID
INSERT INTO -- -- )
Product ( -- -- VALUES
ProductID, -- -- (
Name, -- -- 2,
Price, -- -- 'Tablet',
StockQuantity, -- -- 799.99,
UserID, -- -- 30,
Description, -- -- 1,
CategoryID -- -- 'High-performance tablet',
) -- -- 1
VALUES -- -- );
( -- -- -- Add placeholder images for the second product
2, -- -- INSERT INTO
'Tablet', -- -- Image_URL (URL, ProductID)
799.99, -- -- VALUES
30, -- -- ('https://picsum.photos/id/237/200/300', 2),
1, -- -- ('https://picsum.photos/id/237/200/300', 2);
'High-performance tablet', -- -- -- Read Product (SELECT)
1 -- -- SELECT
); -- -- p.*,
-- -- c.Name as CategoryName,
-- Add placeholder images for the second product -- -- u.Name as SellerName,
INSERT INTO -- -- i.URL as ImageURL
Image_URL (URL, ProductID) -- -- FROM
VALUES -- -- Product p
('https://picsum.photos/id/237/200/300', 2), -- -- JOIN Category c ON p.CategoryID = c.CategoryID
('https://picsum.photos/id/237/200/300', 2); -- -- JOIN User u ON p.UserID = u.UserID
-- -- LEFT JOIN Image_URL i ON p.ProductID = i.ProductID
-- Read Product (SELECT) -- -- WHERE
SELECT -- -- p.ProductID = 1;
p.*, -- -- -- Update Product (UPDATE)
c.Name as CategoryName, -- -- UPDATE Product
u.Name as SellerName, -- -- SET
i.URL as ImageURL -- -- Name = 'Premium Smartphone',
FROM -- -- Price = 649.99,
Product p -- -- StockQuantity = 45,
JOIN Category c ON p.CategoryID = c.CategoryID -- -- Description = 'Updated description with new features'
JOIN User u ON p.UserID = u.UserID -- -- WHERE
LEFT JOIN Image_URL i ON p.ProductID = i.ProductID -- -- ProductID = 1;
WHERE -- -- -- CATEGORY CRUD OPERATIONS
p.ProductID = 1; -- -- -- Create Category (INSERT)
-- -- INSERT INTO
-- Update Product (UPDATE) -- -- Category (CategoryID, Name)
UPDATE Product -- -- VALUES
SET -- -- (6, 'Toys & Games');
Name = 'Premium Smartphone', -- -- -- Read Category (SELECT)
Price = 649.99, -- -- SELECT
StockQuantity = 45, -- -- *
Description = 'Updated description with new features' -- -- FROM
WHERE -- -- Category
ProductID = 1; -- -- WHERE
-- -- CategoryID = 6;
-- CATEGORY CRUD OPERATIONS -- -- -- Update Category (UPDATE)
-- Create Category (INSERT) -- -- UPDATE Category
INSERT INTO -- -- SET
Category (CategoryID, Name) -- -- Name = 'Toys & Children''s Games'
VALUES -- -- WHERE
(6, 'Toys & Games'); -- -- CategoryID = 6;
-- -- -- REVIEW OPERATIONS
-- Read Category (SELECT) -- -- INSERT INTO
SELECT -- -- Review (ReviewID, UserID, ProductID, Comment, Rating)
* -- -- VALUES
FROM -- -- (
Category -- -- 1,
WHERE -- -- 1,
CategoryID = 6; -- -- 1,
-- -- 'Great product, very satisfied with the purchase!',
-- Update Category (UPDATE) -- -- 5
UPDATE Category -- -- );
SET -- -- -- TRANSACTION OPERATIONS
Name = 'Toys & Children''s Games' -- -- INSERT INTO
WHERE -- -- Transaction (TransactionID, UserID, ProductID, PaymentStatus)
CategoryID = 6; -- -- VALUES
-- -- (1, 1, 1, 'Completed');
-- REVIEW OPERATIONS -- -- -- HISTORY OPERATIONS
INSERT INTO -- -- INSERT INTO
Review (ReviewID, UserID, ProductID, Comment, Rating) -- -- History (HistoryID, UserID, ProductID)
VALUES -- -- VALUES
( -- -- (1, 1, 1);
1, -- -- -- Read History (SELECT)
1, -- -- SELECT
1, -- -- h.*,
'Great product, very satisfied with the purchase!', -- -- p.Name as ProductName
5 -- -- FROM
); -- -- History h
-- -- JOIN Product p ON h.ProductID = p.ProductID
-- TRANSACTION OPERATIONS -- -- WHERE
INSERT INTO -- -- h.UserID = 1
Transaction (TransactionID, UserID, ProductID, PaymentStatus) -- -- ORDER BY
VALUES -- -- h.Date DESC;
(1, 1, 1, 'Completed'); -- -- -- FAVORITES OPERATIONS
-- -- INSERT INTO
-- HISTORY OPERATIONS -- -- Favorites (UserID, ProductID)
INSERT INTO -- -- VALUES
History (HistoryID, UserID, ProductID) -- -- (1, 1);
VALUES -- -- -- Read Favorites (SELECT)
(1, 1, 1); -- -- SELECT
-- -- f.*,
-- Read History (SELECT) -- -- p.Name as ProductName,
SELECT -- -- p.Price
h.*, -- -- FROM
p.Name as ProductName -- -- Favorites f
FROM -- -- JOIN Product p ON f.ProductID = p.ProductID
History h -- -- WHERE
JOIN Product p ON h.ProductID = p.ProductID -- -- f.UserID = 1;
WHERE -- -- -- RECOMMENDATION OPERATIONS
h.UserID = 1 -- -- INSERT INTO
ORDER BY -- -- Recommendation (RecommendationID_PK, UserID, RecommendedProductID)
h.Date DESC; -- -- VALUES
-- -- (1, 1, 2);
-- FAVORITES OPERATIONS -- -- -- Read Recommendations (SELECT)
INSERT INTO -- -- SELECT
Favorites (UserID, ProductID) -- -- r.*,
VALUES -- -- p.Name as RecommendedProductName,
(1, 1); -- -- p.Price,
-- -- p.Description
-- Read Favorites (SELECT) -- -- FROM
SELECT -- -- Recommendation r
f.*, -- -- JOIN Product p ON r.RecommendedProductID = p.ProductID
p.Name as ProductName, -- -- WHERE
p.Price -- -- r.UserID = 1;
FROM -- -- -- Authentication Operations
Favorites f -- -- -- Create verification code
JOIN Product p ON f.ProductID = p.ProductID -- -- INSERT INTO
WHERE -- -- AuthVerification (Email, VerificationCode)
f.UserID = 1; -- -- VALUES
-- -- ('new_user@example.com', '123456');
-- RECOMMENDATION OPERATIONS -- -- -- Update authentication status
INSERT INTO -- -- UPDATE AuthVerification
Recommendation (RecommendationID_PK, UserID, RecommendedProductID) -- -- SET
VALUES -- -- Authenticated = TRUE
(1, 1, 2); -- -- WHERE
-- -- Email = 'new_user@example.com'
-- Read Recommendations (SELECT) -- -- AND VerificationCode = '123456';
SELECT -- -- -- Get top-selling products
r.*, -- -- SELECT
p.Name as RecommendedProductName, -- -- p.ProductID,
p.Price, -- -- p.Name,
p.Description -- -- COUNT(t.TransactionID) as SalesCount,
FROM -- -- SUM(p.Price) as TotalRevenue
Recommendation r -- -- FROM
JOIN Product p ON r.RecommendedProductID = p.ProductID -- -- Product p
WHERE -- -- JOIN Transaction t ON p.ProductID = t.ProductID
r.UserID = 1; -- -- WHERE
-- -- t.PaymentStatus = 'Completed'
-- Authentication Operations -- -- GROUP BY
-- Create verification code -- -- p.ProductID,
INSERT INTO -- -- p.Name
AuthVerification (Email, VerificationCode) -- -- ORDER BY
VALUES -- -- SalesCount DESC
('new_user@example.com', '123456'); -- -- LIMIT
-- -- 10;
-- Update authentication status -- -- -- Get highest-rated products
UPDATE AuthVerification -- -- SELECT
SET -- -- p.ProductID,
Authenticated = TRUE -- -- p.Name,
WHERE -- -- AVG(r.Rating) as AverageRating,
Email = 'new_user@example.com' -- -- COUNT(r.ReviewID) as ReviewCount
AND VerificationCode = '123456'; -- -- FROM
-- -- Product p
-- Get top-selling products -- -- JOIN Review r ON p.ProductID = r.ProductID
SELECT -- -- GROUP BY
p.ProductID, -- -- p.ProductID,
p.Name, -- -- p.Name
COUNT(t.TransactionID) as SalesCount, -- -- HAVING
SUM(p.Price) as TotalRevenue -- -- ReviewCount >= 5
FROM -- -- ORDER BY
Product p -- -- AverageRating DESC
JOIN Transaction t ON p.ProductID = t.ProductID -- -- LIMIT
WHERE -- -- 10;
t.PaymentStatus = 'Completed' -- -- -- Get user purchase history with product details
GROUP BY -- -- SELECT
p.ProductID, -- -- t.TransactionID,
p.Name -- -- t.Date,
ORDER BY -- -- p.Name,
SalesCount DESC -- -- p.Price,
LIMIT -- -- t.PaymentStatus
10; -- -- FROM
-- -- Transaction t
-- Get highest-rated products -- -- JOIN Product p ON t.ProductID = p.ProductID
SELECT -- -- WHERE
p.ProductID, -- -- t.UserID = 1
p.Name, -- -- ORDER BY
AVG(r.Rating) as AverageRating, -- -- t.Date DESC;
COUNT(r.ReviewID) as ReviewCount
FROM
Product p
JOIN Review r ON p.ProductID = r.ProductID
GROUP BY
p.ProductID,
p.Name
HAVING
ReviewCount >= 5
ORDER BY
AverageRating DESC
LIMIT
10;
-- Get user purchase history with product details
SELECT
t.TransactionID,
t.Date,
p.Name,
p.Price,
t.PaymentStatus
FROM
Transaction t
JOIN Product p ON t.ProductID = p.ProductID
WHERE
t.UserID = 1
ORDER BY
t.Date DESC;

3
SQL_code/init-db.py Normal file
View File

@@ -0,0 +1,3 @@
import subprocess
if (subprocess.run("mysql -u root mysql < SQL_code/Schema.sql", shell=True, check=True)):
print("successfully created the Marketplace databse")

View File

@@ -13,13 +13,13 @@ exports.sendVerificationCode = async (req, res) => {
// Generate a random 6-digit code // Generate a random 6-digit code
const verificationCode = crypto.randomInt(100000, 999999).toString(); const verificationCode = crypto.randomInt(100000, 999999).toString();
console.log( console.log(
`Generated verification code for ${email}: ${verificationCode}` `Generated verification code for ${email}: ${verificationCode}`,
); );
// Check if email already exists in verification table // Check if email already exists in verification table
const [results, fields] = await db.execute( const [results, fields] = await db.execute(
"SELECT * FROM AuthVerification WHERE Email = ?", "SELECT * FROM AuthVerification WHERE Email = ?",
[email] [email],
); );
if (results.length > 0) { if (results.length > 0) {
@@ -27,7 +27,7 @@ exports.sendVerificationCode = async (req, res) => {
const [result] = await db.execute( const [result] = await db.execute(
`UPDATE AuthVerification SET VerificationCode = ?, Authenticated = FALSE, Date = CURRENT_TIMESTAMP `UPDATE AuthVerification SET VerificationCode = ?, Authenticated = FALSE, Date = CURRENT_TIMESTAMP
WHERE Email = ?`, WHERE Email = ?`,
[verificationCode, email] [verificationCode, email],
); );
// Send email and respond // Send email and respond
@@ -37,7 +37,7 @@ exports.sendVerificationCode = async (req, res) => {
// Insert new record // Insert new record
const [result] = await db.execute( const [result] = await db.execute(
"INSERT INTO AuthVerification (Email, VerificationCode, Authenticated) VALUES (?, ?, FALSE)", "INSERT INTO AuthVerification (Email, VerificationCode, Authenticated) VALUES (?, ?, FALSE)",
[email, verificationCode] [email, verificationCode],
); );
// Send email and respond // Send email and respond
await sendVerificationEmail(email, verificationCode); await sendVerificationEmail(email, verificationCode);
@@ -62,7 +62,7 @@ exports.verifyCode = async (req, res) => {
// Check verification code // Check verification code
const [results, fields] = await db.execute( const [results, fields] = await db.execute(
"SELECT * FROM AuthVerification WHERE Email = ? AND VerificationCode = ? AND Authenticated = 0 AND Date > DATE_SUB(NOW(), INTERVAL 15 MINUTE)", "SELECT * FROM AuthVerification WHERE Email = ? AND VerificationCode = ? AND Authenticated = 0 AND Date > DATE_SUB(NOW(), INTERVAL 15 MINUTE)",
[email, code] [email, code],
); );
if (results.length === 0) { if (results.length === 0) {
console.log(`Invalid or expired verification code for email ${email}`); console.log(`Invalid or expired verification code for email ${email}`);
@@ -76,7 +76,7 @@ exports.verifyCode = async (req, res) => {
// Mark as authenticated // Mark as authenticated
const [result] = await db.execute( const [result] = await db.execute(
"UPDATE AuthVerification SET Authenticated = TRUE WHERE Email = ?", "UPDATE AuthVerification SET Authenticated = TRUE WHERE Email = ?",
[email] [email],
); );
res.json({ res.json({
success: true, success: true,
@@ -95,7 +95,7 @@ exports.completeSignUp = async (req, res) => {
try { try {
const [results, fields] = await db.execute( const [results, fields] = await db.execute(
`SELECT * FROM AuthVerification WHERE Email = ? AND Authenticated = 1;`, `SELECT * FROM AuthVerification WHERE Email = ? AND Authenticated = 1;`,
[data.email] [data.email],
); );
if (results.length === 0) { if (results.length === 0) {
@@ -105,7 +105,7 @@ exports.completeSignUp = async (req, res) => {
// Create the user // Create the user
const [createResult] = await db.execute( const [createResult] = await db.execute(
`INSERT INTO User (Name, Email, UCID, Password, Phone, Address) `INSERT INTO User (Name, Email, UCID, Password, Phone, Address)
VALUES ('${data.name}', '${data.email}', '${data.UCID}', '${data.password}', '${data.phone}', '${data.address}')` VALUES ('${data.name}', '${data.email}', '${data.UCID}', '${data.password}', '${data.phone}', '${data.address}')`,
); );
// Insert role using the user's ID // Insert role using the user's ID
@@ -113,12 +113,12 @@ exports.completeSignUp = async (req, res) => {
`INSERT INTO UserRole (UserID, Client, Admin) `INSERT INTO UserRole (UserID, Client, Admin)
VALUES (LAST_INSERT_ID(), ${data.client || true}, ${ VALUES (LAST_INSERT_ID(), ${data.client || true}, ${
data.admin || false data.admin || false
})` })`,
); );
// Delete verification record // Delete verification record
const [deleteResult] = await db.execute( const [deleteResult] = await db.execute(
`DELETE FROM AuthVerification WHERE Email = '${data.email}'` `DELETE FROM AuthVerification WHERE Email = '${data.email}'`,
); );
res.json({ res.json({
@@ -194,37 +194,47 @@ exports.findUserByEmail = async (req, res) => {
}; };
exports.updateUser = async (req, res) => { exports.updateUser = async (req, res) => {
const { userId, ...updateData } = req.body; try {
const userId = req.body?.userId;
const name = req.body?.name;
const email = req.body?.email;
const phone = req.body?.phone;
const UCID = req.body?.UCID;
const address = req.body?.address;
if (!userId) { if (!userId) {
return res.status(400).json({ error: "User ID is required" }); return res.status(400).json({ error: "User ID is required" });
} }
//query dynamically based on provided fields // Build updateData manually
const updateData = {};
if (name) updateData.name = name;
if (email) updateData.email = email;
if (phone) updateData.phone = phone;
if (UCID) updateData.UCID = UCID;
if (address) updateData.address = address;
if (Object.keys(updateData).length === 0) {
return res.status(400).json({ error: "No valid fields to update" });
}
const updateFields = []; const updateFields = [];
const values = []; const values = [];
Object.entries(updateData).forEach(([key, value]) => { Object.entries(updateData).forEach(([key, value]) => {
// Only include fields that are actually in the User table
if (["Name", "Email", "Password", "Phone", "UCID"].includes(key)) {
updateFields.push(`${key} = ?`); updateFields.push(`${key} = ?`);
values.push(value); values.push(value);
}
}); });
if (updateFields.length === 0) {
return res.status(400).json({ error: "No valid fields to update" });
}
// Add userId to values array
values.push(userId); values.push(userId);
try { const query = `UPDATE User SET ${updateFields.join(", ")} WHERE userId = ?`;
const query = `UPDATE User SET ${updateFields.join(", ")} WHERE UserID = ?`;
const [updateResult] = await db.execute(query, values); const [updateResult] = await db.execute(query, values);
if (updateResult.affectedRows === 0) { if (updateResult.affectedRows === 0) {
return res.status(404).json({ error: "User not found" }); return res.status(404).json({ error: "User not found" });
} }
res.json({ success: true, message: "User updated successfully" }); res.json({ success: true, message: "User updated successfully" });
} catch (error) { } catch (error) {
console.error("Error updating user:", error); console.error("Error updating user:", error);
@@ -243,7 +253,7 @@ exports.deleteUser = async (req, res) => {
// Delete from UserRole first (assuming foreign key constraint) // Delete from UserRole first (assuming foreign key constraint)
const [result1] = await db.execute( const [result1] = await db.execute(
"DELETE FROM UserRole WHERE UserID = ?", "DELETE FROM UserRole WHERE UserID = ?",
[userId] [userId],
); );
// Then delete from User table // Then delete from User table

View File

@@ -2,11 +2,10 @@ const mysql = require("mysql2");
//Create a pool of connections to allow multiple query happen at the same time //Create a pool of connections to allow multiple query happen at the same time
const pool = mysql.createPool({ const pool = mysql.createPool({
host: "marketplace-db.cpkkqmq065sx.ca-central-1.rds.amazonaws.com", host: "localhost",
user: "admin", user: "root",
password: "qizsYh-movpub-wuhdo2", database: "marketplace",
database: "Marketplace", password: "12345678",
port: "3306",
}); });
//Export a promise for promise-based query //Export a promise for promise-based query

View File

@@ -43,7 +43,7 @@ const Settings = () => {
body: JSON.stringify({ body: JSON.stringify({
email: storedUser.email, email: storedUser.email,
}), }),
} },
); );
const data = await response.json(); const data = await response.json();
@@ -53,7 +53,7 @@ const Settings = () => {
// Update state with fetched data // Update state with fetched data
setUserData((prevData) => ({ setUserData((prevData) => ({
...prevData, ...prevData,
userId: data.userId || storedUser.id || "", // Try both sources userId: storedUser.ID, // Try both sources
name: data.name || storedUser.name || "", name: data.name || storedUser.name || "",
email: data.email || storedUser.email || "", email: data.email || storedUser.email || "",
UCID: data.UCID || storedUser.UCID || "", UCID: data.UCID || storedUser.UCID || "",
@@ -70,7 +70,7 @@ const Settings = () => {
} catch (error) { } catch (error) {
console.error("Error fetching user data:", error); console.error("Error fetching user data:", error);
setError( setError(
error.message || "An error occurred while loading your profile" error.message || "An error occurred while loading your profile",
); );
} finally { } finally {
setIsLoading(false); setIsLoading(false);
@@ -88,27 +88,39 @@ const Settings = () => {
})); }));
}; };
const handleProfileUpdate = async (e) => { const handleUpdateProfile = async () => {
e.preventDefault();
try { try {
// TODO: Implement the actual update API call // Ensure userId is present
console.log("Profile updated:", userData); if (!userData.userId) {
throw new Error("User ID is missing. Unable to update profile.");
}
// Update localStorage with new user data setIsLoading(true);
const storedUser = JSON.parse(localStorage.getItem("user")); setError(null);
const updatedUser = {
...storedUser,
name: userData.name,
phone: userData.phone,
UCID: userData.UCID,
address: userData.address,
};
localStorage.setItem("user", JSON.stringify(updatedUser));
const response = await fetch("http://localhost:3030/api/user/update", {
method: "POST", // or "PUT" if your backend supports it
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userData),
});
const result = await response.json();
if (!response.ok) {
throw new Error(result.error || "Failed to update profile");
}
console.log("Profile updated successfully:", result);
alert("Profile updated successfully!"); alert("Profile updated successfully!");
} catch (error) { } catch (error) {
console.error("Error updating profile:", error); console.error("Error updating profile:", error);
alert("Failed to update profile: " + error.message); setError(
error.message || "An error occurred while updating your profile.",
);
} finally {
setIsLoading(false);
} }
}; };
@@ -156,7 +168,7 @@ const Settings = () => {
const handleDeleteAccount = async () => { const handleDeleteAccount = async () => {
if ( if (
window.confirm( window.confirm(
"Are you sure you want to delete your account? This action cannot be undone." "Are you sure you want to delete your account? This action cannot be undone.",
) )
) { ) {
try { try {
@@ -232,7 +244,7 @@ const Settings = () => {
</div> </div>
<div className="p-4"> <div className="p-4">
<form onSubmit={handleProfileUpdate}> <form onSubmit={handleUpdateProfile}>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
<div> <div>
<label <label