Merge branch 'main' into mannBranch
This commit is contained in:
@@ -22,4 +22,8 @@
|
||||
```
|
||||
|
||||
### Database
|
||||
1. To Create the DB use the command bellow
|
||||
```Bash
|
||||
python3 ./SQL_code/init-db.py
|
||||
```
|
||||
- MySql Version 9.2.0
|
||||
|
||||
@@ -36,7 +36,6 @@ CREATE TABLE Product (
|
||||
StockQuantity INT,
|
||||
UserID INT,
|
||||
Description TEXT,
|
||||
Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
CategoryID INT NOT NULL,
|
||||
Date DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (UserID) REFERENCES User (UserID),
|
||||
@@ -121,304 +120,276 @@ CREATE TABLE AuthVerification (
|
||||
Authenticated BOOLEAN DEFAULT FALSE,
|
||||
Date DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Insert sample categories
|
||||
INSERT INTO
|
||||
Category (CategoryID, Name)
|
||||
VALUES
|
||||
(1, 'Electronics'),
|
||||
(2, 'Clothing'),
|
||||
(3, 'Books'),
|
||||
(4, 'Home & Garden'),
|
||||
(5, 'Sports & Outdoors');
|
||||
|
||||
-- USER CRUD OPERATIONS
|
||||
-- Create User (INSERT)
|
||||
INSERT INTO
|
||||
User (Name, Email, UCID, Password, Phone, Address)
|
||||
VALUES
|
||||
(
|
||||
'John Doe',
|
||||
'john@example.com',
|
||||
'UC123456',
|
||||
'hashed_password_here',
|
||||
'555-123-4567',
|
||||
'123 Main St'
|
||||
);
|
||||
|
||||
-- Set user role
|
||||
INSERT INTO
|
||||
UserRole (UserID, Client, Admin)
|
||||
VALUES
|
||||
(LAST_INSERT_ID (), TRUE, FALSE);
|
||||
|
||||
-- Read User (SELECT)
|
||||
SELECT
|
||||
u.*,
|
||||
ur.Client,
|
||||
ur.Admin
|
||||
FROM
|
||||
User u
|
||||
JOIN UserRole ur ON u.UserID = ur.UserID
|
||||
WHERE
|
||||
u.UserID = 1;
|
||||
|
||||
-- Update User (UPDATE)
|
||||
UPDATE User
|
||||
SET
|
||||
Name = 'John Smith',
|
||||
Phone = '555-987-6543',
|
||||
Address = '456 Elm St'
|
||||
WHERE
|
||||
UserID = 1;
|
||||
|
||||
-- Update User Role
|
||||
UPDATE UserRole
|
||||
SET
|
||||
Admin = TRUE
|
||||
WHERE
|
||||
UserID = 1;
|
||||
|
||||
-- PRODUCT CRUD OPERATIONS
|
||||
-- Create Product (INSERT)
|
||||
INSERT INTO
|
||||
Product (
|
||||
ProductID,
|
||||
Name,
|
||||
Price,
|
||||
StockQuantity,
|
||||
UserID,
|
||||
Description,
|
||||
CategoryID
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
1,
|
||||
'Smartphone',
|
||||
599.99,
|
||||
50,
|
||||
1,
|
||||
'Latest model smartphone with amazing features',
|
||||
1
|
||||
);
|
||||
|
||||
-- Add product images with the placeholder URL
|
||||
INSERT INTO
|
||||
Image_URL (URL, ProductID)
|
||||
VALUES
|
||||
('https://picsum.photos/id/237/200/300', 1),
|
||||
('https://picsum.photos/id/237/200/300', 1);
|
||||
|
||||
-- Create another product for recommendations
|
||||
INSERT INTO
|
||||
Product (
|
||||
ProductID,
|
||||
Name,
|
||||
Price,
|
||||
StockQuantity,
|
||||
UserID,
|
||||
Description,
|
||||
CategoryID
|
||||
)
|
||||
VALUES
|
||||
(
|
||||
2,
|
||||
'Tablet',
|
||||
799.99,
|
||||
30,
|
||||
1,
|
||||
'High-performance tablet',
|
||||
1
|
||||
);
|
||||
|
||||
-- Add placeholder images for the second product
|
||||
INSERT INTO
|
||||
Image_URL (URL, ProductID)
|
||||
VALUES
|
||||
('https://picsum.photos/id/237/200/300', 2),
|
||||
('https://picsum.photos/id/237/200/300', 2);
|
||||
|
||||
-- Read Product (SELECT)
|
||||
SELECT
|
||||
p.*,
|
||||
c.Name as CategoryName,
|
||||
u.Name as SellerName,
|
||||
i.URL as ImageURL
|
||||
FROM
|
||||
Product p
|
||||
JOIN Category c ON p.CategoryID = c.CategoryID
|
||||
JOIN User u ON p.UserID = u.UserID
|
||||
LEFT JOIN Image_URL i ON p.ProductID = i.ProductID
|
||||
WHERE
|
||||
p.ProductID = 1;
|
||||
|
||||
-- Update Product (UPDATE)
|
||||
UPDATE Product
|
||||
SET
|
||||
Name = 'Premium Smartphone',
|
||||
Price = 649.99,
|
||||
StockQuantity = 45,
|
||||
Description = 'Updated description with new features'
|
||||
WHERE
|
||||
ProductID = 1;
|
||||
|
||||
-- CATEGORY CRUD OPERATIONS
|
||||
-- Create Category (INSERT)
|
||||
INSERT INTO
|
||||
Category (CategoryID, Name)
|
||||
VALUES
|
||||
(6, 'Toys & Games');
|
||||
|
||||
-- Read Category (SELECT)
|
||||
SELECT
|
||||
*
|
||||
FROM
|
||||
Category
|
||||
WHERE
|
||||
CategoryID = 6;
|
||||
|
||||
-- Update Category (UPDATE)
|
||||
UPDATE Category
|
||||
SET
|
||||
Name = 'Toys & Children''s Games'
|
||||
WHERE
|
||||
CategoryID = 6;
|
||||
|
||||
-- REVIEW OPERATIONS
|
||||
INSERT INTO
|
||||
Review (ReviewID, UserID, ProductID, Comment, Rating)
|
||||
VALUES
|
||||
(
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
'Great product, very satisfied with the purchase!',
|
||||
5
|
||||
);
|
||||
|
||||
-- TRANSACTION OPERATIONS
|
||||
INSERT INTO
|
||||
Transaction (TransactionID, UserID, ProductID, PaymentStatus)
|
||||
VALUES
|
||||
(1, 1, 1, 'Completed');
|
||||
|
||||
-- HISTORY OPERATIONS
|
||||
INSERT INTO
|
||||
History (HistoryID, UserID, ProductID)
|
||||
VALUES
|
||||
(1, 1, 1);
|
||||
|
||||
-- Read History (SELECT)
|
||||
SELECT
|
||||
h.*,
|
||||
p.Name as ProductName
|
||||
FROM
|
||||
History h
|
||||
JOIN Product p ON h.ProductID = p.ProductID
|
||||
WHERE
|
||||
h.UserID = 1
|
||||
ORDER BY
|
||||
h.Date DESC;
|
||||
|
||||
-- FAVORITES OPERATIONS
|
||||
INSERT INTO
|
||||
Favorites (UserID, ProductID)
|
||||
VALUES
|
||||
(1, 1);
|
||||
|
||||
-- Read Favorites (SELECT)
|
||||
SELECT
|
||||
f.*,
|
||||
p.Name as ProductName,
|
||||
p.Price
|
||||
FROM
|
||||
Favorites f
|
||||
JOIN Product p ON f.ProductID = p.ProductID
|
||||
WHERE
|
||||
f.UserID = 1;
|
||||
|
||||
-- RECOMMENDATION OPERATIONS
|
||||
INSERT INTO
|
||||
Recommendation (RecommendationID_PK, UserID, RecommendedProductID)
|
||||
VALUES
|
||||
(1, 1, 2);
|
||||
|
||||
-- Read Recommendations (SELECT)
|
||||
SELECT
|
||||
r.*,
|
||||
p.Name as RecommendedProductName,
|
||||
p.Price,
|
||||
p.Description
|
||||
FROM
|
||||
Recommendation r
|
||||
JOIN Product p ON r.RecommendedProductID = p.ProductID
|
||||
WHERE
|
||||
r.UserID = 1;
|
||||
|
||||
-- Authentication Operations
|
||||
-- Create verification code
|
||||
INSERT INTO
|
||||
AuthVerification (Email, VerificationCode)
|
||||
VALUES
|
||||
('new_user@example.com', '123456');
|
||||
|
||||
-- Update authentication status
|
||||
UPDATE AuthVerification
|
||||
SET
|
||||
Authenticated = TRUE
|
||||
WHERE
|
||||
Email = 'new_user@example.com'
|
||||
AND VerificationCode = '123456';
|
||||
|
||||
-- Get top-selling products
|
||||
SELECT
|
||||
p.ProductID,
|
||||
p.Name,
|
||||
COUNT(t.TransactionID) as SalesCount,
|
||||
SUM(p.Price) as TotalRevenue
|
||||
FROM
|
||||
Product p
|
||||
JOIN Transaction t ON p.ProductID = t.ProductID
|
||||
WHERE
|
||||
t.PaymentStatus = 'Completed'
|
||||
GROUP BY
|
||||
p.ProductID,
|
||||
p.Name
|
||||
ORDER BY
|
||||
SalesCount DESC
|
||||
LIMIT
|
||||
10;
|
||||
|
||||
-- Get highest-rated products
|
||||
SELECT
|
||||
p.ProductID,
|
||||
p.Name,
|
||||
AVG(r.Rating) as AverageRating,
|
||||
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;
|
||||
-- -- Insert sample categories
|
||||
-- INSERT INTO
|
||||
-- Category (CategoryID, Name)
|
||||
-- VALUES
|
||||
-- (1, 'Electronics'),
|
||||
-- (2, 'Clothing'),
|
||||
-- (3, 'Books'),
|
||||
-- (4, 'Home & Garden'),
|
||||
-- (5, 'Sports & Outdoors');
|
||||
-- -- -- USER CRUD OPERATIONS
|
||||
-- -- -- Create User (INSERT)
|
||||
-- -- INSERT INTO
|
||||
-- -- User (Name, Email, UCID, Password, Phone, Address)
|
||||
-- -- VALUES
|
||||
-- -- (
|
||||
-- -- 'John Doe',
|
||||
-- -- 'john@example.com',
|
||||
-- -- 'UC123456',
|
||||
-- -- 'hashed_password_here',
|
||||
-- -- '555-123-4567',
|
||||
-- -- '123 Main St'
|
||||
-- -- );
|
||||
-- -- -- Set user role
|
||||
-- -- INSERT INTO
|
||||
-- -- UserRole (UserID, Client, Admin)
|
||||
-- -- VALUES
|
||||
-- -- (LAST_INSERT_ID (), TRUE, FALSE);
|
||||
-- -- -- Read User (SELECT)
|
||||
-- -- SELECT
|
||||
-- -- u.*,
|
||||
-- -- ur.Client,
|
||||
-- -- ur.Admin
|
||||
-- -- FROM
|
||||
-- -- User u
|
||||
-- -- JOIN UserRole ur ON u.UserID = ur.UserID
|
||||
-- -- WHERE
|
||||
-- -- u.UserID = 1;
|
||||
-- -- -- Update User (UPDATE)
|
||||
-- -- UPDATE User
|
||||
-- -- SET
|
||||
-- -- Name = 'John Smith',
|
||||
-- -- Phone = '555-987-6543',
|
||||
-- -- Address = '456 Elm St'
|
||||
-- -- WHERE
|
||||
-- -- UserID = 1;
|
||||
-- -- -- Update User Role
|
||||
-- -- UPDATE UserRole
|
||||
-- -- SET
|
||||
-- -- Admin = TRUE
|
||||
-- -- WHERE
|
||||
-- -- UserID = 1;
|
||||
-- -- -- PRODUCT CRUD OPERATIONS
|
||||
-- -- -- Create Product (INSERT)
|
||||
-- -- INSERT INTO
|
||||
-- -- Product (
|
||||
-- -- ProductID,
|
||||
-- -- Name,
|
||||
-- -- Price,
|
||||
-- -- StockQuantity,
|
||||
-- -- UserID,
|
||||
-- -- Description,
|
||||
-- -- CategoryID
|
||||
-- -- )
|
||||
-- -- VALUES
|
||||
-- -- (
|
||||
-- -- 1,
|
||||
-- -- 'Smartphone',
|
||||
-- -- 599.99,
|
||||
-- -- 50,
|
||||
-- -- 1,
|
||||
-- -- 'Latest model smartphone with amazing features',
|
||||
-- -- 1
|
||||
-- -- );
|
||||
-- -- -- Add product images with the placeholder URL
|
||||
-- -- INSERT INTO
|
||||
-- -- Image_URL (URL, ProductID)
|
||||
-- -- VALUES
|
||||
-- -- ('https://picsum.photos/id/237/200/300', 1),
|
||||
-- -- ('https://picsum.photos/id/237/200/300', 1);
|
||||
-- -- -- Create another product for recommendations
|
||||
-- -- INSERT INTO
|
||||
-- -- Product (
|
||||
-- -- ProductID,
|
||||
-- -- Name,
|
||||
-- -- Price,
|
||||
-- -- StockQuantity,
|
||||
-- -- UserID,
|
||||
-- -- Description,
|
||||
-- -- CategoryID
|
||||
-- -- )
|
||||
-- -- VALUES
|
||||
-- -- (
|
||||
-- -- 2,
|
||||
-- -- 'Tablet',
|
||||
-- -- 799.99,
|
||||
-- -- 30,
|
||||
-- -- 1,
|
||||
-- -- 'High-performance tablet',
|
||||
-- -- 1
|
||||
-- -- );
|
||||
-- -- -- Add placeholder images for the second product
|
||||
-- -- INSERT INTO
|
||||
-- -- Image_URL (URL, ProductID)
|
||||
-- -- VALUES
|
||||
-- -- ('https://picsum.photos/id/237/200/300', 2),
|
||||
-- -- ('https://picsum.photos/id/237/200/300', 2);
|
||||
-- -- -- Read Product (SELECT)
|
||||
-- -- SELECT
|
||||
-- -- p.*,
|
||||
-- -- c.Name as CategoryName,
|
||||
-- -- u.Name as SellerName,
|
||||
-- -- i.URL as ImageURL
|
||||
-- -- FROM
|
||||
-- -- Product p
|
||||
-- -- JOIN Category c ON p.CategoryID = c.CategoryID
|
||||
-- -- JOIN User u ON p.UserID = u.UserID
|
||||
-- -- LEFT JOIN Image_URL i ON p.ProductID = i.ProductID
|
||||
-- -- WHERE
|
||||
-- -- p.ProductID = 1;
|
||||
-- -- -- Update Product (UPDATE)
|
||||
-- -- UPDATE Product
|
||||
-- -- SET
|
||||
-- -- Name = 'Premium Smartphone',
|
||||
-- -- Price = 649.99,
|
||||
-- -- StockQuantity = 45,
|
||||
-- -- Description = 'Updated description with new features'
|
||||
-- -- WHERE
|
||||
-- -- ProductID = 1;
|
||||
-- -- -- CATEGORY CRUD OPERATIONS
|
||||
-- -- -- Create Category (INSERT)
|
||||
-- -- INSERT INTO
|
||||
-- -- Category (CategoryID, Name)
|
||||
-- -- VALUES
|
||||
-- -- (6, 'Toys & Games');
|
||||
-- -- -- Read Category (SELECT)
|
||||
-- -- SELECT
|
||||
-- -- *
|
||||
-- -- FROM
|
||||
-- -- Category
|
||||
-- -- WHERE
|
||||
-- -- CategoryID = 6;
|
||||
-- -- -- Update Category (UPDATE)
|
||||
-- -- UPDATE Category
|
||||
-- -- SET
|
||||
-- -- Name = 'Toys & Children''s Games'
|
||||
-- -- WHERE
|
||||
-- -- CategoryID = 6;
|
||||
-- -- -- REVIEW OPERATIONS
|
||||
-- -- INSERT INTO
|
||||
-- -- Review (ReviewID, UserID, ProductID, Comment, Rating)
|
||||
-- -- VALUES
|
||||
-- -- (
|
||||
-- -- 1,
|
||||
-- -- 1,
|
||||
-- -- 1,
|
||||
-- -- 'Great product, very satisfied with the purchase!',
|
||||
-- -- 5
|
||||
-- -- );
|
||||
-- -- -- TRANSACTION OPERATIONS
|
||||
-- -- INSERT INTO
|
||||
-- -- Transaction (TransactionID, UserID, ProductID, PaymentStatus)
|
||||
-- -- VALUES
|
||||
-- -- (1, 1, 1, 'Completed');
|
||||
-- -- -- HISTORY OPERATIONS
|
||||
-- -- INSERT INTO
|
||||
-- -- History (HistoryID, UserID, ProductID)
|
||||
-- -- VALUES
|
||||
-- -- (1, 1, 1);
|
||||
-- -- -- Read History (SELECT)
|
||||
-- -- SELECT
|
||||
-- -- h.*,
|
||||
-- -- p.Name as ProductName
|
||||
-- -- FROM
|
||||
-- -- History h
|
||||
-- -- JOIN Product p ON h.ProductID = p.ProductID
|
||||
-- -- WHERE
|
||||
-- -- h.UserID = 1
|
||||
-- -- ORDER BY
|
||||
-- -- h.Date DESC;
|
||||
-- -- -- FAVORITES OPERATIONS
|
||||
-- -- INSERT INTO
|
||||
-- -- Favorites (UserID, ProductID)
|
||||
-- -- VALUES
|
||||
-- -- (1, 1);
|
||||
-- -- -- Read Favorites (SELECT)
|
||||
-- -- SELECT
|
||||
-- -- f.*,
|
||||
-- -- p.Name as ProductName,
|
||||
-- -- p.Price
|
||||
-- -- FROM
|
||||
-- -- Favorites f
|
||||
-- -- JOIN Product p ON f.ProductID = p.ProductID
|
||||
-- -- WHERE
|
||||
-- -- f.UserID = 1;
|
||||
-- -- -- RECOMMENDATION OPERATIONS
|
||||
-- -- INSERT INTO
|
||||
-- -- Recommendation (RecommendationID_PK, UserID, RecommendedProductID)
|
||||
-- -- VALUES
|
||||
-- -- (1, 1, 2);
|
||||
-- -- -- Read Recommendations (SELECT)
|
||||
-- -- SELECT
|
||||
-- -- r.*,
|
||||
-- -- p.Name as RecommendedProductName,
|
||||
-- -- p.Price,
|
||||
-- -- p.Description
|
||||
-- -- FROM
|
||||
-- -- Recommendation r
|
||||
-- -- JOIN Product p ON r.RecommendedProductID = p.ProductID
|
||||
-- -- WHERE
|
||||
-- -- r.UserID = 1;
|
||||
-- -- -- Authentication Operations
|
||||
-- -- -- Create verification code
|
||||
-- -- INSERT INTO
|
||||
-- -- AuthVerification (Email, VerificationCode)
|
||||
-- -- VALUES
|
||||
-- -- ('new_user@example.com', '123456');
|
||||
-- -- -- Update authentication status
|
||||
-- -- UPDATE AuthVerification
|
||||
-- -- SET
|
||||
-- -- Authenticated = TRUE
|
||||
-- -- WHERE
|
||||
-- -- Email = 'new_user@example.com'
|
||||
-- -- AND VerificationCode = '123456';
|
||||
-- -- -- Get top-selling products
|
||||
-- -- SELECT
|
||||
-- -- p.ProductID,
|
||||
-- -- p.Name,
|
||||
-- -- COUNT(t.TransactionID) as SalesCount,
|
||||
-- -- SUM(p.Price) as TotalRevenue
|
||||
-- -- FROM
|
||||
-- -- Product p
|
||||
-- -- JOIN Transaction t ON p.ProductID = t.ProductID
|
||||
-- -- WHERE
|
||||
-- -- t.PaymentStatus = 'Completed'
|
||||
-- -- GROUP BY
|
||||
-- -- p.ProductID,
|
||||
-- -- p.Name
|
||||
-- -- ORDER BY
|
||||
-- -- SalesCount DESC
|
||||
-- -- LIMIT
|
||||
-- -- 10;
|
||||
-- -- -- Get highest-rated products
|
||||
-- -- SELECT
|
||||
-- -- p.ProductID,
|
||||
-- -- p.Name,
|
||||
-- -- AVG(r.Rating) as AverageRating,
|
||||
-- -- 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
3
SQL_code/init-db.py
Normal 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")
|
||||
@@ -13,13 +13,13 @@ exports.sendVerificationCode = async (req, res) => {
|
||||
// Generate a random 6-digit code
|
||||
const verificationCode = crypto.randomInt(100000, 999999).toString();
|
||||
console.log(
|
||||
`Generated verification code for ${email}: ${verificationCode}`
|
||||
`Generated verification code for ${email}: ${verificationCode}`,
|
||||
);
|
||||
|
||||
// Check if email already exists in verification table
|
||||
const [results, fields] = await db.execute(
|
||||
"SELECT * FROM AuthVerification WHERE Email = ?",
|
||||
[email]
|
||||
[email],
|
||||
);
|
||||
|
||||
if (results.length > 0) {
|
||||
@@ -27,7 +27,7 @@ exports.sendVerificationCode = async (req, res) => {
|
||||
const [result] = await db.execute(
|
||||
`UPDATE AuthVerification SET VerificationCode = ?, Authenticated = FALSE, Date = CURRENT_TIMESTAMP
|
||||
WHERE Email = ?`,
|
||||
[verificationCode, email]
|
||||
[verificationCode, email],
|
||||
);
|
||||
|
||||
// Send email and respond
|
||||
@@ -37,7 +37,7 @@ exports.sendVerificationCode = async (req, res) => {
|
||||
// Insert new record
|
||||
const [result] = await db.execute(
|
||||
"INSERT INTO AuthVerification (Email, VerificationCode, Authenticated) VALUES (?, ?, FALSE)",
|
||||
[email, verificationCode]
|
||||
[email, verificationCode],
|
||||
);
|
||||
// Send email and respond
|
||||
await sendVerificationEmail(email, verificationCode);
|
||||
@@ -62,7 +62,7 @@ exports.verifyCode = async (req, res) => {
|
||||
// Check verification code
|
||||
const [results, fields] = await db.execute(
|
||||
"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) {
|
||||
console.log(`Invalid or expired verification code for email ${email}`);
|
||||
@@ -76,7 +76,7 @@ exports.verifyCode = async (req, res) => {
|
||||
// Mark as authenticated
|
||||
const [result] = await db.execute(
|
||||
"UPDATE AuthVerification SET Authenticated = TRUE WHERE Email = ?",
|
||||
[email]
|
||||
[email],
|
||||
);
|
||||
res.json({
|
||||
success: true,
|
||||
@@ -95,7 +95,7 @@ exports.completeSignUp = async (req, res) => {
|
||||
try {
|
||||
const [results, fields] = await db.execute(
|
||||
`SELECT * FROM AuthVerification WHERE Email = ? AND Authenticated = 1;`,
|
||||
[data.email]
|
||||
[data.email],
|
||||
);
|
||||
|
||||
if (results.length === 0) {
|
||||
@@ -105,7 +105,7 @@ exports.completeSignUp = async (req, res) => {
|
||||
// Create the user
|
||||
const [createResult] = await db.execute(
|
||||
`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
|
||||
@@ -113,12 +113,12 @@ exports.completeSignUp = async (req, res) => {
|
||||
`INSERT INTO UserRole (UserID, Client, Admin)
|
||||
VALUES (LAST_INSERT_ID(), ${data.client || true}, ${
|
||||
data.admin || false
|
||||
})`
|
||||
})`,
|
||||
);
|
||||
|
||||
// Delete verification record
|
||||
const [deleteResult] = await db.execute(
|
||||
`DELETE FROM AuthVerification WHERE Email = '${data.email}'`
|
||||
`DELETE FROM AuthVerification WHERE Email = '${data.email}'`,
|
||||
);
|
||||
|
||||
res.json({
|
||||
@@ -194,37 +194,47 @@ exports.findUserByEmail = 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) {
|
||||
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 values = [];
|
||||
|
||||
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} = ?`);
|
||||
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);
|
||||
|
||||
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);
|
||||
|
||||
if (updateResult.affectedRows === 0) {
|
||||
return res.status(404).json({ error: "User not found" });
|
||||
}
|
||||
|
||||
res.json({ success: true, message: "User updated successfully" });
|
||||
} catch (error) {
|
||||
console.error("Error updating user:", error);
|
||||
@@ -243,7 +253,7 @@ exports.deleteUser = async (req, res) => {
|
||||
// Delete from UserRole first (assuming foreign key constraint)
|
||||
const [result1] = await db.execute(
|
||||
"DELETE FROM UserRole WHERE UserID = ?",
|
||||
[userId]
|
||||
[userId],
|
||||
);
|
||||
|
||||
// Then delete from User table
|
||||
|
||||
@@ -2,11 +2,10 @@ const mysql = require("mysql2");
|
||||
|
||||
//Create a pool of connections to allow multiple query happen at the same time
|
||||
const pool = mysql.createPool({
|
||||
host: "marketplace-db.cpkkqmq065sx.ca-central-1.rds.amazonaws.com",
|
||||
user: "admin",
|
||||
password: "qizsYh-movpub-wuhdo2",
|
||||
database: "Marketplace",
|
||||
port: "3306",
|
||||
host: "localhost",
|
||||
user: "root",
|
||||
database: "marketplace",
|
||||
password: "12345678",
|
||||
});
|
||||
|
||||
//Export a promise for promise-based query
|
||||
|
||||
@@ -43,7 +43,7 @@ const Settings = () => {
|
||||
body: JSON.stringify({
|
||||
email: storedUser.email,
|
||||
}),
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const data = await response.json();
|
||||
@@ -53,7 +53,7 @@ const Settings = () => {
|
||||
// Update state with fetched data
|
||||
setUserData((prevData) => ({
|
||||
...prevData,
|
||||
userId: data.userId || storedUser.id || "", // Try both sources
|
||||
userId: storedUser.ID, // Try both sources
|
||||
name: data.name || storedUser.name || "",
|
||||
email: data.email || storedUser.email || "",
|
||||
UCID: data.UCID || storedUser.UCID || "",
|
||||
@@ -70,7 +70,7 @@ const Settings = () => {
|
||||
} catch (error) {
|
||||
console.error("Error fetching user data:", error);
|
||||
setError(
|
||||
error.message || "An error occurred while loading your profile"
|
||||
error.message || "An error occurred while loading your profile",
|
||||
);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
@@ -88,27 +88,39 @@ const Settings = () => {
|
||||
}));
|
||||
};
|
||||
|
||||
const handleProfileUpdate = async (e) => {
|
||||
e.preventDefault();
|
||||
const handleUpdateProfile = async () => {
|
||||
try {
|
||||
// TODO: Implement the actual update API call
|
||||
console.log("Profile updated:", userData);
|
||||
// Ensure userId is present
|
||||
if (!userData.userId) {
|
||||
throw new Error("User ID is missing. Unable to update profile.");
|
||||
}
|
||||
|
||||
// Update localStorage with new user data
|
||||
const storedUser = JSON.parse(localStorage.getItem("user"));
|
||||
const updatedUser = {
|
||||
...storedUser,
|
||||
name: userData.name,
|
||||
phone: userData.phone,
|
||||
UCID: userData.UCID,
|
||||
address: userData.address,
|
||||
};
|
||||
localStorage.setItem("user", JSON.stringify(updatedUser));
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
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!");
|
||||
} catch (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 () => {
|
||||
if (
|
||||
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 {
|
||||
@@ -232,7 +244,7 @@ const Settings = () => {
|
||||
</div>
|
||||
|
||||
<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>
|
||||
<label
|
||||
|
||||
Reference in New Issue
Block a user