From 4dc6eac6130d7f28946428fb239d4eedee870a07 Mon Sep 17 00:00:00 2001 From: 65160024 <65160024@go.buu.ac.th> Date: Tue, 25 Mar 2025 05:57:50 +0000 Subject: [PATCH] update index.js --- index.js | 42 +++++++++++++++++++++++++----------------- views/index.ejs | 11 +++++------ 2 files changed, 30 insertions(+), 23 deletions(-) diff --git a/index.js b/index.js index cc61c83..0485375 100644 --- a/index.js +++ b/index.js @@ -337,26 +337,34 @@ app.post("/approve-loan", isAuthenticated, isAdmin, (req, res) => { // Route แสดงหน้าการยืนยันการยืม -app.post("/confirm-loan", (req, res) => { - if (!req.user) { - return res.redirect("/login"); // หากไม่ได้ล็อกอิน ให้กลับไปที่หน้า login - } +router.post('/confirm-loan', (req, res) => { + const { equipment_id, quantity } = req.body; - const equipment_id = req.body.equipment_id; - const quantity = req.body.quantity; + // คำสั่ง SQL เพื่อลงข้อมูลการยืม + const query = ` + INSERT INTO loans (equipment_id, quantity, user_id, loan_date) + VALUES (?, ?, ?, NOW())`; - // ดึงข้อมูลอุปกรณ์จากฐานข้อมูล - db.query( - "SELECT * FROM equipment WHERE id = ?", - [equipment_id], - (err, result) => { - if (err) throw err; - const equipment = result[0]; + // รับ user_id จาก session หรือจาก JWT token (ถ้าใช้ระบบล็อกอิน) + const user_id = req.session.userId; // สมมติว่าเก็บ user_id ไว้ใน session - // ส่งข้อมูล user ไปยัง confirm-loan.ejs - res.render("confirm-loan", { equipment, quantity, user: req.user }); - } - ); + db.query(query, [equipment_id, quantity, user_id], (err, result) => { + if (err) { + console.error('Error inserting loan data:', err); + return res.status(500).send('เกิดข้อผิดพลาดในการยืมอุปกรณ์'); + } + + // ปรับสถานะของอุปกรณ์หลังการยืม + const updateQuery = 'UPDATE equipment SET quantity = quantity - ? WHERE id = ?'; + db.query(updateQuery, [quantity, equipment_id], (err) => { + if (err) { + console.error('Error updating equipment quantity:', err); + return res.status(500).send('เกิดข้อผิดพลาดในการปรับปรุงข้อมูลอุปกรณ์'); + } + + res.redirect('/loans'); // ไปยังหน้ารวมการยืมอุปกรณ์ + }); + }); }); diff --git a/views/index.ejs b/views/index.ejs index 040be00..303187c 100644 --- a/views/index.ejs +++ b/views/index.ejs @@ -84,13 +84,12 @@ <form action="/confirm-loan" method="POST" class="flex space-x-2"> <input type="hidden" name="equipment_id" value="<%= item.id %>"> <label for="quantity" class="text-sm text-gray-700">จำนวน:</label> - <input type="number" name="quantity" min="1" max="<%= item.quantity %>" - class="p-2 border border-gray-300 rounded-md" required> - <button type="submit" - class="bg-blue-600 text-white p-2 rounded-md hover:bg-blue-700"> - ยืมอุปกรณ์ + <input type="number" name="quantity" min="1" max="<%= item.quantity %>" class="p-2 border border-gray-300 rounded-md" required> + <button type="submit" class="bg-blue-600 text-white p-2 rounded-md hover:bg-blue-700"> + ยืมอุปกรณ์ </button> - </form> + </form> + <% } else { %> <span class="text-gray-400">ไม่สามารถยืมได้</span> -- GitLab