diff --git a/init/full.sql b/init/full.sql index 1c30929b..5f4b8e7b 100644 --- a/init/full.sql +++ b/init/full.sql @@ -1,185 +1,186 @@ -- create ffood database create database ffood; -go +GO --use ffood database use ffood; -go +GO -- Create 14 tables create table FoodType ( food_type_id tinyint identity(1,1) not null primary key, - food_type nvarchar(20) not null + food_type nvarchar(20) not null ); -go +GO create table Food ( - food_id smallint identity(1,1) not null primary key, - food_name nvarchar(500) not null, - food_description nvarchar(2000) not null, - food_price money not null, - food_status bit not null, - food_rate tinyint not null, + food_id smallint identity(1,1) not null primary key, + food_name nvarchar(500) not null, + food_description nvarchar(2000) null, + food_price money not null, + food_status bit not null, + food_rate tinyint null, discount_percent tinyint not null, - food_img_url varchar(255) not null, + food_img_url varchar(400) not null, food_type_id tinyint not null foreign key references FoodType(food_type_id) ); -go +GO create table [Admin] ( - admin_id tinyint identity(1,1) not null primary key, + admin_id tinyint identity(1,1) not null primary key, admin_fullname nvarchar(200) not null, ); -go +GO create table AdminFood ( - admin_id tinyint not null foreign key references [Admin](admin_id), - food_id smallint not null foreign key references Food(food_id) + admin_id tinyint not null foreign key references [Admin](admin_id), + food_id smallint not null foreign key references Food(food_id) ); -go +GO create table Staff ( - staff_id tinyint identity(1,1) not null primary key, + staff_id tinyint identity(1,1) not null primary key, staff_fullname nvarchar(200) not null, ); -go +GO create table Voucher ( - voucher_id tinyint identity(1,1) not null primary key, - voucher_name nvarchar(200) not null, - voucher_code char(16) not null, + voucher_id tinyint identity(1,1) not null primary key, + voucher_name nvarchar(200) not null, + voucher_code char(16) not null, voucher_discount_percent tinyint not null, - voucher_quantity tinyint not null, - voucher_status bit not null, - voucher_date datetime not null + voucher_quantity tinyint not null, + voucher_status bit not null, + voucher_date datetime not null ); -go +GO create table PromotionManager ( - pro_id tinyint identity(1,1) not null primary key, + pro_id tinyint identity(1,1) not null primary key, pro_fullname nvarchar(200) not null, ); -go +GO create table Customer ( - customer_id int identity(1,1) not null primary key, - customer_firstname nvarchar(200) null, - customer_lastname nvarchar(200) null, - customer_gender nvarchar(5) null, - customer_phone varchar(11) null, - customer_address nvarchar(1000) null + customer_id int identity(1,1) not null primary key, + customer_firstname nvarchar(200) not null, + customer_lastname nvarchar(200) not null, + customer_gender nvarchar(5) not null, + customer_phone varchar(11) not null, + customer_address nvarchar(1000) not null ); -go +GO -- Create index for Customer table to improve search performance create index idx_customer_firstname_lastname_gender_phone_address on Customer (customer_firstname, customer_lastname, customer_gender, customer_phone, customer_address); -go +GO + create table Account ( - account_id int identity(1,1) not null primary key, - customer_id int null foreign key references Customer(customer_id), - staff_id tinyint null foreign key references Staff(staff_id), - pro_id tinyint null foreign key references PromotionManager(pro_id), - admin_id tinyint null foreign key references [Admin](admin_id), + account_id int identity(1,1) not null primary key, + customer_id int null foreign key references Customer(customer_id), + staff_id tinyint null foreign key references Staff(staff_id), + pro_id tinyint null foreign key references PromotionManager(pro_id), + admin_id tinyint null foreign key references [Admin](admin_id), account_username nvarchar(100) not null, account_email nvarchar(500) not null, account_password char(32) not null, account_type varchar(20) not null, ); -go +GO create table Cart ( - cart_id int identity(1,1) not null primary key, - customer_id int not null foreign key references Customer(customer_id) + cart_id int identity(1,1) not null primary key, + customer_id int not null foreign key references Customer(customer_id) ); -go +GO create table CartItem ( cart_item_id int identity(1,1) not null primary key, - cart_id int not null foreign key references Cart(cart_id), - food_id smallint not null foreign key references Food(food_id), - food_price money not null, + cart_id int not null foreign key references Cart(cart_id), + food_id smallint not null foreign key references Food(food_id), + food_price money not null, food_quantity tinyint not null ); -go +GO create table OrderStatus ( order_status_id tinyint identity(1,1) not null primary key, order_status nvarchar(50) not null ); -go +GO create table PaymentMethod ( payment_method_id tinyint identity(1,1) not null primary key, payment_method nvarchar(50) not null ); -go +GO create table [Order] ( - order_id int identity(1,1) not null primary key, - cart_id int not null foreign key references Cart(cart_id), - customer_id int not null foreign key references Customer(customer_id), + order_id int identity(1,1) not null primary key, + cart_id int not null foreign key references Cart(cart_id), + admin_id tinyint null foreign key references [Admin](admin_id), + staff_id tinyint null foreign key references Staff(staff_id), + customer_id int not null foreign key references Customer(customer_id), order_status_id tinyint not null foreign key references OrderStatus(order_status_id), payment_method_id tinyint not null foreign key references PaymentMethod(payment_method_id), - voucher_id tinyint null foreign key references Voucher(voucher_id), + voucher_id tinyint null foreign key references Voucher(voucher_id), contact_phone varchar(11) not null, delivery_address nvarchar(500) not null, - order_time datetime not null, - order_total money not null, - order_note nvarchar(1023) null, + order_time datetime not null, + order_total money not null, + order_note nvarchar(1023) null, delivery_time datetime null, order_cancel_time datetime null ); GO +create table Payment ( + order_id int not null foreign key references [Order](order_id), + payment_method_id tinyint not null foreign key references PaymentMethod(payment_method_id), + payment_total money not null, + payment_content nvarchar(1023) null, + payment_bank nvarchar(50) null, + payment_code varchar(20) null, + payment_status tinyint not null, + payment_time datetime not null +); + +GO --Use ffood database USE ffood GO --- Remove link food to other database after delete food -CREATE TRIGGER tr_delete_admin_food_links -ON Food -FOR DELETE -AS -BEGIN - DELETE FROM AdminFood WHERE food_id IN (SELECT deleted.food_id FROM deleted); -END - -go - --- Check price and discount percent before add to Food table -CREATE TRIGGER tr_check_food_price +-- Inactivate food when delete +CREATE TRIGGER tr_InactivateFood ON Food -AFTER DELETE +INSTEAD OF DELETE AS BEGIN - IF (SELECT COUNT(*) FROM inserted WHERE food_price <= 0 OR discount_percent < 0 OR discount_percent > 100) > 0 - BEGIN - RAISERROR('Invalid food price or discount percent.', 16, 1) - ROLLBACK - END -END + UPDATE Food + SET food_status = 0 + WHERE food_id IN (SELECT food_id FROM deleted); +END; GO -- Remove cart after customer deleted - CREATE TRIGGER tr_delete_cart_links ON Account AFTER DELETE @@ -188,7 +189,7 @@ BEGIN DELETE FROM Cart WHERE customer_id IN (SELECT deleted.customer_id FROM deleted); END -go +GO -- Don't delete when still have order CREATE TRIGGER tr_prevent_delete_customer @@ -207,33 +208,6 @@ BEGIN END END -go - --- remove food from cart when a food was removed - -CREATE TRIGGER tr_remove_food_from_carts -ON Food -INSTEAD OF DELETE -AS -BEGIN - SET NOCOUNT ON; - - CREATE TABLE #CartsToRemove (cart_id INT); - - INSERT INTO #CartsToRemove (cart_id) - SELECT DISTINCT ci.cart_id - FROM CartItem ci - INNER JOIN deleted d ON ci.food_id = d.food_id; - - DELETE FROM CartItem WHERE food_id IN (SELECT food_id FROM deleted); - - DELETE FROM Food WHERE food_id IN (SELECT food_id FROM deleted); - - DELETE FROM Cart WHERE cart_id IN (SELECT cart_id FROM #CartsToRemove); - - DROP TABLE #CartsToRemove; -END - GO --Use ffood database @@ -261,24 +235,44 @@ insert into Account (admin_id, account_username, account_email, account_password insert into Account (admin_id, account_username, account_email, account_password, account_type) values (6, N'duykhang123', N'khanghdse172647@fpt.edu.vn', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'admin'); -- Staffs must be added before an associated Account (if exists) can be created -insert into Staff (staff_fullname) values ('Nguyễn Văn TestStaff'); +insert into Staff (staff_fullname) values ('Test Staff Mot'); +insert into Staff (staff_fullname) values ('Test Staff Hai'); +insert into Staff (staff_fullname) values ('Test Staff Ba'); +insert into Staff (staff_fullname) values ('Test Staff Bon'); +insert into Staff (staff_fullname) values ('Test Staff Nam'); +insert into Staff (staff_fullname) values ('Test Staff Sau'); -- Reset the identity seed for the Account table to 20 -- Staffs' account ID starts from 21-40 -dbcc checkident (Account, RESEED, 20); +dbcc checkident (Account, RESEED, 50); -- Insert Staff Account -insert into Account(staff_id, account_username, account_email, account_password, account_type) values (1, N'testStaff', N'teststaff@fpt.edu.vn', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'staff'); +insert into Account(staff_id, account_username, account_email, account_password, account_type) values (1, N'testStaff', N'teststaff1@fpt.edu.vn', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'staff'); +insert into Account(staff_id, account_username, account_email, account_password, account_type) values (2, N'testStaff', N'teststaff2@fpt.edu.vn', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'staff'); +insert into Account(staff_id, account_username, account_email, account_password, account_type) values (3, N'testStaff', N'teststaff3@fpt.edu.vn', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'staff'); +insert into Account(staff_id, account_username, account_email, account_password, account_type) values (4, N'testStaff', N'teststaff4@fpt.edu.vn', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'staff'); +insert into Account(staff_id, account_username, account_email, account_password, account_type) values (5, N'testStaff', N'teststaff5@fpt.edu.vn', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'staff'); +insert into Account(staff_id, account_username, account_email, account_password, account_type) values (6, N'testStaff', N'teststaff6@fpt.edu.vn', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'staff'); -- Insert test promotion manager account -insert into PromotionManager (pro_fullname) values ('Nguyễn Văn TestPromotion'); +insert into PromotionManager (pro_fullname) values ('Test Promotion Manager Mot'); +insert into PromotionManager (pro_fullname) values ('Test Promotion Manager Hai'); +insert into PromotionManager (pro_fullname) values ('Test Promotion Manager Ba'); +insert into PromotionManager (pro_fullname) values ('Test Promotion Manager Bon'); +insert into PromotionManager (pro_fullname) values ('Test Promotion Manager Nam'); +insert into PromotionManager (pro_fullname) values ('Test Promotion Manager Sau'); -- Promotion managers' account ID starts from 41-50 -dbcc checkident (Account, RESEED, 40); +dbcc checkident (Account, RESEED, 100); -- Insert Promotion Manager Account -insert into Account(pro_id, account_username, account_email, account_password, account_type) values (1, N'testPromotion', N'testPromotion@fpt.edu.vn', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'promotionManager'); +insert into Account(pro_id, account_username, account_email, account_password, account_type) values (1, N'testPromotion1', N'testPromotion1@fpt.edu.vn', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'promotionManager'); +insert into Account(pro_id, account_username, account_email, account_password, account_type) values (2, N'testPromotion2', N'testPromotion2@fpt.edu.vn', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'promotionManager'); +insert into Account(pro_id, account_username, account_email, account_password, account_type) values (3, N'testPromotion3', N'testPromotion3@fpt.edu.vn', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'promotionManager'); +insert into Account(pro_id, account_username, account_email, account_password, account_type) values (4, N'testPromotion4', N'testPromotion4@fpt.edu.vn', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'promotionManager'); +insert into Account(pro_id, account_username, account_email, account_password, account_type) values (5, N'testPromotion5', N'testPromotion5@fpt.edu.vn', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'promotionManager'); +insert into Account(pro_id, account_username, account_email, account_password, account_type) values (6, N'testPromotion6', N'testPromotion6@fpt.edu.vn', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'promotionManager'); -- Customer must be added before an associated Account (if exists) can be created insert into Customer (customer_firstname, customer_lastname, customer_gender, customer_phone, customer_address) values (N'Quoc Anh', N'Nguyen', N'Nam', '0914875606', N'Đường sô 3, Khu Vực Bình thường B, Bình Thủy, Cần Thơ'); -dbcc checkident (Account, RESEED, 50); +dbcc checkident (Account, RESEED, 200); -- Insert Customer Account insert into Account (customer_id, account_username, account_email, account_password, account_type) values (1, N'quocanh123', N'anhnq1130@gmail.com', CONVERT(NVARCHAR(32), HashBytes('MD5', '123456'), 2), 'user'); @@ -373,20 +367,22 @@ insert into Voucher (voucher_name, voucher_code, voucher_discount_percent, vouch -- Cart, CartItem, Order test data insert into Cart (customer_id) values (1); -insert into CartItem (cart_id, food_id, food_price, food_quantity) values (1, 2, 55000, 2); +insert into CartItem (cart_id, food_id, food_price, food_quantity) values (1, 2, 50000, 2); +insert into CartItem (cart_id, food_id, food_price, food_quantity) values (1, 10, 30000, 1); insert into CartItem (cart_id, food_id, food_price, food_quantity) values (1, 23, 20000, 3); -- Insert an Order for the Cart insert into [Order] ( -cart_id, customer_id, order_status_id, payment_method_id, +cart_id, customer_id, staff_id ,order_status_id, payment_method_id, contact_phone, delivery_address, order_time, order_total, order_note, delivery_time, order_cancel_time ) values ( -1, 1, 4, 1, -'0931278397', N'39 Mậu Thân, Ninh Kiều, Cần Thơ', '20230708 10:34:09 AM', 170000, +1, 1, 1, 4, 1, +'0931278397', N'39 Mậu Thân, Ninh Kiều, Cần Thơ', '20230708 10:34:09 AM', 190000, NULL, '20230708 10:49:35 AM', NULL); - - - - +insert into Payment ( + order_id, payment_method_id, payment_total, payment_content, payment_bank, payment_code, payment_status, payment_time +) values ( + 1,1,190000,N'Thanh toán đơn hàng ffood',N'NCB','14111641',1,'20230708 11:05:02 AM' +); \ No newline at end of file diff --git a/src/main/java/Controllers/AdminController.java b/src/main/java/Controllers/AdminController.java index 5010de49..a0e44584 100644 --- a/src/main/java/Controllers/AdminController.java +++ b/src/main/java/Controllers/AdminController.java @@ -521,8 +521,6 @@ private void doPostUpdateRole(HttpServletRequest request, HttpServletResponse re if (result == 1) { account.setProID(roleID); int result1 = accountDAO.add(account); - System.out.println(result1); - if (result1 == 1) { response.sendRedirect("/admin#success_update_role"); return; @@ -793,7 +791,6 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) } else if (path.startsWith("/admin/order")) { doGetOrder(request, response); } else { - // response.setContentType("text/css"); request.getRequestDispatcher("/admin.jsp").forward(request, response); } } diff --git a/src/main/java/Controllers/CheckoutController.java b/src/main/java/Controllers/CheckoutController.java index 102cb366..2d7c5851 100644 --- a/src/main/java/Controllers/CheckoutController.java +++ b/src/main/java/Controllers/CheckoutController.java @@ -7,11 +7,13 @@ import DAOs.CartItemDAO; import DAOs.CustomerDAO; import DAOs.OrderDAO; +import DAOs.VoucherDAO; import Models.Account; import Models.Cart; import Models.CartItem; import Models.Customer; import Models.Order; +import Models.Voucher; import java.io.IOException; import java.io.PrintWriter; import jakarta.servlet.ServletException; @@ -83,12 +85,8 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) int customerID = currentAccount.getCustomerID(); CustomerDAO customerDAO = new CustomerDAO(); Customer customer = customerDAO.getCustomer(customerID); - request.setAttribute("customer", customer); - // - } - // } // Lưu trữ URL hiện tại vào session attribute @@ -128,202 +126,305 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) request.getRequestDispatcher("checkout.jsp").forward(request, response); } - /** - * Handles the HTTP POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - * - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) + protected void doPostOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (request.getParameter("btnSubmit") != null - && request.getParameter("btnSubmit").equals("SubmitOrder")) { - int accountID = 0; - if (request.getParameter("txtAccountID") != null - && !request.getParameter("txtAccountID").isEmpty()) { - accountID = Integer.parseInt(request.getParameter("txtAccountID")); - } - - String lastname = request.getParameter("txtLastName"); - String firstname = request.getParameter("txtFirstName"); - String gender = request.getParameter("txtGender"); - String phone = request.getParameter("txtPhone"); - String address = request.getParameter("txtAddress"); - String note = request.getParameter("txtNote"); - - // Trình tự đặt món: thêm Customer -> Cart -> tất cả Cartitem -> Order - // Thêm Customer - Customer customer = new Customer(firstname, lastname, gender, phone, address); - CustomerDAO customerdao = new CustomerDAO(); - int customerID = 0; - - int result = 0; - if (accountID != 0) { - // Nếu có accountID -> đã login thành công - AccountDAO accountDAO = new AccountDAO(); - Account account = accountDAO.getAccount(accountID); - if (account.getCustomerID() != 0) { - // Tài khoản này đã có thông tin KH - customerID = account.getCustomerID(); - } else { + int accountID = 0; + if (request.getParameter("txtAccountID") != null + && !request.getParameter("txtAccountID").isEmpty()) { + accountID = Integer.parseInt(request.getParameter("txtAccountID")); + } - result = customerdao.add(customer); - if (result == 1) { - Customer lastestCustomer = customerdao.getLatestCustomer(); - account.setCustomerID(lastestCustomer.getCustomerID()); - accountDAO.updateCustomerID(account); - customerID = lastestCustomer.getCustomerID(); - } else { - response.sendRedirect("/home#failure"); - return; - } - - customer = customerdao.getLatestCustomer(); // customerId lay tu DB ra tang dan - customerID = customer.getCustomerID(); - } + String lastname = request.getParameter("txtLastName"); + String firstname = request.getParameter("txtFirstName"); + String gender = request.getParameter("txtGender"); + String phone = request.getParameter("txtPhone"); + String address = request.getParameter("txtAddress"); + String note = request.getParameter("txtNote"); + + // Trình tự đặt món: thêm Customer -> Cart -> tất cả Cartitem -> Order + // Thêm Customer + Customer customer = new Customer(firstname, lastname, gender, phone, address); + CustomerDAO customerdao = new CustomerDAO(); + int customerID = 0; + + int result = 0; + if (accountID != 0) { + // Nếu có accountID -> đã login thành công + AccountDAO accountDAO = new AccountDAO(); + Account account = accountDAO.getAccount(accountID); + if (account.getCustomerID() != 0) { + // Tài khoản này đã có thông tin KH + customerID = account.getCustomerID(); } else { - // result = customerdao.add(customer); - if (result != 1) { - request.getRequestDispatcher("checkout.jsp").forward(request, response); + if (result == 1) { + Customer lastestCustomer = customerdao.getLatestCustomer(); + account.setCustomerID(lastestCustomer.getCustomerID()); + accountDAO.updateCustomerID(account); + customerID = lastestCustomer.getCustomerID(); + } else { + response.sendRedirect("/home#failure"); return; } + customer = customerdao.getLatestCustomer(); // customerId lay tu DB ra tang dan customerID = customer.getCustomerID(); } + } else { - // Lấy Cart từ session -> thêm vào db - HttpSession session = request.getSession(); - Cart cart = (Cart) session.getAttribute("cart"); - CartDAO cartdao = new CartDAO(); - - cart.setUserId(customerID); - result = cartdao.add(cart); + // + result = customerdao.add(customer); if (result != 1) { request.getRequestDispatcher("checkout.jsp").forward(request, response); + return; } + customer = customerdao.getLatestCustomer(); // customerId lay tu DB ra tang dan + customerID = customer.getCustomerID(); + } - CartItemDAO cartitemdao = new CartItemDAO(); - List cartItemList = cart.getItems(); - int cartID = cartdao.getLatestCartID(); - cart = cartdao.getCart(cartID); - - double orderTotalDouble = 0; - for (CartItem item : cartItemList) { - int itemDiscount = item.getFood().getDiscountPercent(); - double itemPrice = item.getFood().getFoodPrice().doubleValue(); - int itemQuantity = item.getFoodQuantity(); - orderTotalDouble += (itemPrice - (itemPrice * itemDiscount / 100)) * itemQuantity; - - item.setCartID(cart.getId()); - result = cartitemdao.add(item); - if (result != 1) { - request.getRequestDispatcher("checkout.jsp").forward(request, response); - return; - } - } + // Lấy Cart từ session -> thêm vào db + HttpSession session = request.getSession(); + Cart cart = (Cart) session.getAttribute("cart"); + CartDAO cartdao = new CartDAO(); - // Lấy thời gian hiện tại - LocalDateTime currentTime = LocalDateTime.now(); - // Chuyển đổi thời gian hiện tại thành Timestamp - Timestamp orderTime = Timestamp.valueOf(currentTime); - // Tạo một số ngẫu nhiên từ 5 đến 15 - int randomMinutes = ThreadLocalRandom.current().nextInt(5, 16); - // Tính toán deliveryTime bằng cách cộng thời gian giao hàng ngẫu nhiên với orderTime - LocalDateTime deliveryDateTime = currentTime.plusMinutes(randomMinutes); - Timestamp deliveryTime = Timestamp.valueOf(deliveryDateTime); - - OrderDAO orderdao = new OrderDAO(); - Order order = new Order(cartID, customerID, (byte) 1, (byte) 3, phone, address, orderTime, note, deliveryTime); - // Do khi khởi tạo giá trị mặc định của orderTotal = 0 - // nên ta tự set cho nó - BigDecimal orderTotal = BigDecimal.valueOf(orderTotalDouble); - order.setOrderTotal(orderTotal); - result = orderdao.add(order); + cart.setUserId(customerID); + result = cartdao.add(cart); + if (result != 1) { + request.getRequestDispatcher("checkout.jsp").forward(request, response); + } + + CartItemDAO cartitemdao = new CartItemDAO(); + List cartItemList = cart.getItems(); + int cartID = cartdao.getLatestCartID(); + cart = cartdao.getCart(cartID); + + double orderTotalDouble = 0; + for (CartItem item : cartItemList) { + int itemDiscount = item.getFood().getDiscountPercent(); + double itemPrice = item.getFood().getFoodPrice().doubleValue(); + int itemQuantity = item.getFoodQuantity(); + orderTotalDouble += (itemPrice - (itemPrice * itemDiscount / 100)) * itemQuantity; + + item.setCartID(cart.getId()); + result = cartitemdao.add(item); if (result != 1) { request.getRequestDispatcher("checkout.jsp").forward(request, response); + return; } + } + + + + // Lấy thời gian hiện tại + LocalDateTime currentTime = LocalDateTime.now(); + // Chuyển đổi thời gian hiện tại thành Timestamp + Timestamp orderTime = Timestamp.valueOf(currentTime); + // Tạo một số ngẫu nhiên từ 5 đến 15 + int randomMinutes = ThreadLocalRandom.current().nextInt(5, 16); + // Tính toán deliveryTime bằng cách cộng thời gian giao hàng ngẫu nhiên với orderTime + LocalDateTime deliveryDateTime = currentTime.plusMinutes(randomMinutes); + Timestamp deliveryTime = Timestamp.valueOf(deliveryDateTime); + OrderDAO orderdao = new OrderDAO(); + Order order = new Order(cartID, customerID, (byte) 1, (byte) 3, phone, address, orderTime, note, deliveryTime); + // Do khi khởi tạo giá trị mặc định của orderTotal = 0 + // nên ta tự set cho nó + + VoucherDAO voucherDAO = new VoucherDAO(); + if (request.getParameter("txtVoucherCode") != null) { + String voucherCode = request.getParameter("txtVoucherCode"); + Voucher voucher = voucherDAO.getVoucherByCode(voucherCode); + if (voucher != null ) { + orderTotalDouble = orderTotalDouble * voucher.getVoucherDiscount(); + voucherDAO.updateQuantity(voucher); + order.setVoucherID(voucher.getVoucherID()); + System.out.println("Giam gia"); + } else { + System.out.println("Khong giam gia"); + } + } + + BigDecimal orderTotal = BigDecimal.valueOf(orderTotalDouble); + order.setOrderTotal(orderTotal); + result = orderdao.add(order); + if (result != 1) { + request.getRequestDispatcher("checkout.jsp").forward(request, response); + } - session.removeAttribute("cart"); - // Điều hướng về home sau khi add order thành công - response.sendRedirect("/home#success"); - - } else if (request.getParameter("btnSubmit") != null - && request.getParameter("btnSubmit").equals("Checkout")) { - - HttpSession session = request.getSession(); + session.removeAttribute("cart"); + // Điều hướng về home sau khi add order thành công + response.sendRedirect("/home#success"); + } - if (session.getAttribute("userID") != null) { - int userID = (Integer) session.getAttribute("userID"); - // Người dùng có đăng nhập -> lấy thông tin người dùng để autofill - AccountDAO accountDAO = new AccountDAO(); - Account currentAccount = accountDAO.getAccount(userID); + protected void doPostCheckout(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { - request.setAttribute("currentAccount", currentAccount); - // - // This info will be used to preload the "Thông tin của tôi" form - // Default int values are assigned 0 instead of null - if (currentAccount.getCustomerID() != 0) { - // - int customerID = currentAccount.getCustomerID(); - CustomerDAO customerDAO = new CustomerDAO(); - Customer customer = customerDAO.getCustomer(customerID); + HttpSession session = request.getSession(); + + String voucherStatus = "Vui lòng nhập mã giảm giá nếu bạn có"; + request.setAttribute("voucherStatus", voucherStatus); + request.setAttribute("voucherpercent", 1.0); + + if (session.getAttribute("userID") != null) { + int userID = (Integer) session.getAttribute("userID"); + // Người dùng có đăng nhập -> lấy thông tin người dùng để autofill + AccountDAO accountDAO = new AccountDAO(); + Account currentAccount = accountDAO.getAccount(userID); - request.setAttribute("customer", customer); - // + request.setAttribute("currentAccount", currentAccount); + // + // This info will be used to preload the "Thông tin của tôi" form + // Default int values are assigned 0 instead of null + if (currentAccount.getCustomerID() != 0) { + // + int customerID = currentAccount.getCustomerID(); + CustomerDAO customerDAO = new CustomerDAO(); + Customer customer = customerDAO.getCustomer(customerID); - } + request.setAttribute("customer", customer); // + } + // + } - // Lưu trữ URL hiện tại vào session attribute - session.setAttribute("previousUrl", request.getRequestURI()); + // Lưu trữ URL hiện tại vào session attribute + session.setAttribute("previousUrl", request.getRequestURI()); - Cart cart = (Cart) session.getAttribute("cart"); - if (cart == null || cart.getItems().isEmpty()) { - cart = new Cart(); - session.setAttribute("mess", "Giỏ hàng của bạn đang trống, vui lòng thêm món để thanh toán."); - response.sendRedirect("/"); - return; + Cart cart = (Cart) session.getAttribute("cart"); + if (cart == null || cart.getItems().isEmpty()) { + cart = new Cart(); + session.setAttribute("mess", "Giỏ hàng của bạn đang trống, vui lòng thêm món để thanh toán."); + response.sendRedirect("/"); + return; + } + String quantityParam = ""; + for (CartItem cartItem : cart.getItems()) { + Short foodId = cartItem.getFood().getFoodID(); + + if (request.getParameter("quantity-" + foodId) != null) { + quantityParam = request.getParameter("quantity-" + foodId); + } else if (session.getAttribute("quantity-" + foodId) != null) { + quantityParam = (String) session.getAttribute("quantity-" + foodId); } - String quantityParam = ""; - for (CartItem cartItem : cart.getItems()) { - Short foodId = cartItem.getFood().getFoodID(); - - if (request.getParameter("quantity-" + foodId) != null) { - // Thông thường nếu truy cập /checkout thì sẽ có 2 cách truy cập: - // 1 là từ nút Thanh toán (từ modal Giỏ hàng) - // 2 là từ nút Đặt món (từ chính trang /checkout) - // Tất cả đều sử dụng POST và dữ liệu lấy từ form của trang trước đó - // nên ta sẽ lấy dữ liệu từ parameter - quantityParam = request.getParameter("quantity-" + foodId); - } else if (session.getAttribute("quantity-" + foodId) != null) { - // Tuy nhiên nếu yêu cầu là GET, ví dụ như sau khi đăng nhập - // hoặc đăng xuất thành công thì trả về trang hiện tại tức /checkout - // thì parameter của request sau khi submit form không còn, - // nên ta phải lưu giá trị của form bằng session attribute, - // do đó ta phải lấy từ session - quantityParam = (String) session.getAttribute("quantity-" + foodId); - } - int quantity = Integer.parseInt(quantityParam); - cartItem.setFoodQuantity(quantity); // Cập nhật số lượng cho mục trong giỏ hàng - // Lưu lại số lượng của các mục trong trường hợp request là GET - // ví dụ như sau khi đăng nhập/đăng xuất thành công tại /checkout - session.setAttribute("quantity-" + foodId, quantityParam); + int quantity = Integer.parseInt(quantityParam); + cartItem.setFoodQuantity(quantity); // Cập nhật số lượng cho mục trong giỏ hàng + session.setAttribute("quantity-" + foodId, quantityParam); + } + session.setAttribute("cart", cart); + + // Remove empty cart message if it exists + if (session.getAttribute("mess") != null) { + session.removeAttribute("mess"); + } + + request.getRequestDispatcher("checkout.jsp").forward(request, response); + } + + protected void doPostVoucher(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + HttpSession session = request.getSession(); + + String voucherCode = request.getParameter("voucherCode"); + VoucherDAO voucherDAO = new VoucherDAO(); + Voucher voucher = voucherDAO.getVoucherByCode(voucherCode); + Double voucherpercent = 1.0; + String voucherStatus = "Vui lòng nhập mã giảm giá nếu bạn có"; + LocalDateTime currentTime = LocalDateTime.now(); + Timestamp now = Timestamp.valueOf(currentTime); + if (voucher != null) { + if (voucher.getVoucher_status() == 1 && now.compareTo(voucher.getVoucher_date()) < 0){ + request.setAttribute("voucherCode", voucherCode); + voucherpercent= voucher.getVoucherDiscount(); + System.out.println(voucherpercent); + + voucherStatus = voucher.getVoucher_name() + " - Giảm giá " + voucher.getVoucher_discount_percent() + "%"; + request.setAttribute("voucherStatus", voucherStatus); + request.setAttribute("voucherpercent", voucherpercent); + } else { + request.setAttribute("voucherStatus", voucherStatus); + request.setAttribute("voucherpercent", voucherpercent); + } + } else { + request.setAttribute("voucherStatus", voucherStatus); + request.setAttribute("voucherpercent", voucherpercent); + } + + + if (session.getAttribute("userID") != null) { + int userID = (Integer) session.getAttribute("userID"); + // Người dùng có đăng nhập -> lấy thông tin người dùng để autofill + AccountDAO accountDAO = new AccountDAO(); + Account currentAccount = accountDAO.getAccount(userID); + + request.setAttribute("currentAccount", currentAccount); + // + // This info will be used to preload the "Thông tin của tôi" form + // Default int values are assigned 0 instead of null + if (currentAccount.getCustomerID() != 0) { + // + int customerID = currentAccount.getCustomerID(); + CustomerDAO customerDAO = new CustomerDAO(); + Customer customer = customerDAO.getCustomer(customerID); + + request.setAttribute("customer", customer); + // + } - session.setAttribute("cart", cart); + // + } + + // Lưu trữ URL hiện tại vào session attribute + session.setAttribute("previousUrl", request.getRequestURI()); + + Cart cart = (Cart) session.getAttribute("cart"); + if (cart == null || cart.getItems().isEmpty()) { + cart = new Cart(); + session.setAttribute("mess", "Giỏ hàng của bạn đang trống, vui lòng thêm món để thanh toán."); + response.sendRedirect("/"); + return; + } + String quantityParam = ""; + for (CartItem cartItem : cart.getItems()) { + Short foodId = cartItem.getFood().getFoodID(); - // Remove empty cart message if it exists - if (session.getAttribute("mess") != null) { - session.removeAttribute("mess"); + if (request.getParameter("quantity-" + foodId) != null) { + quantityParam = request.getParameter("quantity-" + foodId); + } else if (session.getAttribute("quantity-" + foodId) != null) { + quantityParam = (String) session.getAttribute("quantity-" + foodId); } + int quantity = Integer.parseInt(quantityParam); + cartItem.setFoodQuantity(quantity); // Cập nhật số lượng cho mục trong giỏ hàng + session.setAttribute("quantity-" + foodId, quantityParam); + } + session.setAttribute("cart", cart); - request.getRequestDispatcher("checkout.jsp").forward(request, response); + // Remove empty cart message if it exists + if (session.getAttribute("mess") != null) { + session.removeAttribute("mess"); + } + + request.getRequestDispatcher("checkout.jsp").forward(request, response); + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + * + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + if (request.getParameter("btnSubmit") != null && request.getParameter("btnSubmit").equals("SubmitOrder")) { + doPostOrder(request, response); + } else if (request.getParameter("btnSubmit") != null && request.getParameter("btnSubmit").equals("Checkout")) { + doPostCheckout(request,response); + } else if (request.getParameter("btnSubmit") != null && request.getParameter("btnSubmit").equals("SubmitVoucher")) { + doPostVoucher(request,response); } } diff --git a/src/main/java/DAOs/VoucherDAO.java b/src/main/java/DAOs/VoucherDAO.java index df3361d0..cda62514 100644 --- a/src/main/java/DAOs/VoucherDAO.java +++ b/src/main/java/DAOs/VoucherDAO.java @@ -51,6 +51,21 @@ public Voucher getVoucher(byte id) { return voucher; } + public Voucher getVoucherByCode(String code) { + Voucher voucher = null; + try { + ps = conn.prepareStatement("select * from Voucher where voucher_code = ?"); + ps.setString(1, code); + rs = ps.executeQuery(); + if (rs.next()) { + voucher = new Voucher(rs.getByte("voucher_id"), rs.getString("voucher_name"), rs.getString("voucher_code"),rs.getByte("voucher_discount_percent"),rs.getByte("voucher_quantity"), rs.getByte("voucher_status"), rs.getTimestamp("voucher_date")); + } + } catch (SQLException ex) { + Logger.getLogger(VoucherDAO.class.getName()).log(Level.SEVERE, null, ex); + } + return voucher; + } + public Voucher getVoucher(String voucher_name) { Voucher voucher = null; try { @@ -169,5 +184,26 @@ public int update(Voucher voucher) { return result; } - + public int updateQuantity(Voucher voucher) { + String sql = "update Voucher set voucher_quantity = ?, voucher_status = ? where voucher_id = ?"; + int result = 0; + byte status = voucher.getVoucher_status(); + byte quantity = voucher.getVoucher_quantity(); + if (quantity == 1) { + status = 0; + quantity = 0; + } else { + quantity = (byte) (quantity - 1); + } + try { + PreparedStatement ps = conn.prepareStatement(sql); + ps.setByte(1, quantity); + ps.setByte(2, status); + ps.setByte(3, voucher.getVoucherID()); + result = ps.executeUpdate(); + } catch (SQLException ex) { + Logger.getLogger(VoucherDAO.class.getName()).log(Level.SEVERE, null, ex); + } + return result; + } } diff --git a/src/main/java/Models/Voucher.java b/src/main/java/Models/Voucher.java index 8382f1a7..745a637b 100644 --- a/src/main/java/Models/Voucher.java +++ b/src/main/java/Models/Voucher.java @@ -93,6 +93,13 @@ public void setVoucher_status(byte voucher_status) { public byte getVoucher_discount_percent() { return voucher_discount_percent; } + + public double getVoucherDiscount() { + int intValue = Byte.toUnsignedInt(voucher_discount_percent); + System.out.println("intValue " + intValue); + double percentage = (double) intValue / 100; + return percentage; + } public void setVoucher_discount_percent(byte voucher_discount_percent) { this.voucher_discount_percent = voucher_discount_percent; diff --git a/src/main/webapp/WEB-INF/jspf/admin/roles.jspf b/src/main/webapp/WEB-INF/jspf/admin/roles.jspf index d89c23fd..7b721511 100644 --- a/src/main/webapp/WEB-INF/jspf/admin/roles.jspf +++ b/src/main/webapp/WEB-INF/jspf/admin/roles.jspf @@ -44,7 +44,7 @@ ${r.fullname} ${r.username} ${r.email} - ${r.accountType eq 'staff' ? 'Staff' : 'Promotion Manager'} + ${r.accountType} diff --git a/src/main/webapp/WEB-INF/jspf/guest/components/verify.jspf b/src/main/webapp/WEB-INF/jspf/guest/components/verify.jspf index a5c34b0b..b75a6d60 100644 --- a/src/main/webapp/WEB-INF/jspf/guest/components/verify.jspf +++ b/src/main/webapp/WEB-INF/jspf/guest/components/verify.jspf @@ -20,7 +20,7 @@
- +
@@ -32,4 +32,31 @@ + + + + \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/web.xml b/src/main/webapp/WEB-INF/web.xml index 6a8ee62c..f812d436 100644 --- a/src/main/webapp/WEB-INF/web.xml +++ b/src/main/webapp/WEB-INF/web.xml @@ -180,6 +180,10 @@ CheckoutController /checkout + + CheckoutController + /checkout/* + LoginController /login diff --git a/src/main/webapp/assets/js/dataTablesConfig.js b/src/main/webapp/assets/js/dataTablesConfig.js index 6f4fc53e..256da0c2 100644 --- a/src/main/webapp/assets/js/dataTablesConfig.js +++ b/src/main/webapp/assets/js/dataTablesConfig.js @@ -441,13 +441,7 @@ $(document).ready(function () { btnUpdate.attr("data-role-username", data2[0][2]); btnUpdate.attr("data-role-fullname", data2[0][3]); btnUpdate.attr("data-role-email", data2[0][4]); - let account_type = ""; - if (data2[0][5] === "Staff"){ - account_type = "staff"; - } else { - account_type = "promotionManager"; - } - btnUpdate.attr("data-role-type", account_type); + btnUpdate.attr("data-role-type", data2[0][5]); btnUpdate.removeClass("disabled"); let roles = {}; diff --git a/src/main/webapp/assets/js/validateForm.js b/src/main/webapp/assets/js/validateForm.js index 58797409..5a2c5098 100644 --- a/src/main/webapp/assets/js/validateForm.js +++ b/src/main/webapp/assets/js/validateForm.js @@ -558,6 +558,26 @@ function validateForm() { form.submit(); } }); + + $("#voucher-form").validate({ + rules: { + voucherCode: { + required: true, + maxlength: 16, + } + }, + messages: { + voucherCode: { + required: "Vui lòng nhập mã giảm giá", + maxlength: "Mã giảm giá không được vượt quá 16 ký tự" + } + + }, + submitHandler: function (form) { + // Handle form submission here + form.submit(); + } + }); $("#changePass-form").validate({ rules: { @@ -756,6 +776,9 @@ $(".checkout-form").validate({ txtAddress: { required: true, maxlength: 255 + }, + txtVoucherCode: { + maxlength: 16 } }, messages: { @@ -777,6 +800,9 @@ $(".checkout-form").validate({ txtAddress: { required: "Vui lòng nhập địa chỉ của Người dùng", maxlength: "Địa chỉ không được vượt quá 255 kí tự" + }, + txtVoucherCode: { + maxlength: "Mã giảm giá không được vượt quá 16 kí tự" } }, submitHandler: function (form) { diff --git a/src/main/webapp/checkout.jsp b/src/main/webapp/checkout.jsp index 11cbefa4..866ff0a8 100644 --- a/src/main/webapp/checkout.jsp +++ b/src/main/webapp/checkout.jsp @@ -4,12 +4,6 @@ Author : CE171454 Hua Tien Thanh --%> -<%-- - Document : checkout - Created on : Jul 1, 2023, 8:00:52 PM - Author : CE171454 Hua Tien Thanh ---%> - <%@page contentType="text/html" pageEncoding="UTF-8"%> @@ -37,7 +31,7 @@ <%@ include file="WEB-INF/jspf/common/components/header.jspf" %> <%@ include file="WEB-INF/jspf/guest/components/login.jspf" %> <%@ include file="WEB-INF/jspf/guest/components/signup.jspf" %> - + <%@ include file="WEB-INF/jspf/guest/components/verify.jspf" %>
@@ -67,8 +61,6 @@ ${Double.parseDouble(cart.food.foodPrice- (cart.food.foodPrice * cart.food.discountPercent / 100)) * cart.foodQuantity} đ - -
@@ -80,32 +72,35 @@

Thông tin giao món

-
+
+
- -
-
-
- - -
+ +
+
+
+ + +
+
+ -
+
-
+
-
+
-
+
- +
- +
- +
@@ -133,13 +128,30 @@

Phương thức thanh toán

- Thanh toán khi nhận món (COD) + Thanh toán khi nhận món (COD)
+
+
+

Giảm giá

+
+ + +
+
+
+
+
+ ${voucherStatus} +
+
-

Tổng thanh toán: ${totalPrice}đ

+

Tổng thanh toán: ${totalPrice*(voucherpercent)}đ

@@ -149,6 +161,7 @@ <%@ include file="WEB-INF/jspf/common/components/footer.jspf" %> <%@ include file="WEB-INF/jspf/common/imports/javascript.jspf" %> + <%@ include file="WEB-INF/jspf/common/imports/validation.jspf" %> - - - <%@ include file="WEB-INF/jspf/common/imports/validation.jspf" %> - \ No newline at end of file diff --git a/src/main/webapp/index.jsp b/src/main/webapp/index.jsp index b1ea56f0..a446ff5b 100644 --- a/src/main/webapp/index.jsp +++ b/src/main/webapp/index.jsp @@ -15,16 +15,16 @@ Tien Thanh --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> - <%@ include file="WEB-INF/jspf/common/components/header.jspf" %> <%@ include - file="WEB-INF/jspf/guest/components/cart.jspf" %> <%@ include - file="WEB-INF/jspf/guest/components/login.jspf" %> <%@ include - file="WEB-INF/jspf/guest/components/signup.jspf" %> <%@ include - file="WEB-INF/jspf/guest/components/forget.jspf" %> <%@ include - file="WEB-INF/jspf/guest/components/changePassword.jspf" %> <%@ include - file="WEB-INF/jspf/guest/components/verify.jspf" %> <%@ include - file="WEB-INF/jspf/guest/components/success.jspf" %> <%@ include - file="WEB-INF/jspf/guest/components/failure.jspf" %> <%@ include - file="WEB-INF/jspf/guest/components/camera.jspf" %> + <%@ include file="WEB-INF/jspf/common/components/header.jspf" %> + <%@ include file="WEB-INF/jspf/guest/components/cart.jspf" %> + <%@ include file="WEB-INF/jspf/guest/components/login.jspf" %> + <%@ include file="WEB-INF/jspf/guest/components/signup.jspf" %> + <%@ include file="WEB-INF/jspf/guest/components/forget.jspf" %> + <%@ include file="WEB-INF/jspf/guest/components/changePassword.jspf" %> + <%@ include file="WEB-INF/jspf/guest/components/verify.jspf" %> + <%@ include file="WEB-INF/jspf/guest/components/success.jspf" %> + <%@ include file="WEB-INF/jspf/guest/components/failure.jspf" %> + <%@ include file="WEB-INF/jspf/guest/components/camera.jspf" %>
@@ -71,8 +71,8 @@ Tien Thanh --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ include file="WEB-INF/jspf/common/components/footer.jspf" %>
- <%@ include file="WEB-INF/jspf/common/imports/javascript.jspf" %> <%@ - include file="WEB-INF/jspf/common/imports/validation.jspf" %> + <%@ include file="WEB-INF/jspf/common/imports/javascript.jspf" %> + <%@ include file="WEB-INF/jspf/common/imports/validation.jspf" %>