hyeonga_code

reProject_17_쇼핑몰 상품 재고 반영, 장바구니 수량 변경 적용 구현 본문

Project_WEATHERWEAR

reProject_17_쇼핑몰 상품 재고 반영, 장바구니 수량 변경 적용 구현

hyeonga 2024. 1. 5. 05:59
반응형

 

 

 

reProject_16_ 장바구니 기능 구현 수정, 재고 수량 적용

reProject_15_주문 페이지, 주문 상세 페이지 작업 2024-01-02 주문페이지로 이동 시 session이 없는 경우(로그인하지 않은 경우) , cookie 값이 없는 경우(비회원 쿠키가 생성되지 않은 경우) 로그인/비회원

hyeonga493.tistory.com

 

2024.01.04

- 재고수량 적용

-- 재고수량이 없으면 select 옵션에 표시되지 않도록 작업하려 했으나, 전면적으로 수정해야하는 상황이라 재고가 없는 경우 alert을 띄우고 옵션선택이되지 않도록 처리하기로 함

 

client_productInfo.js 수정

// 옵션 수량 변경
function count(num, name) {
	var cnt = parseInt($("div[name='" + name + "'] input[name='cnt" + name + "']").val());
	var stCnt = parseInt($("div[name='" + name + "'] input[name='pro_" + name + "_cnt']").val());
	var odTotal = parseInt($("input[name='odTotal']").val());
	let proPrice = parseInt($("input[name='proPrice']").val());
	
	console.log("재고 : " + stCnt);
	console.log("num : " + num);
	
	if (num == -1) {
		odTotal += proPrice;
		cnt++;
	} else if (num == -2){
		odTotal -= proPrice;
		cnt--;
	} else {
		odTotal = proPrice*parseInt(num);
		console.log("odTotal : " + odTotal);
		cnt = num;
	}
	
	if (cnt < 1) {
		cnt = 0;
		$("div[name='" + name + "']").remove();
	} else if(cnt > stCnt){
		cnt = stCnt;
		alert("재고가 부족합니다.");
	}
	
	$("div[name='" + name + "'] input[name='cnt" + name + "']").val(cnt);
	$("input[name='odTotal']").val(odTotal);
}

// 옵션 선택
function select(selectElement) {
	let opList = getOpList();
	
	var color = document.getElementById("opColor").value;
	//console.log(color);
	var size = document.getElementById("opSize").value;
	//console.log(size);
	var odTotal = parseInt($("input[name='odTotal']").val());
	var proName = $("input[name='proName']").val();
	var proId = $("input[name='proId']").val();
	
	if(color === "SELECT" || size === "SELECT"){
		return;
	}
	
	// 재고 확인
	let stCnt = 0;
	
	opList.forEach(op => {
		
		if(op.get("opColor") == color && op.get("opSize") == size){
			stCnt = op.get("stCnt");	
			console.log("select stCnt : " + stCnt);	
		}
	
	});
	
	if (stCnt == '0'){
		cnt = 0;
		alert("재고가 부족합니다.");
		// 초기화
		document.getElementById("opColor").value = "SELECT";
		document.getElementById("opSize").value = "SELECT";
		return;
	}
	
	var name= color+size;
	
	if($("#"+name).length){
		alert("이미 선택한 옵션입니다.");
		count(-1, name);
	} else {
		var select = "";
		select += "<div name='" + color + size + "' id='" + color + size + "' class='selectValue'>"
				+ "<span class='proName'>" + proName + "</span>&nbsp;/&nbsp;" + color + "&nbsp;/&nbsp;" + size + "&nbsp;&nbsp;&nbsp;<br>"
				+ "<button type='button' class='pro_btn' onclick='count(-2,\"" + name +"\")'>-</button>"
				+ "<input class='pro_btn' id='cnt" + name + "'  name='cnt" + name + "' style='width:35px; height:27px; margin-left:3px; margin-right:3px; text-align:center;' max-value=" + stCnt + " onChange='count(this.value,\"" + name +"\")'>"
				+ "<button type='button' class='pro_btn' onclick='count(-1,\"" + name +"\")'>+</button>"
				+ "<input type='hidden' name='opId' value='" + proId + name + "'><input type='hidden' name='pro_" + name + "_cnt' value='" + stCnt + "'>"
				+ "<button id='id' name='" + name + "' class='pro_btn' onclick='deleteSelected(this)' style='flozat:right; margin-left:10px;'>X</button>"
				+ "</div>";

		count(-1, name);
		$("#selectOption").append(select);
	}			
	// 초기화
	document.getElementById("opColor").value = "SELECT";
	document.getElementById("opSize").value = "SELECT";
}

function moveToProductInfoMenu(){
	document.querySelector('.product_info_menu').scrollIntoView();
}

function deleteSelected(element){
	let cnt = $(element).parent().find("input[name='cnt" + element.name + "']").val();
	for(let i=0; i<cnt; i++){
		count(2, element.name);
	}
	$(element).parent().remove();
}
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
 
// 옵션 정보 가져오기
function getOpList(){
    let optionList = $("input[name='optionList']").val();
    let opList = [];
    
    optionList = optionList.slice(1-1);
    optionList = optionList.slice(1-1);
    
    let option = optionList.split("}, {");
    
    option.forEach(op => {
        let option = new Map();
        op = op.split(', ');
        
        for(let i=0; i<op.length; i++){
            let keyValue = op[i].split('=');
            option.set(keyValue[0], keyValue[1]);
        }
        
        opList.push(option);
    });
    return opList;
}
 
// 옵션 수량 변경
function count(num, name) {
    var cnt = parseInt($("div[name='" + name + "'] input[name='cnt" + name + "']").val());
    var stCnt = parseInt($("div[name='" + name + "'] input[name='pro_" + name + "_cnt']").val());
    var odTotal = parseInt($("input[name='odTotal']").val());
    let proPrice = parseInt($("input[name='proPrice']").val());
    
    console.log("재고 : " + stCnt);
    console.log("num : " + num);
    
    if (num == -1) {
        odTotal += proPrice;
        cnt++;
    } else if (num == -2){
        odTotal -= proPrice;
        cnt--;
    } else {
        odTotal = proPrice*parseInt(num);
        console.log("odTotal : " + odTotal);
        cnt = num;
    }
    
    if (cnt < 1) {
        cnt = 0;
        $("div[name='" + name + "']").remove();
    } else if(cnt > stCnt){
        cnt = stCnt;
        alert("재고가 부족합니다.");
    }
    
    $("div[name='" + name + "'] input[name='cnt" + name + "']").val(cnt);
    $("input[name='odTotal']").val(odTotal);
}
 
// 옵션 선택
function select(selectElement) {
    let opList = getOpList();
    
    var color = document.getElementById("opColor").value;
    //console.log(color);
    var size = document.getElementById("opSize").value;
    //console.log(size);
    var odTotal = parseInt($("input[name='odTotal']").val());
    var proName = $("input[name='proName']").val();
    var proId = $("input[name='proId']").val();
    
    if(color === "SELECT" || size === "SELECT"){
        return;
    }
    
    // 재고 확인
    let stCnt = 0;
    
    opList.forEach(op => {
        
        if(op.get("opColor"== color && op.get("opSize"== size){
            stCnt = op.get("stCnt");    
            console.log("select stCnt : " + stCnt);    
        }
    
    });
    
    if (stCnt == '0'){
        cnt = 0;
        alert("재고가 부족합니다.");
        // 초기화
        document.getElementById("opColor").value = "SELECT";
        document.getElementById("opSize").value = "SELECT";
        return;
    }
    
    var name= color+size;
    
    if($("#"+name).length){
        alert("이미 선택한 옵션입니다.");
        count(-1name);
    } else {
        var select = "";
        select += "<div name='" + color + size + "' id='" + color + size + "' class='selectValue'>"
                + "<span class='proName'>" + proName + "</span>&nbsp;/&nbsp;" + color + "&nbsp;/&nbsp;" + size + "&nbsp;&nbsp;&nbsp;<br>"
                + "<button type='button' class='pro_btn' onclick='count(-2,\"" + name +"\")'>-</button>"
                + "<input class='pro_btn' id='cnt" + name + "'  name='cnt" + name + "' style='width:35px; height:27px; margin-left:3px; margin-right:3px; text-align:center;' max-value=" + stCnt + " onChange='count(this.value,\"" + name +"\")'>"
                + "<button type='button' class='pro_btn' onclick='count(-1,\"" + name +"\")'>+</button>"
                + "<input type='hidden' name='opId' value='" + proId + name + "'><input type='hidden' name='pro_" + name + "_cnt' value='" + stCnt + "'>"
                + "<button id='id' name='" + name + "' class='pro_btn' onclick='deleteSelected(this)' style='flozat:right; margin-left:10px;'>X</button>"
                + "</div>";
 
        count(-1name);
        $("#selectOption").append(select);
    }            
    // 초기화
    document.getElementById("opColor").value = "SELECT";
    document.getElementById("opSize").value = "SELECT";
}
 
function moveToProductInfoMenu(){
    document.querySelector('.product_info_menu').scrollIntoView();
}
 
function deleteSelected(element){
    let cnt = $(element).parent().find("input[name='cnt" + element.name + "']").val();
    for(let i=0; i<cnt; i++){
        count(2, element.name);
    }
    $(element).parent().remove();
}
 
// 장바구니에 추가
function addCart(){
    // cartVO 객체를 가지는 리스트
    let proId = $("input[name='proId']").val();
    let list = addList(proId);
    console.log(proId);
    
    $.ajax({
        url: "/w2/clientAddCart.do",
        type: "POST",
        async: true,
        data: JSON.stringify(list),
        contentType: "application/json",
        success: function(response){
            if(confirm("장바구니에 상품이 담겼습니다.\n장바구니로 이동하시겠습니까?")) {
                 location.href="clientCart.do";
             } else {
                 reload:"clientProductInfo.do?proId="+proId;
             }
        },
        error : function(error){
            alert("실패");
        }
    });
}
 
// 상품 리스트에 담기
function addList(proId){
    let list = [];
    let productCounts = document.querySelectorAll(".selectValue");
 
    productCounts.forEach(product => {
        let colorSize = product.id;
        let cart = {}; // 객체 생성
        
        cart.proId = proId;
        cart.opId = product.querySelector("input[name='opId']").value;
        cart.caCnt = product.querySelector("input[name='cnt" + colorSize + "']").value;
        
        //console.log("pro : " + cart);
        
        list.push(cart);
    });
    
    return list;
}
 

 

 

>> 실행 

 

>>> 확인 클릭 시 select 옵션 초기화

 

 

 

-- 장바구니에서 수량 변경시 DB에도 적용시키기

---- 기존에 작업한것은 -.+ 버튼 클릭시에만 작동하도록 js 파일을 작성했으나 input 태그에서 직접 값을 입력하는 경우에도 변경되도록 구현

 

1. client_cart.js 수정

// 수량 변경
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);
	
	console.log("5. cnt : " + cnt);
	
	if (num == -1) { // 수량 증가
		console.log("8. 수량 증가 : ");
		cnt++;
	} else if (num == -2){ // 수량 감소
		console.log("9. 수량 감소 : ");
		cnt--;
	}
	
	pro_totalPrice = pro_oriPrice*num;
	
	if(cnt < 1){
		alert("수량은 1개 이상이어야 합니다.");
		cnt = 1;
		pro_totalPrice = pro_oriPrice;
	}
	
	countInput.value = cnt;
	pro_totalPriceInput.value = pro_totalPrice;
	pro_totalPriceSpan.innerHTML = setFormat(pro_totalPrice);
	
	console.log("10. countInput.value : " + cnt);
	console.log("11. pro_totalPriceInput.value : " + pro_totalPrice);
	
	setPrice();
	
	console.log("12. setPrice()");
	
	console.log("13. name : " + name);
	console.log("14. cnt : " + cnt);

	$.ajax({
		url: "/w2/clientUpdateCart.do",
		type: "POST",
		async: true,
		dataType: "text",
		data: JSON.stringify({
			caId : name,
			cnt : cnt
		}),
		contentType: "application/json",
		success: function(result){
			// 상단에 모달창으로 보여지기?
		},
		error : function(error){
			alert("ajax는 실패입니다.");
		}
	});

}
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
// 가격 지정
$(document).ready(function(){
    setPrice();
});
 
// ajax_상품 삭제
function delProduct(caId){
    $.ajax({
        url: "/w2/clientDeleteCart.do",
        type: "POST",
        async: true,
        dataType: "text",
        data: JSON.stringify({
            caId : caId
        }),
        contentType: "application/json",
        success: function(result){
            // 상단에 모달창으로 보여지기?
        },
        error : function(error){
            alert("ajax는 실패입니다.");
        }
    });
}
 
// 선택 상품 삭제
function deleteSelect(){
    // 선택된 상품 없는 경우
    if(deleteList.length == 0){
        alert("삭제할 상품을 선택해주세요");
        return;
    }
    
    let caIdDiv;
    deleteList.forEach(check => {
        caIdDiv = document.querySelector("#div_"+check);
        caIdDiv.closest(".cart_content.checklist").remove();
        delProduct(check);
    });
    
    checkList.splice(0, checkList.length);
    deleteList.splice(0, deleteList.length);
    
    checkCounts = document.querySelectorAll(".check");
    setPrice();
}
 
// 전체 상품 삭제
function deleteAll(){
    checkCounts = document.querySelectorAll(".check");
    let caIdDiv;
    
    // 선택된 상품 없는 경우
    checkNone(deleteList);
    
    checkCounts.forEach(check => {
        caIdDiv = document.querySelector("#div_"+check.value);
        caIdDiv.closest(".cart_content.checklist").remove();
        delProduct(check.value);
    });
    checkList.splice(0, checkList.length);
    deleteList.splice(0, deleteList.length);
    
    checkCounts = document.querySelectorAll(".check");
    setPrice();
}
 
// 체크박스 적용
$(function(){
    $("#checkAll").click(function(){
        $(".check").prop("checked"this.checked);
        checkCounts = document.querySelectorAll(".check");
        
        if(this.checked){
            checkCounts.forEach((check, index) => {
                pushList(checkList, check.value);
                pushList(deleteList, check.value);
            });
        } else {
            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 caId = check;
 
        // 수량
        const countInput = document.querySelector("input[name='" + caId + "']");
        
        // 기본 가격
        const oriPriceInput = document.querySelector("input[name='oriPrice_" + caId + "']");
        
        const priceDiv = document.querySelector("#price_" + caId);
        const pro_totalPriceSpan = priceDiv.querySelector("#totalPrice_" + caId);
        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);
    
    console.log("5. cnt : " + cnt);
    
    if (num == -1) { // 수량 증가
        console.log("8. 수량 증가 : ");
        cnt++;
    } else if (num == -2){ // 수량 감소
        console.log("9. 수량 감소 : ");
        cnt--;
    }
    
    pro_totalPrice = pro_oriPrice*num;
    
    if(cnt < 1){
        alert("수량은 1개 이상이어야 합니다.");
        cnt = 1;
        pro_totalPrice = pro_oriPrice;
    }
    
    countInput.value = cnt;
    pro_totalPriceInput.value = pro_totalPrice;
    pro_totalPriceSpan.innerHTML = setFormat(pro_totalPrice);
    
    console.log("10. countInput.value : " + cnt);
    console.log("11. pro_totalPriceInput.value : " + pro_totalPrice);
    
    setPrice();
    
    console.log("12. setPrice()");
    
    console.log("13. name : " + name);
    console.log("14. cnt : " + cnt);
 
    $.ajax({
        url: "/w2/clientUpdateCart.do",
        type: "POST",
        async: true,
        dataType: "text",
        data: JSON.stringify({
            caId : name,
            cnt : cnt
        }),
        contentType: "application/json",
        success: function(result){
            // 상단에 모달창으로 보여지기?
        },
        error : function(error){
            alert("ajax는 실패입니다.");
        }
    });
 
}
 
// 숫자 표기
function setFormat(num){
    let result = num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return result;
}

 

 

 

 

2. ClientCartController.java 수정

---- ajax 응답이 계속 반복되는 코드로 임시 모듈로 작업

---- 세션과 쿠키 작업이 계속 반복되어 임시 모듈로 작업

	/** 장바구니 수량 변경 */
	@PostMapping("clientUpdateCart.do")
	public void clientUpdateCart(@RequestBody Map<String, String> data, HttpSession session, ClientCartVO cartvo, HttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println("1. [ Client Cart Controller ] clientUpdateCart");
		
		setUser(session, request, response, cartvo);
		cartvo.setCaId((String)data.get("caId"));
		cartvo.setCaCnt(Integer.parseInt(data.get("cnt")));
		
		int result = cartService.clientUpdateCart(cartvo);

		setResponse(response, result, "application/json");
	}
	
	public ClientCartVO setUser(HttpSession session, HttpServletRequest request, HttpServletResponse response, ClientCartVO cartvo) {
		System.out.println(">> setUser()");

		// 비로그인 상태인 경우
		if(session.getAttribute("session") == null) {
			String ckId = ClientCookie.setCookie(request, response);
			
			cartvo.setCkId(ckId);
		} else { // 로그인 상태인 경우
			cartvo.setClientId((String)session.getAttribute("session"));
		}
		return cartvo;
	}
	
	// ajax 응답
	public HttpServletResponse setResponse(HttpServletResponse response, Object result, String type) throws IOException {
		System.out.println(">> setResponse()");
		
		response.setContentType(type);
		response.getWriter().write(String.valueOf(result));
		
		return response;
	}
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
package com.w2.client.controller;
 
import java.io.IOException;
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
 
import com.w2.client.cart.ClientCartService;
import com.w2.client.cart.ClientCartVO;
import com.w2.util.ClientCookie;
 
@Controller
public class ClientCartController {
    
    @Autowired
    private ClientCartService cartService;
 
    @PostMapping("clientTest.do")
    public ResponseEntity<String> handleRequest(@RequestBody List<ClientCartVO> data) {
        // 전송된 데이터 처리
        System.out.println(data);
        for(int i=0; i<data.size(); i++) {
            System.out.println("data " + i + " : " + data.get(i));
            System.out.println("ca : " + data.get(i).getOpId());
        }
        // 처리 결과 반환
        return ResponseEntity.ok("Success");
    }
    
    /** 장바구니에 상품 추가 */
    @PostMapping("clientAddCart.do")
    public void clientAddCart(@RequestBody List<ClientCartVO> productList, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("1. [ Client Cart Controller ] clientAddCart : " + productList);
        
        // 비로그인 상태인 경우
        if(session.getAttribute("session"== null) {
            String ckId = ClientCookie.setCookie(request, response);
            
            productList.get(0).setCkId(ckId);
        } else { // 로그인 상태인 경우
            productList.get(0).setClientId((String)session.getAttribute("session"));
        }
        
        int result = cartService.clientAddCart(productList);
 
        response.setContentType("application/json");
        response.getWriter().write(String.valueOf(result));
    }
    
    /** 장바구니 상품 삭제 */
    @PostMapping("clientDeleteCart.do")
    public void clientDeleteCart(@RequestBody Map<StringString> data, HttpSession session, ClientCartVO cartvo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("1. [ Client Cart Controller ] clientAddCart");
        
        setUser(session, request, response, cartvo);
        
        int result = cartService.clientDeleteCart((String)data.get("caId"));
 
        setResponse(response, result, "application/json");
    }
    
    /** 장바구니 수량 변경 */
    @PostMapping("clientUpdateCart.do")
    public void clientUpdateCart(@RequestBody Map<StringString> data, HttpSession session, ClientCartVO cartvo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("1. [ Client Cart Controller ] clientUpdateCart");
        
        setUser(session, request, response, cartvo);
        cartvo.setCaId((String)data.get("caId"));
        cartvo.setCaCnt(Integer.parseInt(data.get("cnt")));
        
        int result = cartService.clientUpdateCart(cartvo);
 
        setResponse(response, result, "application/json");
    }
    
    public ClientCartVO setUser(HttpSession session, HttpServletRequest request, HttpServletResponse response, ClientCartVO cartvo) {
        System.out.println(">> setUser()");
 
        // 비로그인 상태인 경우
        if(session.getAttribute("session"== null) {
            String ckId = ClientCookie.setCookie(request, response);
            
            cartvo.setCkId(ckId);
        } else { // 로그인 상태인 경우
            cartvo.setClientId((String)session.getAttribute("session"));
        }
        return cartvo;
    }
    
    // ajax 응답
    public HttpServletResponse setResponse(HttpServletResponse response, Object result, String type) throws IOException {
        System.out.println(">> setResponse()");
        
        response.setContentType(type);
        response.getWriter().write(String.valueOf(result));
        
        return response;
    }
}

 

 

 

 

3. ClientService.java 인터페이스 수정

	// 장바구니 상품 수량 변경
	int clientUpdateCart(ClientCartVO cartvo);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.w2.client.cart;
 
import java.util.List;
 
public interface ClientCartService {
 
    // 장바구니에 상품 추가
    int clientAddCart(List<ClientCartVO> productList);
 
    // 장바구니 목록 불러오기
    List<ClientCartVO> getClientCartList(ClientCartVO cartvo);
 
    // 장바구니 상품 삭제
    int clientDeleteCart(String string);
 
    // 장바구니 상품 수량 변경
    int clientUpdateCart(ClientCartVO cartvo);
}
 
 
 

 

 

 

 

4. ClientServiceImpl.java 클래스 수정

	// 장바구니 상품 수량 변경
	@Override
	public int clientUpdateCart(ClientCartVO cartvo) {
		System.out.println("2. [ ClientCartService ] clientUpdateCart");
		
		return cartDAO.clientUpdateCart(cartvo);
	}
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
package com.w2.client.cart.impl;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.w2.client.cart.ClientCartDAO;
import com.w2.client.cart.ClientCartService;
import com.w2.client.cart.ClientCartVO;
 
@Service("cartService")
public class ClientCartServiceImpl implements ClientCartService {
 
    @Autowired
    private ClientCartDAO cartDAO;
    
    // 장바구니에 상품 추가
    @Override
    public int clientAddCart(List<ClientCartVO> productList) {
        System.out.println("2. [ ClientCartService ] clientAddCart");
        
        return cartDAO.clientAddCart(productList);
    }
 
    // 장바구니 목록 불러오기
    @Override
    public List<ClientCartVO> getClientCartList(ClientCartVO cartvo) {
        System.out.println("2. [ ClientCartService ] getClientCartList");
        
        return cartDAO.getClientCartList(cartvo);
    }
 
    // 장바구니 상품 삭제
    @Override
    public int clientDeleteCart(String caId) {
        System.out.println("2. [ ClientCartService ] clientDeleteCart");
        
        return cartDAO.clientDeleteCart(caId);
    }
 
    // 장바구니 상품 수량 변경
    @Override
    public int clientUpdateCart(ClientCartVO cartvo) {
        System.out.println("2. [ ClientCartService ] clientUpdateCart");
        
        return cartDAO.clientUpdateCart(cartvo);
    }
 
}
 
 
 

 

 

 

 

5. CilentDAO.java 클래스 수정

	// 장바구니 상품 수량 변경
	public int clientUpdateCart(ClientCartVO cartvo) {
		System.out.println("3. [ CartDAO ] clientUpdateCart");
		
		return sqlSessionTemplate.update("CartDAO.clientUpdateCart", cartvo);
	}
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
package com.w2.client.cart;
 
import java.util.List;
 
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
@Repository
public class ClientCartDAO {
 
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
    
    // 장바구니에 상품 추가
    public int clientAddCart(List<ClientCartVO> productList) {
        System.out.println("3. [ CartDAO ] clientAddCart");
        String ckId = null;
        String clientId = null;
        
        for(int i=0; i<productList.size(); i++) {
            if(productList.get(0).getClientId() != null) {
                clientId = productList.get(0).getClientId();
            } else if(productList.get(0).getCkId() != null) {
                ckId = productList.get(0).getCkId();
            }
            
            ClientCartVO cartvo = (ClientCartVO)productList.get(i);
            
            if(i>0) {
                if(clientId != null) {
                    productList.get(i).setClientId(clientId);
                } else if (ckId != null) {
                    productList.get(i).setCkId(ckId);
                }    
            }
            
            int check = sqlSessionTemplate.selectOne("CartDAO.clientCheckCart", cartvo);
 
            // 이미 장바구니에 있는 상품인 경우
            if (check == 1) {
                // 같은 쿠키값 가진 상품 만료시간 업데이트
                if(cartvo.getCkId() != null) {
                    System.out.println(">> 다른 상품 만료시간 업데이트");
                    sqlSessionTemplate.update("CartDAO.clientUpdateCookie", cartvo);
                }
                
                System.out.println(">> 상품 수량 변경");
                sqlSessionTemplate.update("CartDAO.clientUpdateCart", cartvo);
            }else {
                System.out.println(">> 상품 추가");
                sqlSessionTemplate.insert("CartDAO.clientAddCart", cartvo);
            }
        }
        return 1;
    }
 
    // 장바구니 목록 불러오기
    public List<ClientCartVO> getClientCartList(ClientCartVO cartvo) {
        System.out.println("3. [ CartDAO ] getClientCartList");
 
        return sqlSessionTemplate.selectList("CartDAO.getClientCartList", cartvo);
    }
 
    // 장바구니 상품 삭제
    public int clientDeleteCart(String caId) {
        System.out.println("3. [ CartDAO ] clientDeleteCart");
 
        return sqlSessionTemplate.delete("CartDAO.clientDeleteCart", caId);
    }
 
    // 장바구니 상품 수량 변경
    public int clientUpdateCart(ClientCartVO cartvo) {
        System.out.println("3. [ CartDAO ] clientUpdateCart");
        
        return sqlSessionTemplate.update("CartDAO.clientUpdateCart", cartvo);
    }
 
}
 

 

 

 

 

 

6. client-mapping.xml 파일 수정

<!-- 장바구니에 상품 수량 수정 -->
	<update id="clientUpdateCart" parameterType="clientCart">
		UPDATE cart SET caCnt=#{ caCnt }
		<where>
			caId = #{ caId }
			<if test="clientId != null">
				AND cId = #{ clientId }
			</if>
			<if test="clientId == null">
				AND ckId = #{ ckId }
			</if>
		</where>
	</update>
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
<?xml version="1.0" encoding="UTF-8"?>
 
<!-- MyBatis 다운 파일 PDF 에서 붙여넣은 내용입니다. -->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
                 
<mapper namespace="CartDAO">
    <resultMap type="com.w2.client.cart.ClientCartVO" id="clientCart">
        <id property="caId" column="caId" />
        <result property="proId" column="proId" />
        <result property="clientId" column="cId" />
        <result property="opId" column="opId" />
        <result property="caDate" column="caDate" />
        <result property="caCnt" column="caCnt" />
        <result property="ckId" column="ckId" />
        <result property="ckLimit" column="ckLimit" />
        
        <collection property="provo" resultMap="provoResult" />
        <collection property="opvo" resultMap="opvoResult" />
    </resultMap>
    
    <resultMap type="com.w2.product.ProductVO" id="provoResult">
        <result property="proId" column="proId" />
        <result property="proCate" column="proCate" />
        <result property="proName" column="proName" />
        <result property="proContent" column="proContent" />
        <result property="proRegDate" column="proRegDate" />
        <result property="proSell" column="proSell" />
        <result property="proCnt" column="proCnt" />
        <result property="proView" column="proView" />
        <result property="proLike" column="proLike" />
        
        <collection property="imvo" resultMap="imvoResult" />
        <collection property="pricevo" resultMap="pricevoResult" />
    </resultMap>
    
    <resultMap type="com.w2.product.ProductPriceVO" id="pricevoResult">
        <result property="proId" column="proId" />
        <result property="proPrimeCost" column="proPrimeCost" />
        <result property="proCost" column="proCost" />
        <result property="proPrice" column="proPrice" />
        <result property="proTax" column="proTax" />
        <result property="proMargin" column="proMargin" />
        <result property="proAddCost" column="proAddCost" />
    </resultMap>
    
    <resultMap type="com.w2.util.ImageVO" id="imvoResult">
        <result property="imageId" column="imageId" />
        <result property="imageName" column="imageName" />
        <result property="imageDir" column="imageDir" />
        <result property="imageStatus" column="imageStatus" />
        <result property="imageBy" column="imageBy" />
    </resultMap>
    
    <resultMap type="com.w2.product.OptionVO" id="opvoResult">
        <result property="proId" column="proId" />
        <result property="opColor" column="opColor" />
        <result property="opSize" column="opSize" />
        <result property="opId" column="opId" />
        <result property="stCnt" column="stCnt" />
    </resultMap>
    
<!-- 장바구니 목록 조회 -->
    <select id="getClientCartList" parameterType="clientCart" resultMap="clientCart">
        SELECT pro.proId, pro.proName, ca.opId,
                im.imageDir, im.imageName, 
                op.opColor, op.opSize, pri.proPrice, 
                ca.caCnt, ca.caId,
                <if test="clientId != null">
                    cId
                </if>
                <if test="clientId == null">
                    ckId
                </if>
        FROM cart ca
        LEFT JOIN product pro ON ca.proId = pro.proId
        LEFT JOIN product_image im ON ca.proId = im.imageBy AND im.imageStatus='대표'
        LEFT JOIN option_info op ON ca.opId = op.opId
        LEFT JOIN product_price pri ON ca.proId = pri.proId
        <where>
            <if test="clientId != null">
                cId = #{ clientId }
            </if>
            <if test="clientId == null">
                ckId = #{ ckId }
            </if>
        </where>
    </select>
    
<!-- 장바구니 중복 상품 확인 -->
    <select id="clientCheckCart" parameterType="clientCart" resultType="int">
        SELECT COUNT(*) FROM cart
        <where>
            <if test="clientId != null">
                cId = #{ clientId }
            </if>
            <if test="clientId == null">
                ckId = #{ ckId }
            </if>
            AND proId = #{ proId } AND opId = #{ opId }
        </where>
    </select>
 
<!-- 장바구니에 상품 추가 -->
    <insert id="clientAddCart" parameterType="clientCart">
        INSERT INTO cart (proId, opId, caCnt, 
            <if test="clientId != null">
                cId
            </if>
            <if test="clientId == null">
                ckId
            </if>
        ) VALUES ( #{ proId }, #{ opId }, #{ caCnt },
            <if test="clientId != null">
                #{ clientId }
            </if>
            <if test="clientId == null">
                #{ ckId }
            </if>
        )
    </insert>
    
<!-- 장바구니에 상품 수량 수정 -->
    <update id="clientUpdateCart" parameterType="clientCart">
        UPDATE cart SET caCnt=#{ caCnt }
        <where>
            caId = #{ caId }
            <if test="clientId != null">
                AND cId = #{ clientId }
            </if>
            <if test="clientId == null">
                AND ckId = #{ ckId }
            </if>
        </where>
    </update>
    
<!-- 같은 쿠키 값 가진 장바구니 만료시간 수정 -->
    <update id="clientUpdateCookie" parameterType="clientCart">
        UPDATE cart SET ckLimit = (CURRENT_TIMESTAMP + INTERVAL 2 DAY)
        WHERE ckId = #{ ckId }
    </update>
    
<!-- 장바구니 상품 삭제 -->
    <delete id="clientDeleteCart" parameterType="String">
        DELETE FROM cart WHERE caId=#{ caId }
    </delete>    
</mapper>

 

 

>> 실행

 

>>> 옵션 [ 베이지 / S ] 상품의 수량을 + 버튼으로 증가 후 새로고



>>> 두 번째 옵션 [ 그린 / S ] 상품의 input 태그에서 수량을 6으로 변경한 후 새로고침

 

 

reProject_18_Spring Schedular 이용해서 만료된 쿠키에 적용하기 구현 준비

reProject_17_쇼핑몰 상품 재고 반영, 장바구니 수량 변경 적용 구현 reProject_16_ 장바구니 기능 구현 수정, 재고 수량 적용 reProject_15_주문 페이지, 주문 상세 페이지 작업 2024-01-02 주문페이지로 이동

hyeonga493.tistory.com

 

반응형