Skip to content

Commit

Permalink
카트문제, 제품 아이디별 조회
Browse files Browse the repository at this point in the history
  • Loading branch information
qogustj committed Sep 15, 2023
1 parent c64cee1 commit f30e4c8
Show file tree
Hide file tree
Showing 11 changed files with 141 additions and 63 deletions.
5 changes: 4 additions & 1 deletion src/main/java/gip/sever/ResponseMessage.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
@Getter
@RequiredArgsConstructor
public enum ResponseMessage {
POST_PRODUCT_SUCCESS("장바구니에 제품 추가를 완료 했습니다."),
GET_ARTICLE_SUCCESS("기사 조회를 완료 했습니다."),
GET_PRODUCT_SUCCESS("제품 조회를 완료 했습니다."),
GET_CART_SUCCESS("장바구니 조회를 완료 했습니다."),
Expand All @@ -15,7 +16,9 @@ public enum ResponseMessage {
MAIL_SUCCESS("데모 신청이 완료되었습니다"),
ADDITIONAL_INFO_NEED("추가정보 기입이 필요합니다"),
LOGIN_SUCCESS("로그인 성공"),
ADDITIONAL_INFO_SUCCESS("추가 정보 기입이 완료되었습니다");
ADDITIONAL_INFO_SUCCESS("추가 정보 기입이 완료되었습니다"),
DELETE_PRODUCT_SUCCESS("제품 삭제가 완료되었습니다"),
FALSE_PRODUCT("제품이 이미 있습니다");
private final String message;


Expand Down
22 changes: 14 additions & 8 deletions src/main/java/gip/sever/controller/CartController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@


import gip.sever.dto.request.CartRequest;
import gip.sever.dto.response.CartResponse;
//import gip.sever.dto.response.CartResponse;
import gip.sever.dto.response.CartResponseDto;
import gip.sever.global.response.SuccessResponse;
import gip.sever.service.CartService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import static gip.sever.ResponseMessage.GET_CART_SUCCESS;
import static gip.sever.ResponseMessage.*;

@RestController
@RequiredArgsConstructor
Expand All @@ -20,20 +20,26 @@ public class CartController {
private final CartService cartService;

@PostMapping("/add")
public void addToCart(@RequestBody CartRequest cartRequest) throws Exception {
cartService.addToCart(cartRequest.getMemberId(), cartRequest.getProductId());
public ResponseEntity<SuccessResponse<String>> addToCart(@RequestBody CartRequest cartRequest) throws Exception {
boolean add =cartService.addToCart(cartRequest.getMemberId(), cartRequest.getProductId());
if (add) {
return ResponseEntity.ok(SuccessResponse.create(POST_PRODUCT_SUCCESS.getMessage()));
} else {
return ResponseEntity.ok(SuccessResponse.creat(FALSE_PRODUCT.getMessage()));
}
}


@DeleteMapping("/remove")
public void removeFromCart(@RequestBody CartRequest cartRequest) throws Exception {
public ResponseEntity<SuccessResponse<String>> removeFromCart(@RequestBody CartRequest cartRequest) throws Exception {
cartService.removeFromCart(cartRequest.getMemberId(), cartRequest.getProductId());
return ResponseEntity.ok(SuccessResponse.create(DELETE_PRODUCT_SUCCESS.getMessage()));
}


@GetMapping("/{memberId}")
public ResponseEntity<SuccessResponse<CartResponse>> getCart(@PathVariable Long memberId) throws Exception {
return ResponseEntity.ok(SuccessResponse.create(GET_CART_SUCCESS.getMessage(), cartService.getCart(memberId)));
public CartResponseDto.CartResponse getCart(@PathVariable Long memberId) throws Exception {
return cartService.getCart(memberId);

}

Expand Down
4 changes: 2 additions & 2 deletions src/main/java/gip/sever/domain/Cart.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package gip.sever.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.NoArgsConstructor;

Expand All @@ -15,9 +16,8 @@ public class Cart {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "cart_id")
private Long id;

@OneToMany(mappedBy = "cart", cascade = CascadeType.ALL, orphanRemoval = true)
private List<CartItem> cartItems = new ArrayList<>();
private List<CartItem> cartItems = new ArrayList<>();

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id")
Expand Down
1 change: 0 additions & 1 deletion src/main/java/gip/sever/domain/CartItem.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ public class CartItem {
@JoinColumn(name = "cart_id")
private Cart cart;


@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "product_id")
private Product product;
Expand Down
2 changes: 2 additions & 0 deletions src/main/java/gip/sever/domain/Product.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
@NoArgsConstructor
Expand Down
31 changes: 0 additions & 31 deletions src/main/java/gip/sever/dto/response/CartResponse.java

This file was deleted.

75 changes: 75 additions & 0 deletions src/main/java/gip/sever/dto/response/CartResponseDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package gip.sever.dto.response;

import gip.sever.domain.Cart;
import gip.sever.domain.CartItem;
import gip.sever.domain.Product;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Getter
@Builder
@AllArgsConstructor
public class CartResponseDto {

@Getter
@NoArgsConstructor
public static class CartResponse {
private Long id;
private List<CartItemDto> cartItems = new ArrayList<>();


public CartResponse(Cart cart) {

this.cartItems = cart.getCartItems().stream()
.map(cartItem -> new CartItemDto(cartItem))
.collect(Collectors.toList());
this.id = cart.getId();

}
}
@Getter
public static class CartItemDto{
private Long id;
private ProductDto product ;

public CartItemDto(CartItem cartItem){
this.id = cartItem.getId();
this.product = new ProductDto(cartItem.getProduct());

}
}

@Getter
public static class ProductDto{
private Long id;

private String productName;
private double price;
private String photoUrl;
private int likes;
private String kind;
// 부가설명 필드 추가
private String additionalDescription;

// 장바구니 필드
private boolean isInCart; // 제품이 장바구니에 있는지 여부
private int quantity; // 제품의 수량
public ProductDto(Product product) {
this.id=product.getId();
this.productName = product.getProductName();
this.price = product.getPrice();
this.photoUrl = product.getPhotoUrl();
this.likes = product.getLikes();
this.isInCart = product.isInCart();
this.quantity = product.getQuantity();
this.kind = product.getKind();
this.additionalDescription =product.getAdditionalDescription();
}
}
}
2 changes: 2 additions & 0 deletions src/main/java/gip/sever/dto/response/ProductResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public class ProductResponse {
private double price;
private String photoUrl;
private int likes;
private String kind;
// 부가설명 필드 추가
private String additionalDescription;

Expand All @@ -28,6 +29,7 @@ public ProductResponse(Product product) {
this.likes = product.getLikes();
this.isInCart = product.isInCart();
this.quantity = product.getQuantity();
this.kind = product.getKind();
this.additionalDescription =product.getAdditionalDescription();
}
}
4 changes: 3 additions & 1 deletion src/main/java/gip/sever/global/response/SuccessResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ public class SuccessResponse<T> {
public static <T> SuccessResponse<T> create(String message) {
return new SuccessResponse<>(true, message, null);
}

public static <T> SuccessResponse<T> creat(String message) {
return new SuccessResponse<>(false, message, null);
}
public static <T> SuccessResponse<T> create(String message, T data) {
return new SuccessResponse<>(true, message, data);
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/gip/sever/repository/CartItemRepository.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
package gip.sever.repository;

import gip.sever.domain.Cart;
import gip.sever.domain.CartItem;
import org.hibernate.annotations.Parameter;
import org.springframework.data.jpa.repository.JpaRepository;
Expand Down
56 changes: 38 additions & 18 deletions src/main/java/gip/sever/service/CartService.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
import gip.sever.domain.Cart;
import gip.sever.domain.CartItem;
import gip.sever.domain.Product;
import gip.sever.dto.response.CartResponse;
import gip.sever.dto.response.CartResponseDto;
import gip.sever.repository.CartItemRepository;
import gip.sever.repository.CartRepository;
import gip.sever.repository.ProductRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand All @@ -22,37 +21,58 @@ public class CartService {
private final ProductRepository productRepository;
private final CartItemRepository cartItemRepository;

/* @Transactional
public void addToCart(Long memberId, Long productId) throws Exception{
Cart cart = cartRepository.findByMemberId(memberId)
.orElseThrow(() -> new Exception("계정을 찾을 수 없습니다."));;
Product product = productRepository.findById(productId).orElseThrow(() -> new IllegalArgumentException("Product not found"));
// cart.addProduct(product);
cartRepository.save(cart);
}*/
@Transactional
public boolean addToCart(Long memberId, Long productId) throws Exception {
Cart cart = cartRepository.findByMemberId(memberId)
.orElseThrow(() -> new Exception("계정을 찾을 수 없습니다."));

Product product = productRepository.findById(productId)
.orElseThrow(() -> new IllegalArgumentException("Product not found"));


boolean isAlreadyInCart = cart.getCartItems().stream()
.anyMatch(cartItem -> cartItem.getProduct().equals(product));

if (isAlreadyInCart) {
return false;
} else {
CartItem cartItem = new CartItem(cart, product);
cart.getCartItems().add(cartItem);
cartRepository.save(cart);
return true;
}
}
@Transactional
public void addToCart(Long memberId, Long productId) throws Exception {
public boolean removeFromCart(Long memberId, Long productId) throws Exception{
Cart cart = cartRepository.findByMemberId(memberId)
.orElseThrow(() -> new Exception("계정을 찾을 수 없습니다."));

Product product = productRepository.findById(productId)
.orElseThrow(() -> new IllegalArgumentException("Product not found"));

// CartItem을 생성하여 카트에 추가
CartItem cartItem = new CartItem(cart, product);
cart.getCartItems().add(cartItem);
// 장바구니에서 해당 상품을 찾아서 삭제
cart.getCartItems().removeIf(cartItem -> cartItem.getProduct().equals(product));

cartRepository.save(cart);
return true;
}

@Transactional
public void removeFromCart(Long memberId, Long productId) throws Exception{
Cart cart = cartRepository.findByMemberId(memberId)
.orElseThrow(() -> new Exception("계정을 찾을 수 없습니다."));;
Product product = productRepository.findById(productId).orElseThrow(() -> new IllegalArgumentException("Product not found"));
// cart.removeProduct(product);
cartRepository.save(cart);
}

public CartResponse getCart(Long memberId) throws Exception{
public CartResponseDto.CartResponse getCart(Long memberId) throws Exception{
Cart cart = cartRepository.findByMemberId(memberId)
.orElseThrow(() -> new Exception("계정을 찾을 수 없습니다."));

List<CartItem> cartItems = cartItemRepository.findByMemberIdAndCartId(memberId, cart.getId());
List<CartItem> cartItems = cartItemRepository.findByMemberIdAndCartId(memberId, cart.getId());

return new CartResponse(cart.getId(), cartItems);
//
return new CartResponseDto.CartResponse(cart);
}

}

0 comments on commit f30e4c8

Please sign in to comment.