주문ㆍ결제 완료 시 해당 cart 숨기기

기여·2024년 8월 14일
0

소소한 개발팁

목록 보기
71/103

주문ㆍ결제 완료 시 해당 주문상품의 cart를 장바구니에서 단순히 삭제하면 db상 무결성 위배로 실패할 수 있다.
chat gpt의 추천 받아 soft delete 응용해서 해당 cart에 상태를 부여하고, 상태에 따라 cart 조작 또는 조회한다.

1, DB & Vo 중 cart 테이블에 isDel 필드(tinyint / int) 추가한다.
ㄴ 숨김처리 전에는 기본값=0이고, 장바구니에서 결제내역으로 이동 시 1로 업데이트

2, OrderMapper

// 주문 생성
		@Insert("INSERT INTO ord (paynum, uid, cartid, product_code, pquantity, "
		        + "oname, otel, omail, oadd, odetailAddress, "
		        + "omethod, ostatus, totalPay, pnames) "
		        + "VALUES (#{paynum}, #{uid}, #{cartid}, #{product_code}, #{pquantity}, "
		        + "#{oname}, #{otel}, #{omail}, #{oadd}, #{odetailAddress}, "
		        + "#{omethod}, #{ostatus}, #{totalPay}, #{pnames})")
		void createOrder(OrdVo order);	
	
		// 사용자별 주문된 cart 가삭제 (주문내역에 이동 - Soft Delete)
		@Update("<script>"
		        + "UPDATE cart SET isDel=1 "
		        + "WHERE uid = #{uid} "
		        + "AND cartid IN "
		        + "<foreach item='cartId' collection='cartIds' open='(' separator=',' close=')'>"
		        + "#{cartId}"
		        + "</foreach>"
		        + "</script>")
		void delSelectedCart(@Param("uid") String uid, @Param("cartIds") List<String> cartIds);

3, OrderService

//주문 생성	
	@Transactional
    public void createOrder(List<OrdVo> orderList, String uid, List<String> cartIds) {
		
		for (OrdVo order : orderList) {
	        // 각 주문을 DB에 삽입. 상세내역은 ctrl에서 처리
	        ordMapper.createOrder(order);       
	    }		
		// 사용자별 주문된 cart 가삭제 (주문내역에 이동 - Soft Delete)
	        ordMapper.delSelectedCart(uid, cartIds);
    }

이렇게 하면 결제 후 장바구니도 정리되어있다.

  • 아직 주문하지 않고 장바구니에 남아있는 상품 조회하기 위해 아래 sql문에 isDel=0 조건 추가한다.
    4, CartMapper
//uid별 전체 cart 보기
	@Select ("select cartid, uid, c.product_code, pquantity, "
			+ "pname, pprice, pdelifee, pimgStr, pstock "
			+ "from cart c join products p on c.product_code = p.product_code "
			+ "where uid=#{uid} "
			+ "AND isDel=0 "
			+ "order by cartid desc")
	
			List<CartVo> cart (CartVo vo);
  • 주문ㆍ결제 이력 있는 상품을 다시 장바구니에 담았을 때 숨겨지지 않도록 아래 select문에도 isDel=0 조건이 필요하다.
    4, CartMapper
//장바구니 담기
	
		//1. 사용자가 동일 제품 담은 레코드 조회
		@Select ("SELECT cartid FROM cart "
				+ "WHERE uid = #{uid} "
				+ "AND isDel=0 "
				+ "AND product_code = #{product_code}")
				
				String findCartidByUidAndProductCode(@Param("uid") String uid, 
				@Param("product_code") String product_code);
		
		/* isDel: cart에 있었던 건을 주문.결제 완료 시 가삭제 (isDel=1로 업뎃) 됨에 따라,
		해당 상품 다시 담았을 때 cart가 숨겨지지 않도록 isDel=0 조건 필요 */
		
		//2. 동일 건 없으면 새 레코드 삽입
		@Insert ("INSERT INTO cart (uid, product_code, pquantity) "
				+ "VALUES (#{uid}, #{product_code}, #{pquantity})")
				
				void addCart(CartVo vo);
		
		//3. 동일 건 있으면 해당 건의 주문수량 변경
		@Update ("UPDATE cart SET pquantity = pquantity + #{pquantity} "
				+ "WHERE cartid = #{cartid}")
				
				void updatePquantity(CartVo vo);

	//장바구니 담기 끝	
profile
기기 좋아하는 여자

0개의 댓글