From 9b9f1feede42949c04cc8787f98fe203a87b7a3f Mon Sep 17 00:00:00 2001 From: 65160381 <65160381@go.buu.ac.th> Date: Tue, 25 Mar 2025 01:57:24 +0700 Subject: [PATCH] 8.4 --- app.js | 70 +++++++++++++++++++++++++++++++++++++++ public/cart.html | 81 +++++++++++++++++++++++++++++++++++++++++++++ public/profile.html | 54 ++++++++++++++++++++++++++++++ 3 files changed, 205 insertions(+) create mode 100644 public/cart.html create mode 100644 public/profile.html diff --git a/app.js b/app.js index 09fcbf0..10703b8 100644 --- a/app.js +++ b/app.js @@ -169,6 +169,76 @@ app.post('/login', async (req, res) => { } }); + // เพิ่มสินค้าใหม่ + app.get('/api/user/products', async (req, res) => { + if (!req.session.user) { + return res.status(401).send('User not logged in'); + } + + const userId = req.session.user.id; // ใช้ user_id จาก session + try { + const connection = await pool.getConnection(); + const [products] = await connection.query( + 'SELECT * FROM products WHERE user_id = ?', + [userId] + ); + connection.release(); + res.json(products); + } catch (err) { + console.error('Error fetching user products:', err); + res.status(500).send('Error fetching user products'); + } +}); + +// เพิ่มสินค้าใหม่ +app.post('/api/products', (req, res) => { + if (!req.session.user) { + return res.status(401).send('User not logged in'); + } + + const { productName, productPrice, productImg } = req.body; + const userId = req.session.user.id; // user_id จาก session + + pool.query(` + INSERT INTO products (product_name, product_price, product_img, user_id) + VALUES (?, ?, ?, ?) + `, [productName, productPrice, productImg, userId], (err, results) => { + if (err) { + return res.status(500).send('Error adding product'); + } + res.send('Product added successfully'); + }); +}); + + +// ดึงสินค้าของผู้ใช้ +app.get('/api/user/products', (req, res) => { + if (!req.session.user) { + return res.status(401).send('User not logged in'); + } + + const userId = req.session.user.id; + + pool.query(` + SELECT * FROM products WHERE user_id = ? + `, [userId], (err, results) => { + if (err) { + return res.status(500).send('Error fetching user products'); + } + res.json(results); + }); +}); + +// ดึงสินค้าทั้งหมด +app.get('/api/products', (req, res) => { + pool.query('SELECT * FROM products', (err, results) => { + if (err) { + return res.status(500).send('Error fetching products'); + } + res.json(results); + }); +}); + app.use(express.json()); // สำหรับการ parse ข้อมูลแบบ JSON app.use(express.urlencoded({ extended: true })); // สำหรับการ parse ข้อมูลแบบ URL-encoded diff --git a/public/cart.html b/public/cart.html new file mode 100644 index 0000000..901828f --- /dev/null +++ b/public/cart.html @@ -0,0 +1,81 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>Cart ASA</title> + <link rel="stylesheet" href="styles/cart.css"> +</head> +<body> + <header> + <h1>ASA Cart</h1> + </header> + + <div class="cart-items" id="cart-items"> + <!-- Cart items will be dynamically loaded here --> + </div> + + <footer> + <p>© 2025 ASA</p> + <div class="checkout" onclick="goToCheckout()">Checkout</div> + </footer> + + <script> + // Load cart items from the API + async function loadCart() { + try { + const response = await fetch('/api/cart'); + const cart = await response.json(); + const cartItemsContainer = document.getElementById('cart-items'); + cartItemsContainer.innerHTML = ''; + + if (cart.length === 0) { + cartItemsContainer.innerHTML = '<p>Your cart is empty!</p>'; + } + + cart.forEach(item => { + const itemDiv = document.createElement('div'); + itemDiv.classList.add('cart-item'); + itemDiv.innerHTML = ` + <img src="${item.product_img}" alt="${item.product_name}"> + <div> + <h3>${item.product_name}</h3> + <p>Price: $${item.product_price}</p> + <p>Total Price: $<span id="total-price-${item.product_id}">${item.total_price}</span></p> + </div> + <div> + <input type="number" value="${item.quantity}" min="1" onchange="updateQuantity(${item.product_id}, this.value)"> + <button onclick="removeFromCart(${item.product_id})">Remove</button> + </div> + `; + cartItemsContainer.appendChild(itemDiv); + }); + } catch (error) { + console.error('Error loading cart items:', error); + } + } + + async function updateQuantity(productId, newQuantity) { + await fetch(`/api/cart/${productId}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ quantity: newQuantity }) + }); + + loadCart(); // Reload the cart after updating + } + + async function removeFromCart(productId) { + await fetch(`/api/cart/${productId}`, { method: 'DELETE' }); + loadCart(); // Reload the cart after removal + } + + function goToCheckout() { + window.location.href = 'checkout.html'; + } + + // Load cart items when page loads + loadCart(); + </script> +</body> +</html> diff --git a/public/profile.html b/public/profile.html new file mode 100644 index 0000000..4848fd0 --- /dev/null +++ b/public/profile.html @@ -0,0 +1,54 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>Your Products</title> + <link rel="stylesheet" href="styles/home.css"> +</head> +<body> + <header> + <h1>Your Products</h1> + </header> + + <div class="products" id="user-products"> + <!-- User's products will be dynamically loaded here --> + </div> + + <footer> + <p>© 2025 ASA</p> + </footer> + + <script> + // Function to load products posted by the logged-in user + async function loadUserProducts() { + try { + const response = await fetch('/api/user/products'); + const products = await response.json(); + const productContainer = document.getElementById('user-products'); + productContainer.innerHTML = ''; // Clear the container + + if (products.length === 0) { + productContainer.innerHTML = '<p>You have no products listed.</p>'; + } + + products.forEach(product => { + const productDiv = document.createElement('div'); + productDiv.classList.add('product'); + productDiv.innerHTML = ` + <img src="${product.product_img}" alt="${product.product_name}"> + <h3>${product.product_name}</h3> + <p>Price: $${product.product_price}</p> + `; + productContainer.appendChild(productDiv); + }); + } catch (error) { + console.error('Error loading user products:', error); + } + } + + // Call function to load user products when page loads + loadUserProducts(); + </script> +</body> +</html> -- GitLab