|
| 1 | +package controller; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.math.BigDecimal; |
| 5 | +import java.sql.Connection; |
| 6 | +import java.sql.SQLException; |
| 7 | +import java.util.ArrayList; |
| 8 | +import java.util.List; |
| 9 | +import java.util.Map; |
| 10 | + |
| 11 | +import javax.servlet.ServletException; |
| 12 | +import javax.servlet.annotation.WebServlet; |
| 13 | +import javax.servlet.http.HttpServlet; |
| 14 | +import javax.servlet.http.HttpServletRequest; |
| 15 | +import javax.servlet.http.HttpServletResponse; |
| 16 | +import javax.servlet.http.HttpSession; |
| 17 | + |
| 18 | +import config.DIContainer; |
| 19 | +import dao.OrderDAO; |
| 20 | +import dao.OrderProductDAO; |
| 21 | +import dao.interfaces.ProductDAO; |
| 22 | +import model.Order; |
| 23 | +import model.OrderProduct; |
| 24 | +import model.Product; |
| 25 | +import model.User; |
| 26 | + |
| 27 | +@WebServlet("/order/*") |
| 28 | +public class OrderEditController extends HttpServlet { |
| 29 | + |
| 30 | + private OrderDAO orderDAO; |
| 31 | + private OrderProductDAO orderProductDAO; |
| 32 | + private ProductDAO productDAO; |
| 33 | + |
| 34 | + @Override |
| 35 | + public void init() throws ServletException { |
| 36 | + try { |
| 37 | + Connection conn = DIContainer.getConnection(); |
| 38 | + orderDAO = new OrderDAO(conn); |
| 39 | + orderProductDAO = new OrderProductDAO(conn); |
| 40 | + productDAO = DIContainer.get(ProductDAO.class); |
| 41 | + } catch (Exception e) { |
| 42 | + throw new ServletException("Failed to initialize OrderEditController", e); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + @Override |
| 47 | + protected void doGet(HttpServletRequest request, HttpServletResponse response) |
| 48 | + throws ServletException, IOException { |
| 49 | + |
| 50 | + HttpSession session = request.getSession(false); |
| 51 | + if (session == null) { |
| 52 | + response.sendRedirect(request.getContextPath() + "/login.jsp"); |
| 53 | + return; |
| 54 | + } |
| 55 | + Object userObj = session.getAttribute("user"); |
| 56 | + if (!(userObj instanceof User)) { |
| 57 | + response.sendRedirect(request.getContextPath() + "/login.jsp"); |
| 58 | + return; |
| 59 | + } |
| 60 | + User user = (User) userObj; |
| 61 | + |
| 62 | + String pathInfo = request.getPathInfo(); |
| 63 | + if ("/edit".equals(pathInfo)) { |
| 64 | + showEditForm(request, response, user); |
| 65 | + } else { |
| 66 | + response.sendError(HttpServletResponse.SC_NOT_FOUND); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + @Override |
| 71 | + protected void doPost(HttpServletRequest request, HttpServletResponse response) |
| 72 | + throws ServletException, IOException { |
| 73 | + |
| 74 | + HttpSession session = request.getSession(false); |
| 75 | + if (session == null) { |
| 76 | + response.sendRedirect(request.getContextPath() + "/login.jsp"); |
| 77 | + return; |
| 78 | + } |
| 79 | + Object userObj = session.getAttribute("user"); |
| 80 | + if (!(userObj instanceof User)) { |
| 81 | + response.sendRedirect(request.getContextPath() + "/login.jsp"); |
| 82 | + return; |
| 83 | + } |
| 84 | + User user = (User) userObj; |
| 85 | + |
| 86 | + if (!utils.SecurityUtil.validateCSRFToken(request)) { |
| 87 | + utils.ErrorAction.handleValidationError(request, response, |
| 88 | + "CSRF token validation failed", "OrderEditController.doPost"); |
| 89 | + return; |
| 90 | + } |
| 91 | + |
| 92 | + String pathInfo = request.getPathInfo(); |
| 93 | + if ("/update".equals(pathInfo)) { |
| 94 | + processUpdate(request, response, user); |
| 95 | + } else { |
| 96 | + response.sendError(HttpServletResponse.SC_NOT_FOUND); |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + private void showEditForm(HttpServletRequest request, HttpServletResponse response, User user) |
| 101 | + throws ServletException, IOException { |
| 102 | + try { |
| 103 | + int orderId = utils.SecurityUtil.getValidatedIntParameter(request, "orderId", 1, Integer.MAX_VALUE); |
| 104 | + Order order = orderDAO.getOrderById(orderId); |
| 105 | + |
| 106 | + if (order == null || order.getUserId() != user.getId()) { |
| 107 | + utils.ErrorAction.handleAuthorizationError(request, response, "OrderEditController.showEditForm"); |
| 108 | + return; |
| 109 | + } |
| 110 | + |
| 111 | + if (!"Pending".equalsIgnoreCase(order.getStatus()) && !"PENDING".equalsIgnoreCase(order.getStatus())) { |
| 112 | + request.setAttribute("error", "Only pending orders can be edited."); |
| 113 | + request.setAttribute("order", order); |
| 114 | + request.getRequestDispatcher("/order-edit.jsp").forward(request, response); |
| 115 | + return; |
| 116 | + } |
| 117 | + |
| 118 | + List<OrderProduct> rawItems = orderProductDAO.getProductsByOrderId(orderId); |
| 119 | + List<Map<String, Object>> enrichedItems = new ArrayList<>(); |
| 120 | + for (OrderProduct op : rawItems) { |
| 121 | + java.util.HashMap<String, Object> item = new java.util.HashMap<>(); |
| 122 | + item.put("productId", op.getProductId()); |
| 123 | + item.put("quantity", op.getQuantity()); |
| 124 | + item.put("priceAtOrderTime", op.getPriceAtOrderTime()); |
| 125 | + try { |
| 126 | + Product p = productDAO.getProductById(op.getProductId()); |
| 127 | + item.put("productName", p != null ? p.getName() : "Product #" + op.getProductId()); |
| 128 | + item.put("stock", p != null ? p.getStockQuantity() : 0); |
| 129 | + } catch (Exception ex) { |
| 130 | + item.put("productName", "Product #" + op.getProductId()); |
| 131 | + item.put("stock", 0); |
| 132 | + } |
| 133 | + enrichedItems.add(item); |
| 134 | + } |
| 135 | + |
| 136 | + request.setAttribute("order", order); |
| 137 | + request.setAttribute("orderItems", enrichedItems); |
| 138 | + request.getRequestDispatcher("/order-edit.jsp").forward(request, response); |
| 139 | + |
| 140 | + } catch (Exception e) { |
| 141 | + utils.ErrorAction.handleServerError(request, response, e, "OrderEditController.showEditForm"); |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + private void processUpdate(HttpServletRequest request, HttpServletResponse response, User user) |
| 146 | + throws ServletException, IOException { |
| 147 | + try { |
| 148 | + int orderId = utils.SecurityUtil.getValidatedIntParameter(request, "orderId", 1, Integer.MAX_VALUE); |
| 149 | + Order order = orderDAO.getOrderById(orderId); |
| 150 | + |
| 151 | + if (order == null || order.getUserId() != user.getId()) { |
| 152 | + utils.ErrorAction.handleAuthorizationError(request, response, "OrderEditController.processUpdate"); |
| 153 | + return; |
| 154 | + } |
| 155 | + |
| 156 | + if (!"Pending".equalsIgnoreCase(order.getStatus()) && !"PENDING".equalsIgnoreCase(order.getStatus())) { |
| 157 | + response.sendRedirect(request.getContextPath() + "/orderhistory?error=Order+cannot+be+modified"); |
| 158 | + return; |
| 159 | + } |
| 160 | + |
| 161 | + String[] productIds = request.getParameterValues("productId"); |
| 162 | + if (productIds == null || productIds.length == 0) { |
| 163 | + response.sendRedirect(request.getContextPath() + "/orderhistory"); |
| 164 | + return; |
| 165 | + } |
| 166 | + |
| 167 | + BigDecimal newTotal = BigDecimal.ZERO; |
| 168 | + |
| 169 | + for (String productIdStr : productIds) { |
| 170 | + int productId = Integer.parseInt(productIdStr); |
| 171 | + String qtyStr = request.getParameter("quantity_" + productId); |
| 172 | + if (qtyStr == null) continue; |
| 173 | + |
| 174 | + int newQty = Integer.parseInt(qtyStr); |
| 175 | + |
| 176 | + // Get current order product |
| 177 | + List<OrderProduct> existing = orderProductDAO.getProductsByOrderId(orderId); |
| 178 | + OrderProduct current = null; |
| 179 | + for (OrderProduct op : existing) { |
| 180 | + if (op.getProductId() == productId) { |
| 181 | + current = op; |
| 182 | + break; |
| 183 | + } |
| 184 | + } |
| 185 | + if (current == null) continue; |
| 186 | + |
| 187 | + int oldQty = current.getQuantity(); |
| 188 | + int diff = newQty - oldQty; |
| 189 | + |
| 190 | + if (newQty <= 0) { |
| 191 | + // Remove item and restore stock |
| 192 | + orderProductDAO.deleteOrderProduct(orderId, productId); |
| 193 | + if (oldQty > 0) { |
| 194 | + productDAO.increaseStock(productId, oldQty); |
| 195 | + } |
| 196 | + } else { |
| 197 | + if (diff > 0) { |
| 198 | + // Increasing quantity - check stock |
| 199 | + Product p = productDAO.getProductById(productId); |
| 200 | + if (p == null || p.getStockQuantity() < diff) { |
| 201 | + response.sendRedirect(request.getContextPath() |
| 202 | + + "/order/edit?orderId=" + orderId |
| 203 | + + "&error=Insufficient+stock+for+product+" + productId); |
| 204 | + return; |
| 205 | + } |
| 206 | + productDAO.decreaseStock(productId, diff); |
| 207 | + } else if (diff < 0) { |
| 208 | + // Decreasing quantity - restore stock |
| 209 | + productDAO.increaseStock(productId, -diff); |
| 210 | + } |
| 211 | + current.setQuantity(newQty); |
| 212 | + orderProductDAO.updateOrderProduct(current); |
| 213 | + newTotal = newTotal.add(BigDecimal.valueOf(current.getPriceAtOrderTime() * newQty)); |
| 214 | + } |
| 215 | + } |
| 216 | + |
| 217 | + // Recalculate order total |
| 218 | + List<OrderProduct> remaining = orderProductDAO.getProductsByOrderId(orderId); |
| 219 | + if (remaining.isEmpty()) { |
| 220 | + // No items left - cancel order |
| 221 | + order.setStatus("Cancelled"); |
| 222 | + } |
| 223 | + BigDecimal total = BigDecimal.ZERO; |
| 224 | + for (OrderProduct op : remaining) { |
| 225 | + total = total.add(BigDecimal.valueOf(op.getPriceAtOrderTime() * op.getQuantity())); |
| 226 | + } |
| 227 | + order.setTotalAmount(total); |
| 228 | + orderDAO.updateOrder(order); |
| 229 | + |
| 230 | + response.sendRedirect(request.getContextPath() + "/orderhistory"); |
| 231 | + |
| 232 | + } catch (Exception e) { |
| 233 | + utils.ErrorAction.handleServerError(request, response, e, "OrderEditController.processUpdate"); |
| 234 | + } |
| 235 | + } |
| 236 | +} |
0 commit comments