Skip to content

Commit

Permalink
부산대 BE_정지민 4주차 과제(3단계) (#376)
Browse files Browse the repository at this point in the history
* feat: 지난주차 코드 가져옴

feat: 지난주차 코드 가져옴

* feat: schema.sql 업데이트
- 카테고리 추가
- product 도메인 수정

* feat: Category 도메인 추가

* feat: Category 도메인 추가

feat: Category 도메인 추가

* feat: 위시리스트 생성 로직 수정
- 위시 리스트를 생성한다

* feat: 로그인 토큰 앞에 Bearer

* feat: 유저 조회 API 생성

* refactor: user 로그인 후 위시리스트에 상품을 추가할 수 있다

* feat: 카테고리 생성/조회 로직 추가
- 카테고리 조회
- 카테고리 추가

* refactor: code style 통일
- intellij 코드 스타일 적용이 안되고 있었네요
- 전체 파일 일괄 적용시켜줬습니다.

* feat: 연관관계 설정
- Product & Category 연관관계 설정

* feat: 카테고리 도메인 추가
- 카테고리 생성
- 카테고리 프로퍼티 추가 (색상, 이미지, 설명)
- schema.sql 추가

* feat: 상품 추가 로직 카테고리 validate
- 상품 추가시 필수적으로 상품 카테고리 추가
- validate 카테고리

* docs: README.md

* refactor: jwt 의존성 버전업
- 0.11.5 -> 0.12.3

* refactor: jwt 의존성 버전업
- 0.11.5 -> 0.12.3

* feat: user Role 포함

* feat: role 기반 인가
- 상품/카테고리 생성 자체는 ADMIN만 가능하다

* feat: 카테고리 생성 관리자 인가

* feat: Product Option 도메인 추가

* feat: 가격은 제외

* feat: 상품 옵션 추가 API 구현
- 관리자는 상품 옵션을 추가할 수 있다
- 동일한 이름의 옵션은 추가할 수 없다

* feat: WishList 레포지토리 분리
- Jpa 레포지토리/순수 Java 레포지토리 분리

* feat: WishList 레포지토리 분리
- Jpa 레포지토리/순수 Java 레포지토리 분리

* feat: WishList 레포지토리 분리
- Jpa 레포지토리/순수 Java 레포지토리 분리

* feat: 상품 옵션 선택해서 추가
- 회원이 위시리스트에 상품을 추가할 때 option id까지 추가하도록 한다

* feat: kakao id는 여기 없는데 왜 추가한거지?

* feat: 구매 로직 구현
- 구매를 수행할 경우 stoke --

* feat: 상품에 대한 개수 추가

* feat: quentity type 수정
- Long

* feat: 클래스단위 read only 해제

* refactor: Category 생성자 수정
- 파라미터 분해 x

* refactor: ProductOption 생성자 수정
- 파라미터 분해 x

* refactor: Product 생성자 수정
- 파라미터 분해 x

* refactor: WishList 생성자 수정
- 파라미터 분해 x
  • Loading branch information
stopmin authored Jul 23, 2024
1 parent e25a46e commit 30dabaf
Show file tree
Hide file tree
Showing 14 changed files with 217 additions and 47 deletions.
44 changes: 44 additions & 0 deletions src/main/java/gift/payment/application/PaymentService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package gift.payment.application;

import gift.product.domain.Product;
import gift.product.domain.ProductOption;
import gift.product.domain.WishList;
import gift.product.domain.WishListProduct;
import gift.product.exception.ProductException;
import gift.product.infra.ProductRepository;
import gift.product.infra.WishListRepository;
import gift.util.ErrorCode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
public class PaymentService {

private final WishListRepository wishListRepository;
private final ProductRepository productRepository;

public PaymentService(WishListRepository wishListRepository, ProductRepository productRepository) {
this.wishListRepository = wishListRepository;
this.productRepository = productRepository;
}

@Transactional
public void processPayment(Long userId, Long wishListId) {
WishList wishList = wishListRepository.findById(wishListId);

if (!Objects.equals(wishList.getUser().getId(), userId)) {
throw new ProductException(ErrorCode.NOT_USER_OWNED);
}

for (WishListProduct product : wishList.getWishListProducts()) {
Product wishListProduct = product.getProduct();
ProductOption productOption = product.getProductOption();
productOption.decreaseQuantity(product.getQuantity());

productRepository.save(wishListProduct);
}
wishListRepository.delete(wishList);
}
}
33 changes: 33 additions & 0 deletions src/main/java/gift/payment/controller/PaymentController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package gift.payment.presentation;

import gift.payment.application.PaymentService;
import gift.util.CommonResponse;
import gift.util.annotation.JwtAuthenticated;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/payment")
public class PaymentController {

private final PaymentService paymentService;

public PaymentController(PaymentService paymentService) {
this.paymentService = paymentService;
}

@PostMapping("/process/{wishListId}")
@JwtAuthenticated
public ResponseEntity<?> processPayment(@PathVariable Long wishListId) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Long userId = Long.valueOf(authentication.getName());

paymentService.processPayment(userId, wishListId);
return ResponseEntity.ok(new CommonResponse<>(
null, "결제 완료", true
));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public void addCategory(CreateCategoryRequest request) {
if (categoryRepository.findByName(request.getName()) != null) {
throw new IllegalArgumentException("이미 존재하는 카테고리입니다.");
}
Category category = new Category(request.getName(), request.getDescription(), request.getImageUrl(), request.getColor());
Category category = new Category(request);

categoryRepository.save(category);
}
Expand Down
12 changes: 2 additions & 10 deletions src/main/java/gift/product/application/ProductService.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import java.util.List;

@Service
@Transactional(readOnly = true)
public class ProductService {

private final ProductRepository productRepository;
Expand All @@ -28,8 +27,7 @@ public ProductService(ProductRepository productRepository, CategoryService categ
@Transactional
public Long saveProduct(CreateProductRequestDTO createProductRequestDTO) {
Category category = categoryService.getCategoryByName(createProductRequestDTO.getCategory());
Product product = new Product(createProductRequestDTO.getName(), createProductRequestDTO.getPrice(),
createProductRequestDTO.getImageUrl(), category);
Product product = new Product(createProductRequestDTO, category);
validateProduct(product);

return productRepository.save(product).getId();
Expand All @@ -39,14 +37,8 @@ public Long saveProduct(CreateProductRequestDTO createProductRequestDTO) {
public void addProductOption(Long id, CreateProductOptionRequestDTO createProductOptionRequestDTO) {
Product product = productRepository.findById(id);

productRepository.findProductOptionsByProductId(id).forEach(productOption -> {
if (productOption.getName().equals(createProductOptionRequestDTO.getName())) {
throw new ProductException(ErrorCode.DUPLICATED_OPTION_NAME);
}
});
product.addProductOption(createProductOptionRequestDTO);

ProductOption productOption = productRepository.saveProductOption(new ProductOption(createProductOptionRequestDTO.getName(),
createProductOptionRequestDTO.getQuantity(), product));
productRepository.save(product);
}

Expand Down
19 changes: 8 additions & 11 deletions src/main/java/gift/product/application/WishListService.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package gift.product.application;

import gift.product.domain.Product;
import gift.product.domain.ProductOption;
import gift.product.domain.WishList;
import gift.product.domain.WishListProduct;
import gift.product.domain.*;
import gift.product.exception.ProductException;
import gift.product.infra.ProductRepository;
import gift.product.infra.WishListRepository;
Expand Down Expand Up @@ -51,23 +48,23 @@ public Page<WishList> getProductsInWishList(Long userId, int page, int size, Str
}

@Transactional
public void addProductToWishList(Long userId, Long wishlistId, Long productId, Long optionId) {
WishList wishList = findById(wishlistId);
if (!Objects.equals(wishList.getUser().getId(), userId)) {
public void addProductToWishList(AddWishListRequest request) {
WishList wishList = findById(request.getWishlistId());
if (!Objects.equals(wishList.getUser().getId(), request.getUserId())) {
throw new ProductException(ErrorCode.NOT_USER_OWNED);
}

Product product = productRepository.findById(productId);
ProductOption productOption = productRepository.getProductWithOption(productId, optionId);
Product product = productRepository.findById(request.getProductId());
ProductOption productOption = productRepository.getProductWithOption(request.getProductId(), request.getOptionId());

wishList.addWishListProduct(new WishListProduct(wishList, product, productOption));
wishList.addWishListProduct(new WishListProduct(wishList, product, productOption, request.getQuantity()));


wishListRepository.save(wishList);
}

public WishList findById(Long id) {
return wishListRepository.findById(id).orElseThrow(() -> new ProductException(ErrorCode.WISHLIST_NOT_FOUND));
return wishListRepository.findById(id);
}

@Transactional
Expand Down
37 changes: 37 additions & 0 deletions src/main/java/gift/product/domain/AddWishListRequest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package gift.product.domain;

public class AddWishListRequest {
private Long userId;
private Long wishlistId;
private Long productId;
private Long optionId;
private Long quantity;

public Long getUserId() {
return userId;
}

public Long getWishlistId() {
return wishlistId;
}

public Long getProductId() {
return productId;
}

public Long getOptionId() {
return optionId;
}

public Long getQuantity() {
return quantity;
}

public AddWishListRequest(Long userId, Long wishlistId, Long productId, Long optionId, Long quantity) {
this.userId = userId;
this.wishlistId = wishlistId;
this.productId = productId;
this.optionId = optionId;
this.quantity = quantity;
}
}
10 changes: 5 additions & 5 deletions src/main/java/gift/product/domain/Category.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ public class Category {
public Category() {
}

public Category(String name, String description, String imageUrl, String color) {
this.name = name;
this.description = description;
this.imageUrl = imageUrl;
this.color = color;
public Category(CreateCategoryRequest request) {
this.name = request.getName();
this.description = request.getDescription();
this.imageUrl = request.getImageUrl();
this.color = request.getColor();
}

public Long getId() {
Expand Down
21 changes: 7 additions & 14 deletions src/main/java/gift/product/domain/Product.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ public class Product {
public Product() {
}

public Product(String name, Double price, String imageUrl, Category category) {
this.name = name;
this.price = price;
this.imageUrl = imageUrl;
public Product(CreateProductRequestDTO createProductRequestDTO, Category category) {
this.name = createProductRequestDTO.getName();
this.price = createProductRequestDTO.getPrice();
this.imageUrl = createProductRequestDTO.getImageUrl();
this.category = category;
}

Expand Down Expand Up @@ -71,19 +71,12 @@ public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}

public List<WishListProduct> getWishListProducts() {
return wishListProducts;
}

public void setWishListProducts(List<WishListProduct> wishListProducts) {
this.wishListProducts = wishListProducts;
}

public void addProductOption(String name, Long quentity) {
ProductOption productOption = new ProductOption(name, quentity, this);
public void addProductOption(CreateProductOptionRequestDTO createProductOptionRequestDTO) {
ProductOption productOption = new ProductOption(createProductOptionRequestDTO.getName(), createProductOptionRequestDTO.getQuantity(), this);
productOptions.add(productOption);
}


public void addProductOption(ProductOption productOption) {
productOptions.add(productOption);
}
Expand Down
19 changes: 19 additions & 0 deletions src/main/java/gift/product/domain/ProductOption.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ public class ProductOption {
@JoinColumn(name = "product_id")
private Product product;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "wishlist_product_id")
private WishListProduct wishListProduct;

public ProductOption(String name, Long quentity, Product product) {
this.name = name;
this.quentity = quentity;
Expand All @@ -24,7 +28,22 @@ public ProductOption(String name, Long quentity, Product product) {
public ProductOption() {
}

public Long getId() {
return id;
}

public Long getQuentity() {
return quentity;
}

public String getName() {
return name;
}

public void decreaseQuantity(Long quentity) {
if (this.quentity < quentity) {
throw new IllegalArgumentException("재고가 부족합니다.");
}
this.quentity -= quentity;
}
}
6 changes: 5 additions & 1 deletion src/main/java/gift/product/domain/WishList.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class WishList {
@JoinColumn(name = "user_id")
private User user;

@OneToMany(mappedBy = "wishList", cascade = CascadeType.ALL, orphanRemoval = true)
@OneToMany(mappedBy = "wishList")
private List<WishListProduct> wishListProducts = new ArrayList<>();

private LocalDateTime createdAt;
Expand Down Expand Up @@ -71,4 +71,8 @@ public LocalDateTime getCreatedAt() {
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}

public void clearProducts() {
wishListProducts.clear();
}
}
14 changes: 13 additions & 1 deletion src/main/java/gift/product/domain/WishListProduct.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,16 @@ public class WishListProduct {
@JoinColumn(name = "product_option_id")
private ProductOption productOption;

private Long quantity;

public WishListProduct() {
}

public WishListProduct(WishList wishList, Product product, ProductOption productOption) {
public WishListProduct(WishList wishList, Product product, ProductOption productOption, Long quantity) {
this.wishList = wishList;
this.product = product;
this.productOption = productOption;
this.quantity = quantity;
}

public Long getId() {
Expand All @@ -54,4 +57,13 @@ public Product getProduct() {
public void setProduct(Product product) {
this.product = product;
}


public ProductOption getProductOption() {
return productOption;
}

public Long getQuantity() {
return quantity;
}
}
38 changes: 38 additions & 0 deletions src/main/java/gift/product/infra/WishListRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package gift.product.infra;

import gift.product.domain.WishList;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public class WishListRepository {
private final WishListJpaRepository wishListJpaRepository;

public WishListRepository(WishListJpaRepository wishListJpaRepository) {
this.wishListJpaRepository = wishListJpaRepository;
}

public WishList findByUserId(Long userId) {
return wishListJpaRepository.findByUserId(userId)
.orElseThrow(() -> new IllegalArgumentException("해당 ID의 위시리스트가 존재하지 않습니다."));
}

public Page<WishList> findByUserId(Long userId, Pageable pageable) {
return wishListJpaRepository.findByUserId(userId, pageable);
}

public void save(WishList wishList) {
wishListJpaRepository.save(wishList);
}

public WishList findById(Long id) {
return wishListJpaRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("해당 ID의 위시리스트가 존재하지 않습니다."));
}

public void delete(WishList wishList) {
wishListJpaRepository.delete(wishList);
}
}
Loading

0 comments on commit 30dabaf

Please sign in to comment.