diff --git a/index.js b/index.js index 3537a08d1370f3e1f735dc8a656b2d6d0d1613fc..bb3aab7a4ae29bf1455a327ca7c62f5016678c3b 100644 --- a/index.js +++ b/index.js @@ -377,34 +377,35 @@ app.post("/confirm-loan", (req, res) => { // Route สำหรับยืนยันการยืม -app.post('/submit-loan', (req, res) => { - const user_id = req.user.id; // สมมติว่าผู้ใช้ล็อกอินแล้ว - const equipment_id = req.body.equipment_id; - const quantity = req.body.quantity; +app.post('/submit-loan', async (req, res) => { + try { + const user_id = req.user.id; // สมมติว่าผู้ใช้ล็อกอินแล้ว + const { equipment_id, quantity } = req.body; - // ตรวจสอบว่าอุปกรณ์มีจำนวนเพียงพอหรือไม่ - db.query('SELECT * FROM equipment WHERE id = ?', [equipment_id], (err, result) => { - if (err) throw err; - const equipment = result[0]; + // ตรวจสอบว่าอุปกรณ์มีจำนวนเพียงพอหรือไม่ + const [equipment] = await db.promise().query('SELECT * FROM equipment WHERE id = ?', [equipment_id]); - if (equipment.quantity >= quantity) { + if (equipment && equipment.quantity >= quantity) { // บันทึกข้อมูลการยืมลงในตาราง loans - db.query('INSERT INTO loans (user_id, equipment_id, quantity, status) VALUES (?, ?, ?, "pending")', [user_id, equipment_id, quantity], (err) => { - if (err) throw err; - // ปรับจำนวนอุปกรณ์ในตาราง equipment - db.query('UPDATE equipment SET quantity = quantity - ? WHERE id = ?', [quantity, equipment_id], (err) => { - if (err) throw err; - res.redirect('/loans'); // เปลี่ยนเส้นทางไปยังหน้า "รวมการยืมอุปกรณ์" - }); - }); + await db.promise().query('INSERT INTO loans (user_id, equipment_id, quantity, status) VALUES (?, ?, ?, "pending")', [user_id, equipment_id, quantity]); + + // ปรับจำนวนอุปกรณ์ในตาราง equipment + await db.promise().query('UPDATE equipment SET quantity = quantity - ? WHERE id = ?', [quantity, equipment_id]); + + // เปลี่ยนเส้นทางไปยังหน้า "รวมการยืมอุปกรณ์" + res.redirect('/loans'); } else { res.send('จำนวนอุปกรณ์ไม่เพียงพอ'); } - }); + } catch (err) { + console.error('Error occurred:', err); + res.status(500).send('เกิดข้อผิดพลาดในขณะดำเนินการ'); + } }); + // การยกเลิกการยืม (Backend) app.post("/cancel-loan", (req, res) => { const loanId = req.body.loan_id;