Gitlab@Informatics

Skip to content
Snippets Groups Projects
Commit 78405a3d authored by 65160270's avatar 65160270
Browse files

update-cart

parent e90ebba2
Branches
No related tags found
No related merge requests found
......@@ -3,13 +3,13 @@ const router = express.Router();
const pool = require('../config/database');
// ฟังก์ชันช่วยคำนวณราคารวม
async function calculateTotal(userId) {
async function calculateTotal(sessionId) {
const [cartItems] = await pool.query(
`SELECT cart_items.*, products.price
FROM cart_items
JOIN products ON cart_items.product_id = products.id
WHERE cart_items.user_id = ?`,
[userId]
WHERE cart_items.session_id = ?`,
[sessionId]
);
return cartItems.reduce((sum, item) => sum + (item.price * item.quantity), 0);
}
......@@ -34,14 +34,7 @@ router.get('/', async (req, res) => {
// เพิ่มสินค้าลงตะกร้า
router.post('/add', async (req, res) => {
console.log("Session User:", req.session.user); // ดูค่า session
console.log("Received Data:", req.body); // ดูค่าที่ส่งมา
const { productId, quantity } = req.body;
if (!req.session.user) {
return res.status(401).send('Unauthorized');
}
try {
const [[product]] = await pool.query(
'SELECT stock FROM products WHERE id = ?', [productId]
......@@ -55,13 +48,14 @@ router.post('/add', async (req, res) => {
return res.status(400).send('สินค้ามีจำนวนไม่เพียงพอ');
}
// ตรวจสอบว่ามีสินค้าในตะกร้าอยู่แล้วหรือไม่
// ตรวจสอบว่าสินค้านี้มีอยู่ในตะกร้าหรือยัง
const [[existingItem]] = await pool.query(
'SELECT id, quantity FROM cart_items WHERE user_id = ? AND product_id = ?',
[req.session.user.id, productId]
'SELECT id, quantity FROM cart_items WHERE session_id = ? AND product_id = ?',
[req.session.id, productId]
);
if (existingItem) {
// อัปเดตจำนวนสินค้า
const newQuantity = existingItem.quantity + parseInt(quantity);
if (newQuantity > product.stock) {
return res.status(400).send('สินค้ามีจำนวนไม่เพียงพอ');
......@@ -71,16 +65,17 @@ router.post('/add', async (req, res) => {
[newQuantity, existingItem.id]
);
} else {
// เพิ่มสินค้าใหม่
await pool.query(
'INSERT INTO cart_items (user_id, product_id, quantity) VALUES (?, ?, ?)',
[req.session.user.id, productId, parseInt(quantity)]
'INSERT INTO cart_items (session_id, product_id, quantity) VALUES (?, ?, ?)',
[req.session.id, productId, parseInt(quantity)]
);
}
res.redirect('/cart');
} catch (error) {
console.error("Error adding to cart:", error);
res.status(500).send('Error adding to cart.');
console.error(error);
res.status(500).send('Error adding to cart');
}
});
......@@ -122,6 +117,7 @@ router.post('/update', async (req, res) => {
}
});
// ลบสินค้าออกจากตะกร้า
router.post('/remove', async (req, res) => {
const { cartItemId } = req.body;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment