hyeonga_code

reProject_39_위시리스트 추가/삭제 기능 작업 본문

Project_WEATHERWEAR

reProject_39_위시리스트 추가/삭제 기능 작업

hyeonga 2024. 1. 31. 06:59
반응형

 

reProject_38_sweetAlert2 적용하기, myBatis foreach문으로 반복 update, delete 적용

2024.01.30 기존에 작업했던 파일중 foreach문이 실행되지 않아 DAO.java에서 for문으로 작업한 기능들을 수정 alert()을 custom하기위해 sweetAlert을 적용했다. -- sweetAlert 적용 구글링을 하다가 참고한 사이

hyeonga493.tistory.com

2024.01.30

상품 상세 페이지에서 위시리스트에 추가, 삭제하는 기능과 장바구니에서 선택한 상품 리스트를 위시리스트에 추가하는 로직을 하나로 사용하기 위해 리스트에 담아 작업하는 코드로 작성했다. 회원 관련 기능은 다른 팀원이 작업하기로 했으나 상품 위시리스트 적용은 상품쪽 기능인 것 같아 일단 Product 관련 파일에 작업해두고 추후 프로젝트 통합 후 수정할 예정이다.

 

-- 상품상세/장바구니 페이지에서 상품 위시리스트에 추가

productInfo.jsp 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WeatherWear 사용자</title>
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com">
 
<!-- Vendor CSS Files -->
<link href="resources/client/ZenBlog/assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="resources/client/ZenBlog/assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
 
<!-- Swiper -->
 
<!-- Template Main CSS Files -->
<link href="resources/client/ZenBlog/assets/css/main.css" rel="stylesheet">
<link href="resources/client/ZenBlog/assets/css/variables.css" rel="stylesheet">
 
<style>
.mb-2 { width: 210px; height: 50px; overflow: hidden}
.col-lg-3 { height: 440px; padding-left: 5%;}
.selectOption {color: #909090; font-size: 17px;}
.optionbox { display: flex; flex-direction: column;}
.optionbox_p { width: 50%; }
.total_div {display: flex; justify-content: space-around; font-size:20px; font-weight: 300;}
.selectValue{ width:100%; display: flex; flex-direction:row;}
</style>
</head>
<body class="hold-transition sidebar-collapse layout-top-nav">
    <div class="wrapper">
        <%@ include file="../header.jsp" %>
        <main id="main">
            <section>
                <div class="container">
                    <div class="row">
                        <div class="col-md-9 post-content aos-init aos-animate" data-aos="fade-up">
                            <!-- ======= Single Post Content ======= -->
                            <div class="single-post border-bottom">
                                <div class="post-meta">
                                    <input type="hidden" name="stockList" value="${ optionList }">
                                    <input type="hidden" name="productName" value="${ product.productName }">
                                    <input type="hidden" name="productId" value="${ product.productId }">
                                    <input type="hidden" name="optionInfo" value="${ optionInfo }">
                                    <input type="hidden" name="productPrice" value="${ product.productPrice }">
                                    <input type="hidden" name="odTotal" value="0">
                                    <span class="date"><a href="main.do">HOME</a></span> 
                                    <span class="mx-1"></span> 
                                    <span><a href="#">OUTER</a></span>
                                </div>
                                <h1 class="mb-5">${ product.productName }</h1>
                                <img src="${ product.mainImage }" alt="" class="img-fluid"><br><br>
                            </div>
                            <div class="single-post"><br>
                                <c:forEach var="detail" items="${ detailImageList }">
                                    <img src="${ detail.detailImage }" alt="" class="img-fluid"><br><br>
                                </c:forEach>
                                <p>${ product.productContent }</p>
                            </div>
                            <!-- End Single Post Content -->
                        </div>
                        <!-- Category -->
                        <div class="col-md-3">
                            <div class="aside-block">
                                <div class="tab-content" id="pills-tabContent">
                                    <!-- Popular -->
                                    <div class="tab-pane fade show active" id="pills-popular" role="tabpanel" aria-labelledby="pills-popular-tab">
                                        <div class="post-entry-1 border-bottom">
                                            <h2>${ product.productName }</h2>
                                            <h4><fmt:formatNumber value="${ product.productPrice }" pattern="###,###"/></h4>
                                        </div>
                                        <div class="post-entry-1 border-bottom">
                                            <!-- Color -->
                                            <div class="post-meta"><span class="date">Color</span></div>
                                            <c:forEach var="color" items="${ optionInfo.optionColorList }">
                                                <button type="button" id="color_${ color }" class="btn btn-outline-primary colorOption optionBtn" value="${ color }" onclick="select(this)">${ color }</button>&nbsp;
                                            </c:forEach>
                                            <input type="hidden" name="colorValue">
                                            <br><br>
                                            <!-- Size -->
                                            <div class="post-meta"><span class="date">Size</span></div>
                                            <c:forEach var="size" items="${ optionInfo.optionSizeList }">
                                                <button type="button" id="size_${ size }"  class="btn btn-outline-primary sizeOption optionBtn" value="${ size }" onclick="select(this)">${ size }</button>&nbsp;
                                            </c:forEach>
                                            <input type="hidden" name="sizeValue">
                                            <br><br>
                                        </div>
                                        <div class="post-entry-1 border-bottom optionbox" id="optionbox">
                                            
                                        </div>
                                        <div class="post-entry-1 border-bottom total_div">
                                            <span><b>Total</b></span>
                                            <span class="totalPrice"></span>
                                            <br><br>
                                        </div>
                                        <div class="post-entry-1 border-bottom">
                                            <button type="button" class="btn btn-outline-primary" onclick="addWishList()">WishList</button>
                                            <button type="button" class="btn btn-outline-primary" onclick="addCart()">Add Cart</button>
                                            <button type="button" class="btn btn-primary" onclick="">Buy Now</button>
                                            <br><br>
                                        </div>
                                    </div>
                                    <!-- End Popular -->
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </main>
        <%@ include file="../footer.jsp" %>
    </div>
 
<script src="resources/client/ZenBlog/assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script  src="resources/util/plugins/sweetalert/jquery-lates.min.js"></script>
<script src="resources/util/plugins/sweetalert/sweetalert2.js"></script>
 
<!-- Template Main JS File -->
<script src="resources/client/ZenBlog/assets/js/main.js"></script>
 
<!-- sweetAlert (alert/confirm/toast) -->
<script src="resources/util/js/sweetalert.js"></script>
 
<script src="resources/client/js/product.js"></script>
<script src="resources/util/js/manageWishList.js"></script>
</body>
</html>

 

cart.jsp 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WeatherWear 사용자</title>
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com">
 
<!-- Vendor CSS Files -->
<link href="resources/client/ZenBlog/assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="resources/client/ZenBlog/assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
 
<!-- Swiper -->
 
<!-- Template Main CSS Files -->
<link href="resources/client/ZenBlog/assets/css/main.css" rel="stylesheet">
<link href="resources/client/ZenBlog/assets/css/variables.css" rel="stylesheet">
 
<link rel="stylesheet" href="/w2/resources/client/css/cart.css">
<style>
.mb-2 { width: 210px; height: 50px; overflow: hidden}
.col-lg-3 { height: 440px; padding-left: 5%;}
.productDiv:hover { cursor: pointer; }
</style>
</head>
<body class="hold-transition sidebar-collapse layout-top-nav">
    <div class="wrapper">
        <%@ include file="header.jsp" %>
        
        <main id="main">
            <section id="contact" class="contact mb-5">
                <div class="container aos-init aos-animate" data-aos="fade-up">
                    <div class="row">
                        <div class="col-lg-12 text-center mb-5">
                            <h1 class="page-title">CART</h1>
                        </div>
                    </div>
                    <div class="row">
                        <div class="cartList">
                            <div class="cart_table">
                                <ul class="cart_header">
                                    <li class="cart_head no">
                                        <button type="button" class="btn btn-sm btn-outline-primary checkAll" id="checkAll">전체선택</button>
                                    </li>
                                    <li class="cart_head con">PRODUCT</li>
                                    <li class="cart_head count">COUNT</li>
                                    <li class="cart_head price">PRICE</li>
                                </ul>
                                <c:forEach var="pro" items="${ cartList }">
            <!-- 상품마다 반복 시작 -->
                                <ul class="cart_content checklist">
                                    <li class="cart_con no">
                                        <input type="checkbox" id="checkbox_${ pro.cartId }" value="${ pro.cartId }" class="check">
                                    </li>
                                    <li class="cart_con con">
                                        <div class="product_info_div">
                                        <section class="product_image_section">
                                            <img class="product_image" src="${ pro.product.mainImage }" onclick="location.href='productInfo.do?productId=${ pro.productId }'">
                                        </section>
                                        <section class="product_content_section">
                                            <span class="order_product_name">
                                                <a href="productInfo.do?productId=${ pro.productId }" class="community_a">
                                                    ${ pro.product.productName }
                                                </a>
                                            </span>
                                            <span class="order_product_option">
                                                ${ pro.option.optionColor } / ${ pro.option.optionSize }
                                            </span>
                                        </section>
                                        </div>
                                    </li>
                                    <li class="cart_con count">
                                        <div id="div_${ pro.cartId }" class="cartValue">
                                            <button type="button" class="pro_btn" onclick="count(-2,'${ pro.cartId }')">-</button>
                                            <input class="pro_btn" name="${ pro.cartId }" value="${ pro.cartCnt }" onChange="count(this.value, '${ pro.cartId }')">
                                            <button type="button" class="pro_btn" onclick="count(-1,'${ pro.cartId }')">+</button>
                                            <input type="hidden" name="oriPrice_${ pro.cartId }" value="${ pro.product.productPrice }">
                                        </div>
                                    </li>
                                    <li class="cart_con price">
                                        <div id="price_${ pro.cartId }">
                            <!-- 상품가격*수량 합계 출력 -->
                                            <span id="totalPrice_${ pro.cartId }" class="pro_totalPrice"></span>
                            <!-- 상품가격*수량 합계 -->
                                            <input type="hidden" name="totalPrice_${ pro.cartId }">
                                        </div>
                                    </li>
                                </ul>
            <!-- 상품마다 반복 끝 -->
                                </c:forEach>
        
            <!-- 삭제 버튼 -->
                                <div class="cart_btn_div delete_btn">
                                    <input type="button" id="addWishList" class="cart_btn" value="관심상품으로 이동" onclick="moveWishList()">
                                    <input type="button" id="deleteSelected" class="cart_btn" value="선택 삭제" onclick="deleteSelect('delete')">
                                    <input type="button" id="deleteAll" class="cart_btn" value="전체 삭제" onclick="deleteAll()">
                                </div>
                            </div>
                            <div class="cart_table_option">
            <!-- 금액 -->
                                <div class="cart_total">
                                    <ul class="cart_total_ul">
                                        <li class="cart_total_li"><span>총 상품금액</span></li>
                                        <li class="cart_total_li val">
                                            <span id="totalPrice"></span>
                                            <input type="hidden" name="totalPrice">
                                        </li>
                                    </ul>
                                    <ul class="cart_total_ul buho">
                                        <li class="cart_total_buho">+</li>
                                    </ul>
                                    <ul class="cart_total_ul">
                                        <li class="cart_total_li"><span>총 배송비</span></li>
                                        <li class="cart_total_li val">
                                            <span id="deliPrice"></span>
                                            <input type="hidden" name="deliPrice">
                                        </li>
                                    </ul>
                                    <ul class="cart_total_ul buho">
                                        <li class="cart_total_buho">=</li>
                                    </ul>
                                    <ul class="cart_total_ul">
                                        <li class="cart_total_li"><span>결제 예정 금액</span></li>
                                        <li class="cart_total_li val">
                                            <span id="endPrice"></span>
                                            <input type="hidden" name="endPrice">
                                        </li>
                                    </ul>
                                </div>
            <!-- 주문 버튼 -->
                                <div class="cart_btn_div order_btn">
                                    <input type="button" id="orderSelected" class="cart_btn" value="선택 상품 주문" onclick="orderSelect()">
                                    <input type="button" id="orderAll" class="cart_btn" value="전체 상품 주문">
                                </div>
                            </div>
                        </div>    
                    </div>
                </div>
            </section>
        </main>
        
        <%@ include file="footer.jsp" %>
    </div>
 
<script src="resources/client/ZenBlog/assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script  src="resources/util/plugins/sweetalert/jquery-lates.min.js"></script>
<script src="resources/util/plugins/sweetalert/sweetalert2.js"></script>
 
<!-- Template Main JS File -->
<script src="resources/client/ZenBlog/assets/js/main.js"></script>
 
<!-- sweetAlert (alert/confirm/toast) -->
<script src="resources/util/js/sweetalert.js"></script>
 
<script src="resources/client/js/cart.js"></script>
<script src="resources/util/js/manageWishList.js"></script>
</body>
</html>

 

 

ClientConroller.java 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package com.w2.client.controller;
 
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.w2.product.service.ProductService;
import com.w2.util.ResponseDTO;
import com.w2.util.SearchOrderby;
 
import lombok.extern.slf4j.Slf4j;
 
@Slf4j
@Controller
public class ClientController {
    
    @Autowired
    private ProductService productService;
    
    @RequestMapping("test.do")
    public String test() {
        return "test";
    }
 
    /**
     * 메인 화면 호출
     * @return
     */
    @RequestMapping("main.do")
    public String mainView(Model model, HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        model.addAttribute("bestItem", productService.getMainProductList("best"));
        model.addAttribute("newItem", productService.getMainProductList("new"));
        //model.addAttribute("userInfo", session.getAttribute("userInfo"));
        return "main";
    }
 
    /**
     * 상품 목록 화면 호출
     * @return
     */
    @RequestMapping("productList.do")
    public String productList(Model model, @RequestParam(required = false, defaultValue = "1"int page,
            @RequestParam(required = false, defaultValue = "1"int range, @RequestParam(required = false, defaultValue = "productName"String searchType,
            @RequestParam(required = falseString keyword, @RequestParam(required = false, defaultValue = "productRegDate"String orderby, @ModelAttribute("search") SearchOrderby search) {
        // 검색
        model.addAttribute("search", search);
        if(search.getListSize()==10)
            search.setListSize(20);
        search.setSearchType(searchType);
        search.setKeyword(keyword);
        search.setOrderby(orderby);
        
        // 전체 게시글 개수
        int listCnt = productService.getProductListCnt(search);
        
        // 검색 페이지 정보
        search.pageInfo(page, range, listCnt);
        // 페이징
        model.addAttribute("pagination", search);
        // 화면 출력
        model.addAttribute("productList", productService.getProductList(search));
        
        return "product/productList";
    }
 
    /**
     * 상품 상세 화면 호출
     * @return
     */
    @RequestMapping("productInfo.do")
    public String productInfo(@RequestParam(value = "productId", required = false)String productId, Model model, HttpServletRequest request) {
        model.addAttribute("product", productService.getProduct(productId, model));
        return "product/productInfo";
    }
    
    /** 위시리스트 상품 추가 */
    @ResponseBody
    @PostMapping("wishListInsert.do")
    public ResponseDTO<String> wishListInsert(HttpSession session, @RequestBody List<String> checkList) throws IOException {
        int result;
 
        Integer statusCode = HttpStatus.OK.value();
        int code;
        String resultCode;
        String msg;
        String data = null;
        System.err.println("checkList : " + checkList);
        // 비로그인 상태인 경우
        if(session.getAttribute("session"== null) {
            code = -2;
            resultCode = "fail";
            msg = "로그인 후 이용할 수 있습니다.";
            data = "로그인하시겠습니까?";
        } else { // 로그인 상태인 경우
            Map<String, Object> client = new HashMap<String, Object>();
            client.put("productList", checkList);
            client.put("clientId", (String)session.getAttribute("session"));
            System.err.println("client : " + client);
 
            try {
                result = productService.insertWishList(client);
                if(result > 0) {
                    code = 1;
                    resultCode = "success";
                    msg = "위시리스트에 상품이 담겼습니다.";
                    data = "위시리스트로 이동하시겠습니까?";
                } else if (result == -3){
                    code = -3;
                    resultCode = "fail";
                    msg = "위시리스트에 이미 상품이 담겨있습니다.";
                    data = "위시리스트에서 삭제하시겠습니까?";
                } else {
                    code = -1;
                    resultCode = "fail";
                    msg = "오류가 발생했습니다. 다시 시도해주세요";
                }
            } catch (Exception e) {
                e.printStackTrace();
                code = -1;
                resultCode = "fail";
                msg = "오류가 발생했습니다. 다시 시도해주세요";
            }
        }
        return new ResponseDTO<String>(statusCode, code, resultCode, msg, data);
    }
    
    /** 위시리스트 상품 삭제 */
    @ResponseBody
    @PostMapping("wishListDelete.do")
    public ResponseDTO<String> wishListDelete(HttpSession session, @RequestBody List<String> checkList) throws IOException {
        int result;
 
        Integer statusCode = HttpStatus.OK.value();
        int code;
        String resultCode;
        String msg;
        
        // 비로그인 상태인 경우
        if(session.getAttribute("session"== null) {
            code = -2;
            resultCode = "fail";
            msg = "로그인 후 이용할 수 있습니다.\n 로그인하시겠습니까?";
        } else { // 로그인 상태인 경우
            Map<String, Object> client = new HashMap<String, Object>();
            client.put("productList", checkList);
            client.put("clientId", (String)session.getAttribute("session"));
            try {
                result = productService.deleteWishList(client);
                if(result > 0) {
                    code = 1;
                    resultCode = "success";
                    msg = "위시리스트에서 삭제되었습니다.";
                } else {
                    code = -1;
                    resultCode = "fail";
                    msg = "오류가 발생했습니다. 다시 시도해주세요";
                }
            } catch (Exception e) {
                e.printStackTrace();
                code = -1;
                resultCode = "fail";
                msg = "오류가 발생했습니다. 다시 시도해주세요";
            }
        }
        return new ResponseDTO<String>(statusCode, code, resultCode, msg, null);
    }
    
    
}

 

 

ProductService.java 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.w2.product.service;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.springframework.ui.Model;
 
import com.w2.product.ProductVO;
import com.w2.util.SearchOrderby;
 
public interface ProductService {
 
    // 관리자
    List<ProductVO> getProductList(SearchOrderby search);    // 상품 목록 가져오기
    int getProductListCnt(SearchOrderby search);            // 상품 목록 개수 가져오기
    int insertProduct(Map<String, Object> pro);            // 상품 등록
    HashMap<String, Object> getProduct(String productId, Model model);            // 상품 상세
    int updateProduct(Map<String, Object> pro);            // 상품 수정
    int updateProductStatus(List<Map<StringString>> checkList);    // 상품 상태 변경
    int deleteProduct(String productId);                    // 상품 삭제
    
    // 사용자
    List<ProductVO> getMainProductList(String string);        // 메인페이지 상품 리스트 가져오기
    int insertWishList(Map<String, Object> client);            // 위시리스트에 상품 추가
    int deleteWishList(Map<String, Object> client);            // 위시리스트 상품 삭제
    
}
 

 

 

ProductServiceImpl.java 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com.w2.product.service;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
 
import com.w2.product.ProductDAO;
import com.w2.product.ProductVO;
import com.w2.util.SearchOrderby;
 
@Transactional
@Service("ProductService")
public class ProductServiceImpl implements ProductService {
 
    @Autowired
    private ProductDAO productDAO;
    
    @Override
    public List<ProductVO> getProductList(SearchOrderby search) {
        return productDAO.getProductList(search);
    }
    
    @Override
    public int getProductListCnt(SearchOrderby search) {
        return productDAO.getProductListCnt(search);
    }
 
    @Override
    public int insertProduct(Map<String, Object> pro) {
        int result = -1;
        try {
            result = productDAO.insertProduct((ProductVO)pro.get("product"));
            result = productDAO.insertPrice(pro);
            result = productDAO.insertOption(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
 
    @Override
    public HashMap<String, Object> getProduct(String productId, Model model) {
        return productDAO.getProduct(productId, model);
    }
 
    @Override
    public int updateProduct(Map<String, Object> pro) {
        int result=-1;
        try {
            result = productDAO.updateProduct((ProductVO)pro.get("product"));
            result = productDAO.updatePrice(pro);
            result = productDAO.deleteOption((String)pro.get("productId"));
            if(result > 0) {
                result = productDAO.insertOption(pro);
                System.err.println("insert option : " + result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
 
    @Override
    public int deleteProduct(String productId) {
        int result = -1;
        result = productDAO.deletePrice(productId);
        result = productDAO.deleteOption(productId);
        result = productDAO.deleteProduct(productId);
        
        return result;
    }
 
    @Override
    public int updateProductStatus(List<Map<StringString>> checkList) {
        return productDAO.updateProductStatus(checkList);
    }
 
    @Override
    public List<ProductVO> getMainProductList(String type) {
        return productDAO.getMainProductList(type);
    }
 
    @Override
    public int insertWishList(Map<String, Object> client) {
        return productDAO.insertWishList(client);
    }
 
    @Override
    public int deleteWishList(Map<String, Object> client) {
        return productDAO.deleteWishList(client);
    }
}
 

 

 

ProductDAO.java 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package com.w2.product;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
 
import com.w2.util.SearchOrderby;
 
@Repository
public class ProductDAO {
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
 
    public List<ProductVO> getProductList(SearchOrderby search) {
        System.err.println("search : " + search);
        return sqlSessionTemplate.selectList("ProductDAO.getProductList", search);
    }
 
    public int getProductListCnt(SearchOrderby search) {
        System.err.println(">>search : " + search);
        return sqlSessionTemplate.selectOne("ProductDAO.getProductListCnt", search);
    }
 
    public int insertProduct(ProductVO product) {
        return sqlSessionTemplate.insert("ProductDAO.insertProduct", product);
    }
 
    public int insertPrice(Map<String, Object> pro) {
        return sqlSessionTemplate.insert("ProductDAO.insertPrice", pro);
    }
 
    public int insertOption(Map<String, Object> pro) {
        List<OptionVO> optionList = new ArrayList<OptionVO>();
        List<String> optionColorList = (List<String>)pro.get("optionColorList");
        List<String> optionSizeList = (List<String>)pro.get("optionSizeList");
        List<Integer> stockCntList = (List<Integer>)pro.get("stockCntList");
 
        
        for(int i=0; i<optionColorList.size(); i++) {
            for(int j=0; j<optionSizeList.size(); j++) {
                OptionVO option = new OptionVO();
                option.setProductId(((ProductVO)pro.get("product")).getProductId());
                option.setOptionColor(optionColorList.get(i));
                option.setOptionSize(optionSizeList.get(j));
                option.setStockCnt(stockCntList.get(((i+1)*(j+1)-1)));
                System.err.println("option : " + option);
                optionList.add(option);
            }
        }
        return sqlSessionTemplate.insert("ProductDAO.insertOption", optionList);
    }
 
    public HashMap<String, Object> getProduct(String productId, Model model) {
        model.addAttribute("optionInfo",sqlSessionTemplate.selectOne("ProductDAO.getOptionInfo", productId));
        model.addAttribute("optionList",sqlSessionTemplate.selectList("ProductDAO.getOptionList", productId));
        model.addAttribute("detailImageList",sqlSessionTemplate.selectList("ProductDAO.getDetailImage", productId));
        return sqlSessionTemplate.selectOne("ProductDAO.getProduct", productId);
    }
 
    public int updateProduct(ProductVO product) {
        return sqlSessionTemplate.update("ProductDAO.updateProduct", product);
    }
 
    public int updatePrice(Map<String, Object> pro) {
        return sqlSessionTemplate.update("ProductDAO.updatePrice", pro);
    }
 
    public int deleteOption(String productId) {
        return sqlSessionTemplate.delete("ProductDAO.deleteOption", productId);
    }
 
    public int deleteProduct(String productId) {
        return sqlSessionTemplate.delete("ProductDAO.deleteProduct", productId);
    }
 
    public int deletePrice(String productId) {
        return sqlSessionTemplate.delete("ProductDAO.deletePrice", productId);
    }
 
    public int updateProductStatus(List<Map<StringString>> checkList) {
        int result = -1;
        for(Map<StringString> product: checkList) {
            result = sqlSessionTemplate.update("ProductDAO.updateStatus", product);
            if(result < 1) {
                return -1;
            }
        }
        return result;
    }
 
    public List<ProductVO> getMainProductList(String type) {
        return sqlSessionTemplate.selectList("ProductDAO.getMainProductList", type);
    }
 
    public int insertWishList(Map<String, Object> client) {
        String result = sqlSessionTemplate.selectOne("ProductDAO.checkWishList", client);
        
        if(result != null) {
            return -3;
        }
        
        return sqlSessionTemplate.update("ProductDAO.insertWishList", client);
    }
 
    public int deleteWishList(Map<String, Object> client) {
        return sqlSessionTemplate.update("ProductDAO.deleteWishList", client);
    }
}
 

 

 

product-mapping.xml 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
                 
<mapper namespace="ProductDAO">
    <resultMap id="optionInfoResult" type="hashMap">
        <result property="optionColor" column="optionColor" />
        <result property="optionSize" column="optionSize" />
        <result property="stockCnt" column="stockCnt" />
    </resultMap>
    
    <resultMap id="insertResult" type="String">
        <result property="productId" column="productId" />
    </resultMap>
 
    <select id="getProductList" resultType="product">
        SELECT p.*, CONCAT(pm.imageDir, pm.imageName) as mainImage, pr.productPrice
        FROM product p
        LEFT JOIN product_image pm ON (p.productId = pm.imageBy AND pm.imageStatus = '대표')
        LEFT JOIN product_price pr ON (p.productId = pr.productId)
        <trim prefix="WHERE" prefixOverrides="AND|OR">
            <if test="keyword != null and keyword != ''">
                <if test="searchType == 'productName'">
                    AND productName like CONCAT('%', #{keyword}, '%')
                </if>
                <if test="searchType == 'productId'">
                    AND productId like CONCAT('%', #{keyword}, '%')
                </if>
            </if>
            <if test="keyword == null or keyword == ''">
                <if test="searchType == 'outer'">
                    AND p.productCate Like '11%'
                </if>
                <if test="searchType == 'tops'">
                    AND p.productCate Like '12%'
                </if>
                <if test="searchType == 'pants'">
                    AND p.productCate Like '13%'
                </if>
                <if test="searchType == 'skirts'">
                    AND p.productCate Like '14%'
                </if>
                <if test="searchType == 'dress'">
                    AND p.productCate Like '15%'
                </if>
            </if>
        </trim>
        ORDER BY ${ orderby }
        LIMIT #{startList}, #{listSize};
    </select>
    
    <select id="getProductListCnt" resultType="int">
        SELECT count(*)
        FROM product
        <trim prefix="WHERE" prefixOverrides="AND|OR">
            <if test="keyword != null and keyword != ''">
                <if test="searchType == 'productName'">
                    AND productName like CONCAT('%', #{keyword}, '%')
                </if>
                <if test="searchType == 'productId'">
                    AND productId like CONCAT('%', #{keyword}, '%')
                </if>
            </if>
            <if test="keyword == null or keyword == ''">
                <if test="searchType == 'outer'">
                    AND productCate Like '11%'
                </if>
                <if test="searchType == 'tops'">
                    AND productCate Like '12%'
                </if>
                <if test="searchType == 'pants'">
                    AND productCate Like '13%'
                </if>
                <if test="searchType == 'skirts'">
                    AND productCate Like '14%'
                </if>
                <if test="searchType == 'dress'">
                    AND productCate Like '15%'
                </if>
            </if>
        </trim>
        ORDER BY ${ orderby }
    </select>
    
    <select id="getProduct" resultType="hashmap">
        SELECT p.*, pr.*, CONCAT(pm.imageDir, pm.imageName) as mainImage
        FROM product p
        LEFT JOIN product_price pr ON(p.productId = pr.productId) 
        LEFT JOIN product_image pm ON (p.productId = pm.imageBy AND pm.imageStatus = '대표')
        WHERE p.productId=#{ productId }
    </select>
    
    <select id="getOptionInfo" resultType="hashmap">
        SELECT GROUP_CONCAT(DISTINCT optionColor SEPARATOR ',') as optionColorList, 
                GROUP_CONCAT(DISTINCT optionSize SEPARATOR ',') as optionSizeList
        FROM option_info
        WHERE productId=#{ productId }
    </select>
    
    <select id="getOptionList" resultMap="optionInfoResult">
        SELECT optionColor, optionSize, stockCnt
        FROM option_info
        WHERE productId=#{ productId }
    </select>
    
    <select id="getDetailImage" resultType="hashmap">
        SELECT CONCAT(imageDir, imageName) as detailImage
        FROM product_image
        WHERE imageBy=#{ productId } AND imageStatus='상세'
    </select>
    
<!-- 상품 등록 -->
    <insert id="insertProduct" parameterType="product" useGeneratedKeys="true" keyProperty="productId">
        INSERT INTO product(productId, productName, productContent, productCate, productSell) 
        VALUES(#{ productId }, #{ productName }, #{ productContent }, #{ productCate }, 'Y')
    </insert>
    
<!-- 가격 등록 -->    
    <insert id="insertPrice" parameterType="hashmap">
        INSERT INTO product_price(productId, productPrimeCost) 
        VALUES(#{ product.productId }, #{ productPrimeCost })
    </insert>
    
<!-- 옵션 등록 -->
    <insert id="insertOption" parameterType="list">
        INSERT INTO option_info(productId, optionColor, optionSize, stockCnt)
        VALUES
        <foreach collection="list" item="option" separator=",">
            (#{ option.productId }, #{ option.optionColor }, #{ option.optionSize }, #{ option.stockCnt })
        </foreach>
    </insert>
 
<!-- 상품 수정 -->
    <update id="updateProduct" parameterType="product">
        UPDATE product
        SET productName=#{ productName }, productContent=#{ productContent }
        WHERE productId=#{ productId }
    </update>
    
<!-- 가격 수정 -->    
    <update id="updatePrice" parameterType="hashmap">
        UPDATE product_price
        SET productPrimeCost=#{ productPrimeCost } 
        WHERE productId=#{ product.productId }
    </update>
 
<!-- 상품상태 수정 -->
    <update id="updateStatus" parameterType="hashmap">
        UPDATE product
        SET productSell=#{ productSell }
        WHERE productId=#{ productId }
    </update>
<!-- 옵션 수정 -->
    <update id="updateOption" parameterType="list">
        UPDATE option_info
        SET 
        (productId, optionColor, optionSize, stockCnt)
        VALUES
        <foreach collection="list" item="option" separator=",">
            (#{ option.productId }, #{ option.optionColor }, #{ option.optionSize }, #{ option.stockCnt })
        </foreach>
        WHERE productId=#{ productId }
    </update>
    
<!-- 옵션 삭제 -->
    <delete id="deleteOption">
        DELETE FROM option_info WHERE productId=#{ productId }
    </delete>
    
<!-- 상품가격 삭제 -->
    <delete id="deletePrice">
        DELETE FROM product_price WHERE productId=#{ productId }
    </delete>
    
<!-- 상품 삭제 -->
    <delete id="deleteProduct">
        DELETE FROM product WHERE productId=#{ productId }
    </delete>
 
    <select id="getMainProductList" parameterType="String" resultType="product">
        SELECT p.*, CONCAT(pm.imageDir, pm.imageName) as mainImage, pr.productPrice
        FROM product p
        LEFT JOIN product_image pm ON (p.productId = pm.imageBy AND pm.imageStatus = '대표')
        LEFT JOIN product_price pr ON (p.productId = pr.productId)
        ORDER BY 
        <choose>
            <when test="type == 'best'">p.productCnt DESC, p.productView DESC</when>
            <when test="type == 'new'">p.productRegDate DESC</when>
        </choose>
        LIMIT 0,8;
    </select>
    
    <select id="checkWishList" parameterType="hashmap" resultType="String">
        SELECT clientMarkList FROM client
        WHERE  clientId=#{ clientId } AND clientMarkList LIKE CONCAT('%', 
            <foreach collection="productList" item="product" index="index">
            #{ product }, 
            </foreach>
            '%');
    </select>
    
<!-- 위시리스트 추가 -->
    <update id="insertWishList" parameterType="hashmap">
        <foreach collection="productList" item="product" index="index">
            UPDATE client
            SET clientMarkList = CONCAT(clientMarkList, ',', #{ product })
            WHERE FIND_IN_SET(#{ product }, clientMarkList) = 0
            AND clientId=#{ clientId };
        </foreach>
    </update>
    
<!-- 위시리스트 삭제 -->
    <update id="deleteWishList" parameterType="hashmap">
        <foreach collection="productList" item="product" index="index">
        UPDATE client
        SET clientMarkList = TRIM(BOTH ',' FROM 
                                    REPLACE(CONCAT(',', clientMarkList, ','), 
                                    CONCAT(',', 
                                        #{ productId }, 
                                ','), ','))
        WHERE CONCAT(',', clientMarkList, ',') LIKE CONCAT('%,', #{ productId }, ',%') AND clientId=#{ clientId };
        </foreach>
    </update>
</mapper>
 
cs

 

 

manageWishList.js 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
 * 위시리스트 추가/제거
 */
 
 // 위시리스트 추가
function insertWishList(checkList){
    $.ajax({
        url: "/w2/wishListInsert.do",
        type: "POST",
        dataType: "json",
        async: true,
        data: JSON.stringify(checkList),
        dataType: "json",
        contentType: "application/json",
        success: function(res){
            if(res.code == -1) {
                playToast(res.message, 'error');
                return;
            } else if (res.code == -2){
                playConfirm(res.message, res.data, 'question''로그인하기''취소하기'"playToast('로그인 페이지로 이동(수정하기)', 'success')");
            } else if(res.code == 1) {
                playConfirm(res.message, res.data, 'question''위시리스트로 이동''계속 쇼핑하기'"playToast('위시리스트로 이동(수정하기)', 'success')"null);
            } else if(res.code == -3){
                Swal.fire({    // 매개변수 있어서 직접 작성
                    title: res.message,
                    text: res.data,
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: '위시리스트에서 삭제',
                    cancelButtonText: '취소하기',
                    reverseButtons: true// 버튼 순서 거꾸로
                }).then((result) => {
                    if(result.isConfirmed){
                        deleteWishList(checkList);
                    } else {
                        return;
                    }
                });
            }
        },
        error : function(error){
            playToast(error.message, 'error');
        }
    });
}
 
// 위시리스트 삭제
function deleteWishList(checkList){
    $.ajax({
        url: "/w2/wishListDelete.do",
        type: "POST",
        async: true,
        data: JSON.stringify(checkList),
        dataType: "json",
        contentType: "application/json",
        success: function(res){
            if(res.code == -1) {
                playToast(res.message, 'error');
                return;
            }else if (res.code == -2){
                playConfirm(res.message, res.data, 'question''로그인하기''취소하기'"playToast('로그인 페이지로 이동(수정하기)', 'success')"null);
            } 
            
            if(res.code == 1) {
                playToast(res.message, 'success');
            } 
            return;
        },
        error : function(error){
            playToast(error.message, 'error');
        }
    });
}

 

 

cart.js 수정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// 가격 지정
$(document).ready(function(){
    setPrice();
});
 
// 위시리스트로 이동
function moveWishList(){
    // 선택된 상품 없는 경우
    if(deleteList.length == 0){
        playToast("위시리스트에 추가할 상품을 선택해주세요"'warning');
        return;
    }
    insertWishList(deleteList);
    deleteSelect('addWishList');
}
 
// 선택 상품 주문
function orderSelect(){
    // 선택된 상품 없는 경우
    if(deleteList.length == 0){
        playToast("주문할 상품을 선택해주세요"'warning');
        return;
    }
    location.href="order.do?cartList=" + deleteList;
}
 
// ajax_상품 삭제
function delProduct(checkList, type){
    $.ajax({
        url: "/w2/cartDelete.do",
        type: "POST",
        async: true,
        data: JSON.stringify(checkList),
        dataType: "json",
        contentType: "application/json",
        success: function(res){
            if(type == 'delete')
                playToast(res.message, 'success');
            return;
        },
        error : function(error){
            playToast("ajax는 실패입니다."'error');
        }
    });
}
 
// 선택 상품 삭제
function deleteSelect(type){
    // 선택된 상품 없는 경우
    if(deleteList.length == 0){
        playToast("삭제할 상품을 선택해주세요"'warning');
        return;
    }
    
    let cartIdDiv;
    deleteList.forEach(check => {
        cartIdDiv = document.querySelector("#div_"+check);
        cartIdDiv.closest(".cart_content.checklist").remove();
    });
    delProduct(checkList, type);
    checkList.splice(0, checkList.length);
    deleteList.splice(0, deleteList.length);
    
    checkCounts = document.querySelectorAll(".check");
    setPrice();
}
 
// 전체 상품 삭제
function deleteAll(){
    checkCounts = document.querySelectorAll(".check");
    let cartIdDiv;
    
    // 선택된 상품 없는 경우
    checkNone(deleteList);
    
    checkCounts.forEach(check => {
        cartIdDiv = document.querySelector("#div_"+check.value);
        cartIdDiv.closest(".cart_content.checklist").remove();
    });
    delProduct(deleteList);
    checkList.splice(0, checkList.length);
    deleteList.splice(0, deleteList.length);
    
    checkCounts = document.querySelectorAll(".check");
    setPrice();
}
 
// 체크박스 적용
 $(document).ready(function(){
    // 전체선택
    $("#checkAll").click(function(){
        checkCounts = document.querySelectorAll(".check");
        
        if($(this).hasClass("checkAll")){    // 전체선택
            $(this).removeClass("checkAll").addClass("uncheckAll").addClass("active");
            $(this).text("전체해제");
            $(".check").prop("checked"true);
            
            checkCounts.forEach((check, index) => {
                pushList(checkList, check.value);
                pushList(deleteList, check.value);
            });
        } else if($(this).hasClass("uncheckAll")){    // 전체해제
            $(this).removeClass("active").removeClass("uncheckAll").addClass("checkAll");
            $(this).text("전체선택");
            $(".check").prop("checked"false);
            
            checkCounts.forEach(check => {
                spliceList(checkList, check.value);
                spliceList(deleteList, check.value);
            });
        }
        setPrice();
    });
    
    
    $(".check").click(function(){
        
        if(this.checked){
            // 첫 화면시 모두 추가되어 있는 상태
            if(checkList.length == $(".checklist .check").length){
                checkList.splice(0, checkList.length);
            }
            
            pushList(checkList, this.value);
            pushList(deleteList, this.value);
        } else {
            spliceList(checkList, this.value);
            spliceList(deleteList, this.value);
        }
        
        if($(".check:checked").length < $(".checklist .check").length){
            $("#checkAll").prop("checked"false);
        } else {
            $("#checkAll").prop("checked"true);
        }
        setPrice();
    });
});
 
// checkList/deleteList 에 추가
function pushList(list, Value){
    const index = list.indexOf(Value);
    
    // 인덱스에 없는 경우
    if(index == -1){
        list.push(Value);
    }
}
 
// checkList/deleteList 에서 제거
function spliceList(list, Value) {
    const index = list.indexOf(Value);
 
    // 인덱스에 있는 경우
    if(index !== -1){
        list.splice(index, 1);
    }
}
 
// list 상태 확인
function checkNone(list){
    if(list == ''){
        // 상품별 count li 태그 찾기
        const cartCounts = document.querySelectorAll(".cart_con.count");
        cartCounts.forEach(cartId => {
            list.push((cartId.querySelector(".cartValue").id).split("_")[1]);
        });
    }
}
 
// 값 설정
function setPrice(){
    let totalPriceVal = 0;
    let deliPriceVal = 3000;
 
    checkNone(checkList);
    
    // 상품별
    checkList.forEach(check => {
        const cartId = check;
 
        // 수량
        const countInput = document.querySelector("input[name='" + cartId + "']");
        
        // 기본 가격
        const oriPriceInput = document.querySelector("input[name='oriPrice_" + cartId + "']");
        
        const priceDiv = document.querySelector("#price_" + cartId);
        const pro_totalPriceSpan = priceDiv.querySelector("#totalPrice_" + cartId);
        const pro_totalPriceInput = priceDiv.querySelector("input");
        
        // (기본가격 * 수량)
        let pro_totalPrice = countInput.value * oriPriceInput.value
        
        pro_totalPriceSpan.innerHTML = setFormat(pro_totalPrice);
        pro_totalPriceInput.value = pro_totalPrice;
 
        // 총 상품 금액
        totalPriceVal += pro_totalPrice;                
    });
    
    // 배송비 조건부 무료
    if(totalPriceVal > 50000 || totalPriceVal == 0){
        deliPriceVal = 0;
    }
 
    // input
    const totalPriceInput = document.querySelector("input[name='totalPrice']");
    const deliPriceInput = document.querySelector("input[name='deliPrice']");
    const endPriceInput = document.querySelector("input[name='endPrice']");
    
    //span
    const totalPriceSpan = document.querySelector("#totalPrice");
    const deliPriceSpan = document.querySelector("#deliPrice");
    const endPriceSpan = document.querySelector("#endPrice");
    
    totalPriceInput.value = totalPriceVal;
    deliPriceInput.value = deliPriceVal;
    endPriceInput.value = totalPriceVal + deliPriceVal;
    
    totalPriceSpan.innerHTML = setFormat(totalPriceVal);
    deliPriceSpan.innerHTML = setFormat(deliPriceVal);
    endPriceSpan.innerHTML = setFormat(totalPriceVal + deliPriceVal);
}
 
let checkList = [];        // 주문 리스트
let deleteList = [];    // 삭제 리스트
 
// 체크박스 전체
let checkCounts = document.querySelectorAll(".check");
 
// 수량 변경
function count(num, name) {
    const countInput = document.querySelector("input[name='" + name + "']");
    const pro_oriPriceInput = document.querySelector("input[name='oriPrice_" + name + "']");
    const pro_totalPriceInput = document.querySelector("input[name='totalPrice_" + name + "']");
    const pro_totalPriceSpan = document.querySelector("#totalPrice_" + name);
    
    let cnt = parseInt(countInput.value);
    let pro_oriPrice = parseInt(pro_oriPriceInput.value);
    let pro_totalPrice = parseInt(pro_totalPriceInput.value);
    
    if (num == -1) { // 수량 증가
        cnt++;
    } else if (num == -2){ // 수량 감소
        cnt--;
    }
    
    pro_totalPrice = pro_oriPrice*num;
    
    if(cnt < 1){
        playToast("수량은 1개 이상이어야 합니다."'warning');
        cnt = 1;
        pro_totalPrice = pro_oriPrice;
    }
    
    countInput.value = cnt;
    pro_totalPriceInput.value = pro_totalPrice;
    pro_totalPriceSpan.innerHTML = setFormat(pro_totalPrice);
    
    setPrice();
 
    $.ajax({
        url: "/w2/cartUpdate.do",
        type: "POST",
        async: true,
        dataType: "text",
        data: JSON.stringify({
            cartId : name,
            cnt : cnt
        }),
        contentType: "application/json",
        success: function(result){
            playToast("수량이 변경되었습니다."'success');
        },
        error : function(error){
            playToast("ajax는 실패입니다."'error');
        }
    });
}
 
// 숫자 표기
function setFormat(num){
    let result = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return result;
}
 

 

>> 실행 

-- 위시리스트 추가 버튼 클릭시 비로그인인 경우 묻는 confirm 창 실행 

 

-- 세션 있는 경우

 

-- 위시리스트에 이미 상품이 있는 경우

 

-- 장바구니에 상품을 담은 경우

 

 

>> 선택 상품이 없는 경우 관심상품 버튼 클릭

 

 

>>> 체크 후 관심상품으로 이동 클릭 시 관심상품에 등록하고 장바구니에서 삭제됨 

 

 

reProject_40_Dropzone 이해하기, 관리자 상품 등록 이미지 업로드 적용, summernote S3 이미지 업로드 적용

2024.01.31 상품 등록시 상품 사진 업로드, 리뷰 이미지, 공지 이미지 등 이미지를 aws s3에 업로드하는 기능을 이전에는 input file 태그로 작성했었는데 dropzone을 사용하면 편리하고 깔끔한 스타일로

hyeonga493.tistory.com

 

반응형