쇼핑몰 웹사이트 만들어보기 - 장바구니 창에서 상품 수량 조절하기

Shiba·2024년 7월 29일
0

프로젝트 및 일기

목록 보기
10/29

이제 장바구니에 넣은 상품들이 제대로 들어갔는지 확인해보고, 장바구니 창에서 수량을 조정할 수 있도록 해보자.

getCart()는 이전시간에 만들었으므로, 컨트롤러와 html만 있으면 된다.

@GetMapping("/cart/{user_id}")
    public String getCart(@PathVariable("user_id") String user_id,
                            Model model){
        List<Cart> carts = new ArrayList<>();
        carts = cartService.getCart(user_id);
        int total = 0;
        for(int i = 0; i<carts.size(); i++){
            Products p = carts.get(i).getProducts();
            total += (carts.get(i).getQuantity()*p.getPrice());
        }
        model.addAttribute("carts", carts);
        model.addAttribute("total", total);
        return "cart";
    }
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>장바구니</title>
    <style>
        .clickable-row {
            cursor: pointer;
        }
        .quantity-controls {
            display: flex;
            align-items: center;
        }
        .quantity-controls button {
            border: 1px solid #ccc;
            background-color: #f0f0f0;
            padding: 5px;
            cursor: pointer;
        }
        .quantity-controls span {
            padding: 0 10px;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>장바구니</h2>
<table>
    <thead>
    <tr>
        <th>상품이름</th>
        <th>사진</th>
        <th>가격</th>
        <th>갯수</th>
    </tr>
    </thead>
    <tbody>
    <tr class="clickable-row" th:each="cart, iterStat : ${carts}">
        <td th:text="${cart.products.product_name}"></td>
        <td>
            <img th:src="@{'/images/uploads/' + ${cart.products.photo}}" alt="Product Image" height="200" width="200">
        </td>
        <td>
            <div class="quantity-controls">
                <button type="button" class="decrease-quantity" th:data-cart-item-id="${cart.id}">-</button>
                <span class="quantity" th:text="${cart.quantity}"></span>
                <button type="button" class="increase-quantity" th:data-cart-item-id="${cart.id}">+</button>
            </div>
        </td>
        <td th:text="${cart.products.price * cart.quantity}"><span></span></td>
    </tr>
    </tbody>
</table>
<h3>총 합계: <span id="totalAmount" th:text="${total}"></span></h3>
<script>
    $(document).ready(function() {
        function updatePriceAndTotal() {
            var totalAmount = 0;
            $('tbody tr').each(function() {
                var quantity = parseInt($(this).find('.quantity').text());
                var price = parseFloat($(this).find('td:nth-child(4)').text().replace('원', ''));
                var totalPrice = quantity * price;
                $(this).find('.total-price').text(totalPrice + '원');
                totalAmount += totalPrice;
            });
            $('#totalAmount').text(totalAmount + '원');
        }

        $('.increase-quantity, .decrease-quantity').on('click', function() {
            var cartItemId = $(this).data('cart-item-id');
            var quantitySpan = $(this).siblings('.quantity');
            var currentQuantity = parseInt(quantitySpan.text());
            var newQuantity = $(this).hasClass('increase-quantity') ? currentQuantity + 1 : currentQuantity - 1;

            if (newQuantity < 1) return; // 수량이 1보다 작아지지 않도록 함

            quantitySpan.text(newQuantity);

            // 서버에 수량 업데이트 요청
            $.post('/cart/update', { cartItemId: cartItemId, quantity: newQuantity }, function(response) {
                if (response === 'success') {
                    updatePriceAndTotal();
                } else {
                    alert('Failed to update cart item quantity.');
                }
            });
        });

        // 초기 로딩 시 가격 업데이트
        updatePriceAndTotal();
    });
</script>
</body>
</html>

수량을 업데이트 해야하므로 CartRepository와 CartService를 수정해야한다. CartRepository에서는 id를 통해 cart를 찾을 수 있도록 하고, CartService에서는 수량이 업데이트되면 그 값을 바로 cart타입에 저장할 수 있도록 해주자.

CartRepository

//앞전 함수는 생략

public Cart findById(int id){
        return em.find(Cart.class, id);
    }

CartService

public void updateCartItemQuantity(int cartItemId, int quantity) {
        Optional<Cart> cartItemOpt = Optional.ofNullable(cartRepository.findById(cartItemId));
        if (cartItemOpt.isPresent()) {
            Cart cartItem = cartItemOpt.get();
            cartItem.setQuantity(quantity);
            cartRepository.addCart(cartItem);
        }
    }

RestController

@PostMapping("/products/add")
    public String addProduct(
            @RequestParam(name = "name") String name,
            @RequestParam(name = "description") String description,
            @RequestParam(name = "price") int price,
            @RequestParam(name = "file") MultipartFile file,
            @RequestParam(name = "category") int category,
            HttpSession session
    ) {
        String userId = (String) session.getAttribute("userId");
        productService.saveProduct(name, description, price, file, category,userId);
        return "success";
    }

다음과 같이 정상 작동함을 볼 수 있었다.

다음 시간에는 중간점검으로 곳곳에 숨어있는 오류를 수정하도록 하자. 수정한 후에는 결제기능, 상품테이블 추가, 리뷰기능, 쿠폰, 위시리스트등을 추가해보자.

profile
모르는 것 정리하기

0개의 댓글