From e012cb20748dcbc07b98a5f9aaa5d167d1724e75 Mon Sep 17 00:00:00 2001
From: 65160024 <65160024@go.buu.ac.th>
Date: Sat, 29 Mar 2025 02:42:45 +0000
Subject: [PATCH] update

---
 index.js               | 55 +++++++++++++++++++++++++++---------------
 views/confirm-loan.ejs | 23 +++++++++---------
 2 files changed, 46 insertions(+), 32 deletions(-)

diff --git a/index.js b/index.js
index cc61c83..17809a6 100644
--- a/index.js
+++ b/index.js
@@ -361,30 +361,45 @@ app.post("/confirm-loan", (req, res) => {
 
 
 // Route สำหรับยืนยันการยืม
-app.post('/submit-loan', async (req, res) => {
-  try {
-      const user_id = req.user.id;  // สมมติว่าผู้ใช้ล็อกอินแล้ว
-      const { equipment_id, quantity } = req.body;
-
-      // ตรวจสอบว่าอุปกรณ์มีจำนวนเพียงพอหรือไม่
-      const [equipment] = await db.promise().query('SELECT * FROM equipment WHERE id = ?', [equipment_id]);
+app.post('/submit-loan', (req, res) => {
+  const { equipment_id, quantity } = req.body;
+  const user_id = req.session.user.id; // ใช้ session ของผู้ใช้ที่ล็อกอิน
 
-      if (equipment && equipment.quantity >= quantity) {
-          // บันทึกข้อมูลการยืมลงในตาราง loans
-          await db.promise().query('INSERT INTO loans (user_id, equipment_id, quantity, status) VALUES (?, ?, ?, "pending")', [user_id, equipment_id, quantity]);
+  if (!equipment_id || !quantity || !user_id) {
+      return res.status(400).json({ message: 'ข้อมูลไม่ครบถ้วน' });
+  }
 
-          // ปรับจำนวนอุปกรณ์ในตาราง equipment
-          await db.promise().query('UPDATE equipment SET quantity = quantity - ? WHERE id = ?', [quantity, equipment_id]);
+  // ตรวจสอบจำนวนอุปกรณ์คงเหลือ
+  db.query('SELECT quantity FROM equipment WHERE id = ?', [equipment_id], (err, results) => {
+      if (err) {
+          console.error('เกิดข้อผิดพลาด:', err);
+          return res.status(500).json({ message: 'เกิดข้อผิดพลาดในการดึงข้อมูล' });
+      }
 
-          // เปลี่ยนเส้นทางไปยังหน้า "รวมการยืมอุปกรณ์"
-          res.redirect('/loans');
-      } else {
-          res.send('จำนวนอุปกรณ์ไม่เพียงพอ');
+      if (results.length === 0 || results[0].quantity < quantity) {
+          return res.status(400).json({ message: 'จำนวนอุปกรณ์ไม่เพียงพอ' });
       }
-  } catch (err) {
-      console.error('Error occurred:', err);
-      res.status(500).send('เกิดข้อผิดพลาดในขณะดำเนินการ');
-  }
+
+      // บันทึกข้อมูลการยืม
+      db.query('INSERT INTO loans (user_id, equipment_id, quantity, status) VALUES (?, ?, ?, ?)', 
+      [user_id, equipment_id, quantity, 'borrowed'], (err) => {
+          if (err) {
+              console.error('เกิดข้อผิดพลาดในการบันทึกข้อมูลการยืม:', err);
+              return res.status(500).json({ message: 'เกิดข้อผิดพลาดในการยืมอุปกรณ์' });
+          }
+
+          // อัปเดตจำนวนอุปกรณ์
+          db.query('UPDATE equipment SET quantity = quantity - ? WHERE id = ?', 
+          [quantity, equipment_id], (err) => {
+              if (err) {
+                  console.error('เกิดข้อผิดพลาดในการอัปเดตอุปกรณ์:', err);
+                  return res.status(500).json({ message: 'เกิดข้อผิดพลาดในการอัปเดตข้อมูล' });
+              }
+
+              res.json({ message: 'ยืมอุปกรณ์สำเร็จ' });
+          });
+      });
+  });
 });
 
 
diff --git a/views/confirm-loan.ejs b/views/confirm-loan.ejs
index 29357c5..7811148 100644
--- a/views/confirm-loan.ejs
+++ b/views/confirm-loan.ejs
@@ -64,34 +64,33 @@
 
                 <script>
                     // เมื่อกดปุ่ม "ยืนยันการยืม" ให้เปลี่ยนเส้นทางไปยังหน้า /loans
-                    document.getElementById('confirmButton').addEventListener('click', function () {
-                        // ส่งข้อมูลยืมไปยังเซิร์ฟเวอร์ (ในกรณีที่ต้องการให้มีการบันทึกข้อมูลก่อน)
+                    document.getElementById('confirmButton').addEventListener('click', function (event) {
+                        event.preventDefault(); // ป้องกันหน้ารีเฟรช
+
                         const equipment_id = "<%= equipment.id %>";
                         const quantity = "<%= quantity %>";
 
                         fetch('/submit-loan', {
                             method: 'POST',
                             headers: {
-                                'Content-Type': 'application/json',  // ตั้งค่า header ให้เป็น application/json
+                                'Content-Type': 'application/json',
                             },
-                            body: JSON.stringify({
-                                equipment_id: equipment_id,
-                                quantity: quantity
-                            })
+                            body: JSON.stringify({ equipment_id, quantity }),
                         })
-                            .then(response => {
-                                if (response.ok) {
-                                    // หลังจากยืนยันเสร็จแล้วเปลี่ยนเส้นทางไปที่ /loans
+                            .then(response => response.json())
+                            .then(data => {
+                                if (data.message === 'ยืมอุปกรณ์สำเร็จ') {
+                                    alert('ยืมอุปกรณ์สำเร็จ!');
                                     window.location.href = '/loans';
                                 } else {
-                                    alert('การยืมอุปกรณ์ล้มเหลว');
+                                    alert(data.message);
                                 }
                             })
                             .catch(error => {
                                 alert('เกิดข้อผิดพลาด: ' + error);
                             });
-
                     });
+
                 </script>
 
 </body>
-- 
GitLab