Skip to content

Commit

Permalink
Merge pull request #81 from Uni-Made/feature/#70
Browse files Browse the repository at this point in the history
♻️ [REFACTOR] 요청값 사용자 토큰으로 변경 #70
  • Loading branch information
moonyaeyoon authored Jul 26, 2024
2 parents f0e07d2 + f98d7d4 commit 28e1a43
Show file tree
Hide file tree
Showing 15 changed files with 97 additions and 75 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
import lombok.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import umc.unimade.domain.accounts.dto.BuyerOrderHistoryResponse;
import umc.unimade.domain.accounts.dto.BuyerPageResponse;
import umc.unimade.domain.accounts.entity.Buyer;
import umc.unimade.domain.accounts.service.BuyerCommandService;
import umc.unimade.domain.accounts.service.BuyerQueryService;
import umc.unimade.domain.favorite.dto.FavoriteProductsListResponse;
Expand All @@ -30,10 +32,10 @@ public class BuyerController {

@Tag(name = "FavoriteSeller")
@Operation(summary = "찜하지 않은 상태라면 찜하기. \n 찜한 상태라면 찜하기 취소")
@PostMapping("/favorite/{sellerId}/{buyerId}")
public ResponseEntity<ApiResponse<Void>> toggleFavoriteSeller(@PathVariable Long sellerId, @PathVariable Long buyerId) {
@PostMapping("/favorite/{sellerId}")
public ResponseEntity<ApiResponse<Void>> toggleFavoriteSeller(@AuthenticationPrincipal Buyer currentBuyer,@PathVariable Long sellerId) {
try {
return ResponseEntity.ok(buyerCommandService.toggleFavoriteSeller(sellerId, buyerId));
return ResponseEntity.ok(buyerCommandService.toggleFavoriteSeller(sellerId, currentBuyer));
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ApiResponse.onFailure(HttpStatus.BAD_REQUEST.name(), e.getMessage()));
} catch (UserExceptionHandler e) {
Expand All @@ -43,10 +45,10 @@ public ResponseEntity<ApiResponse<Void>> toggleFavoriteSeller(@PathVariable Long

@Tag(name = "Buyer", description = "구매자 관련 API")
@Operation(summary = "구매자 마이페이지에서 찜한 상품과 메이더를 보여준다.")
@GetMapping("/myPage/{buyerId}")
public ResponseEntity<ApiResponse<BuyerPageResponse>> getBuyerPage(@PathVariable Long buyerId) {
@GetMapping("/myPage")
public ResponseEntity<ApiResponse<BuyerPageResponse>> getBuyerPage(@AuthenticationPrincipal Buyer currentBuyer) {
try {
return ResponseEntity.ok(ApiResponse.onSuccess(buyerQueryService.getBuyerPage(buyerId)));
return ResponseEntity.ok(ApiResponse.onSuccess(buyerQueryService.getBuyerPage(currentBuyer)));
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ApiResponse.onFailure(HttpStatus.BAD_REQUEST.name(), e.getMessage()));
} catch (UserExceptionHandler e) {
Expand All @@ -55,13 +57,13 @@ public ResponseEntity<ApiResponse<BuyerPageResponse>> getBuyerPage(@PathVariable
}
@Tag(name = "Buyer", description = "구매자 관련 API")
@Operation(summary = "구매 내역 리스트")
@GetMapping("/history/{buyerId}")
@GetMapping("/history")
public ResponseEntity<ApiResponse<BuyerOrderHistoryResponse>> getOrderHistory(
@RequestParam Long buyerId,
@AuthenticationPrincipal Buyer currentBuyer,
@RequestParam(required = false) Long cursor,
@RequestParam int pageSize) {
try {
return ResponseEntity.ok(ApiResponse.onSuccess(buyerQueryService.getOrderHistory(buyerId, cursor, pageSize)));
return ResponseEntity.ok(ApiResponse.onSuccess(buyerQueryService.getOrderHistory(currentBuyer, cursor, pageSize)));
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ApiResponse.onFailure(HttpStatus.BAD_REQUEST.name(), e.getMessage()));
} catch (UserExceptionHandler e) {
Expand All @@ -71,12 +73,13 @@ public ResponseEntity<ApiResponse<BuyerOrderHistoryResponse>> getOrderHistory(

@Tag(name = "FavoriteProduct")
@Operation(summary = "찜한 상품 더보기")
@GetMapping("/{buyerId}/favorite-products")
public ResponseEntity<ApiResponse<FavoriteProductsListResponse>> getFavoriteProductsList(@PathVariable Long buyerId,
@GetMapping("/favorite-products")
public ResponseEntity<ApiResponse<FavoriteProductsListResponse>> getFavoriteProductsList(@AuthenticationPrincipal Buyer currentBuyer,
@RequestParam(required = false) Long cursor,
@RequestParam int pageSize) {
@RequestParam int pageSize
) {
try {
return ResponseEntity.ok(ApiResponse.onSuccess(buyerQueryService.getFavoriteProdutsList(buyerId, cursor, pageSize)));
return ResponseEntity.ok(ApiResponse.onSuccess(buyerQueryService.getFavoriteProdutsList(currentBuyer, cursor, pageSize)));
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ApiResponse.onFailure(HttpStatus.BAD_REQUEST.name(), e.getMessage()));
} catch (UserExceptionHandler e) {
Expand All @@ -86,12 +89,12 @@ public ResponseEntity<ApiResponse<FavoriteProductsListResponse>> getFavoriteProd

@Tag(name = "FavoriteSeller")
@Operation(summary = "찜한 메이더 더보기")
@GetMapping("/{buyerId}/favorite-sellers")
public ResponseEntity<ApiResponse<FavoriteSellersListResponse>> getFavoriteSellersList(@PathVariable Long buyerId,
@GetMapping("/favorite-sellers")
public ResponseEntity<ApiResponse<FavoriteSellersListResponse>> getFavoriteSellersList(@AuthenticationPrincipal Buyer currentBuyer,
@RequestParam(required = false) Long cursor,
@RequestParam int pageSize) {
try {
return ResponseEntity.ok(ApiResponse.onSuccess(buyerQueryService.getFavoriteSellersList(buyerId, cursor, pageSize)));
return ResponseEntity.ok(ApiResponse.onSuccess(buyerQueryService.getFavoriteSellersList(currentBuyer, cursor, pageSize)));
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ApiResponse.onFailure(HttpStatus.BAD_REQUEST.name(), e.getMessage()));
} catch (UserExceptionHandler e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

import java.util.Optional;

import static umc.unimade.domain.accounts.entity.QBuyer.buyer;

@Service
@RequiredArgsConstructor
public class BuyerCommandService {
Expand All @@ -24,9 +26,8 @@ public class BuyerCommandService {
private final FavoriteSellerRepository favoriteSellerRepository;

@Transactional
public ApiResponse<Void> toggleFavoriteSeller(Long sellerId,Long buyerId){
public ApiResponse<Void> toggleFavoriteSeller(Long sellerId, Buyer buyer){
Seller seller = findSellerById(sellerId);
Buyer buyer = findBuyerById(buyerId);
Optional<FavoriteSeller> existingFavorite = findFavoriteSeller(seller,buyer);

if(existingFavorite.isPresent()){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ public class BuyerQueryService {
private final OrderRepository orderRepository;

// 구매자 마이페이지
public BuyerPageResponse getBuyerPage(Long buyerId){
Buyer buyer = findBuyerById(buyerId);
public BuyerPageResponse getBuyerPage(Buyer buyer){
List<FavoriteProductResponse> favoriteProducts = favoriteProductRepository.findTop4ByBuyerOrderByCreatedAtDesc(buyer).stream()
.map(FavoriteProductResponse::from)
.collect(Collectors.toList());
Expand All @@ -47,25 +46,27 @@ public BuyerPageResponse getBuyerPage(Long buyerId){
}

// 구매 내역
public BuyerOrderHistoryResponse getOrderHistory(Long buyerId, Long cursor, Integer pageSize){
public BuyerOrderHistoryResponse getOrderHistory(Buyer buyer, Long cursor, Integer pageSize){
Pageable pageable = PageRequest.of(0, pageSize);
List<Orders> orders = orderRepository.findOrdersByBuyerIdWithCursorPagination(buyerId, cursor, pageable);
List<Orders> orders = orderRepository.findOrdersByBuyerWithCursorPagination(buyer, cursor, pageable);

Long nextCursor = orders.isEmpty() ? null : orders.get(orders.size() - 1).getId();
boolean isLast = orders.size() < pageSize;
return BuyerOrderHistoryResponse.from(orders, nextCursor, isLast);
}

// 찜한 상품 더보기
public FavoriteProductsListResponse getFavoriteProdutsList(Long buyerId,Long cursor, int pageSize){
public FavoriteProductsListResponse getFavoriteProdutsList(Buyer currentBuyer,Long cursor, int pageSize){
Buyer buyer = findBuyerById(currentBuyer.getId());

Pageable pageable = PageRequest.of(0, pageSize, Sort.by(Sort.Direction.DESC, "createdAt"));

List<FavoriteProduct> favoriteProducts;

if (cursor == null) {
favoriteProducts = favoriteProductRepository.findByBuyerIdOrderByCreatedAtDesc(buyerId, pageable);
favoriteProducts = favoriteProductRepository.findByBuyerOrderByCreatedAtDesc(buyer, pageable);
} else {
favoriteProducts = favoriteProductRepository.findByBuyerIdAndIdLessThanOrderByCreatedAtDesc(buyerId, cursor, pageable);
favoriteProducts = favoriteProductRepository.findByBuyerAndIdLessThanOrderByCreatedAtDesc(buyer, cursor, pageable);
}

Long nextCursor = favoriteProducts.isEmpty() ? null : favoriteProducts.get(favoriteProducts.size() - 1).getId();
Expand All @@ -75,13 +76,13 @@ public FavoriteProductsListResponse getFavoriteProdutsList(Long buyerId,Long cur
}

// 찜한 메이더 더보기
public FavoriteSellersListResponse getFavoriteSellersList(Long buyerId, Long cursor, int pageSize){
public FavoriteSellersListResponse getFavoriteSellersList(Buyer buyer, Long cursor, int pageSize){
Pageable pageable = PageRequest.of(0, pageSize, Sort.by(Sort.Direction.DESC, "createdAt"));
List<FavoriteSeller> favoriteSellers;
if (cursor == null){
favoriteSellers = favoriteSellerRepository.findByBuyerIdOrderByCreatedAtDesc(buyerId, pageable);
favoriteSellers = favoriteSellerRepository.findByBuyerOrderByCreatedAtDesc(buyer, pageable);
}else {
favoriteSellers = favoriteSellerRepository.findByBuyerIdAndIdLessThanOrderByCreatedAtDesc(buyerId, cursor, pageable);
favoriteSellers = favoriteSellerRepository.findByBuyerAndIdLessThanOrderByCreatedAtDesc(buyer, cursor, pageable);
}
Long nextCursor = favoriteSellers.isEmpty() ? null : favoriteSellers.get(favoriteSellers.size() - 1).getId();
Boolean isLast = favoriteSellers.size() < pageSize;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,24 @@
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import umc.unimade.domain.accounts.entity.Buyer;
import umc.unimade.domain.favorite.entity.FavoriteProduct;
import umc.unimade.domain.products.entity.Products;

import java.util.List;
import java.util.Optional;

@Repository
public interface FavoriteProductRepository extends JpaRepository<FavoriteProduct, Long> {

Optional<FavoriteProduct> findByProductAndBuyer(Products product, Buyer buyer);

List<FavoriteProduct> findTop4ByBuyerOrderByCreatedAtDesc(Buyer buyer);

@Query("SELECT fp FROM FavoriteProduct fp WHERE fp.buyer.id = :buyerId ORDER BY fp.createdAt DESC")
List<FavoriteProduct> findByBuyerIdOrderByCreatedAtDesc(Long buyerId, Pageable pageable);
@Query("SELECT fp FROM FavoriteProduct fp WHERE fp.buyer = :buyer ORDER BY fp.createdAt DESC")
List<FavoriteProduct> findByBuyerOrderByCreatedAtDesc(Buyer buyer, Pageable pageable);

@Query("SELECT fp FROM FavoriteProduct fp WHERE fp.buyer.id = :buyerId AND fp.id < :cursor ORDER BY fp.createdAt DESC")
List<FavoriteProduct> findByBuyerIdAndIdLessThanOrderByCreatedAtDesc(Long buyerId, Long cursor, Pageable pageable);
@Query("SELECT fp FROM FavoriteProduct fp WHERE fp.buyer = :buyer AND fp.id < :cursor ORDER BY fp.createdAt DESC")
List<FavoriteProduct> findByBuyerAndIdLessThanOrderByCreatedAtDesc(Buyer buyer, Long cursor, Pageable pageable);
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ public interface FavoriteSellerRepository extends JpaRepository<FavoriteSeller,

List<FavoriteSeller> findTop4ByBuyerOrderByCreatedAtDesc(Buyer buyer);

@Query("SELECT fs FROM FavoriteSeller fs WHERE fs.buyer.id = :buyerId ORDER BY fs.createdAt DESC")
List<FavoriteSeller> findByBuyerIdOrderByCreatedAtDesc(Long buyerId, Pageable pageable);
@Query("SELECT fs FROM FavoriteSeller fs WHERE fs.buyer = :buyer ORDER BY fs.createdAt DESC")
List<FavoriteSeller> findByBuyerOrderByCreatedAtDesc(Buyer buyer, Pageable pageable);

@Query("SELECT fs FROM FavoriteSeller fs WHERE fs.buyer.id = :buyerId AND fs.id < :cursor ORDER BY fs.createdAt DESC")
List<FavoriteSeller> findByBuyerIdAndIdLessThanOrderByCreatedAtDesc(Long buyerId, Long cursor, Pageable pageable);
@Query("SELECT fs FROM FavoriteSeller fs WHERE fs.buyer = :buyer AND fs.id < :cursor ORDER BY fs.createdAt DESC")
List<FavoriteSeller> findByBuyerAndIdLessThanOrderByCreatedAtDesc(Buyer buyer, Long cursor, Pageable pageable);
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import umc.unimade.domain.accounts.entity.Buyer;
import umc.unimade.domain.accounts.entity.Seller;
import umc.unimade.domain.orders.dto.*;
import umc.unimade.domain.accounts.exception.UserExceptionHandler;
Expand Down Expand Up @@ -34,10 +36,10 @@ public class OrderController {

@Tag(name = "Order", description = "구매 관련 API")
@Operation(summary = "상품 구매하기")
@PostMapping("/{productId}/{buyerId}")
public ResponseEntity<ApiResponse<OrderResponse>> createOrder (@PathVariable Long productId, @PathVariable Long buyerId, @RequestBody OrderRequest orderRequest){
@PostMapping("/{productId}")
public ResponseEntity<ApiResponse<OrderResponse>> createOrder (@AuthenticationPrincipal Buyer currentBuyer, @PathVariable Long productId, @RequestBody OrderRequest orderRequest){
try {
return ResponseEntity.ok(ApiResponse.onSuccess(orderCommandService.createOrder(productId, buyerId, orderRequest)));
return ResponseEntity.ok(ApiResponse.onSuccess(orderCommandService.createOrder(productId, currentBuyer, orderRequest)));
}
catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ApiResponse.onFailure(HttpStatus.BAD_REQUEST.name(), e.getMessage()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import umc.unimade.domain.accounts.entity.Buyer;
import umc.unimade.domain.orders.entity.OrderStatus;
import umc.unimade.domain.orders.entity.Orders;

Expand All @@ -18,8 +19,8 @@ public interface OrderRepository extends JpaRepository<Orders, Long> {
@Query("SELECT o FROM Orders o WHERE o.product.id = :productId")
List<Orders> findOrdersByProductId(Long productId, Pageable pageable);

@Query("SELECT o FROM Orders o WHERE o.buyer.id = :buyerId AND (:cursor IS NULL OR o.id < :cursor) ORDER BY o.id DESC")
List<Orders> findOrdersByBuyerIdWithCursorPagination(@Param("buyerId") Long buyerId, @Param("cursor") Long cursor, Pageable pageable);
@Query("SELECT o FROM Orders o WHERE o.buyer = :buyer AND (:cursor IS NULL OR o.id < :cursor) ORDER BY o.id DESC")
List<Orders> findOrdersByBuyerWithCursorPagination(Buyer buyer, @Param("cursor") Long cursor, Pageable pageable);

@Query("SELECT o FROM Orders o WHERE o.purchaseForm.createdAt < :threeDaysAgo AND o.status = :status")
List<Orders> findOrdersCreatedBefore(LocalDateTime threeDaysAgo, OrderStatus status);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,10 @@ public class OrderCommandService {
private final OrderItemRepository orderItemRepository;

@Transactional
public OrderResponse createOrder(Long productId, Long buyerId, OrderRequest orderRequest) {
public OrderResponse createOrder(Long productId, Buyer buyer, OrderRequest orderRequest) {
if (!orderRequest.getPurchaseForm().getIsAgree()) {
throw new OrderExceptionHandler(ErrorCode.ORDER_AGREEMENT_REQUIRED);
}

Buyer buyer = findBuyerById(buyerId);
Products product = findProductById(productId);

// PurchaseForm 엔티티 생성 및 저장
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import lombok.*;
import org.springframework.web.multipart.MultipartFile;
import umc.unimade.domain.accounts.entity.Buyer;
import umc.unimade.domain.products.dto.ProductRegisterResponse;
import umc.unimade.domain.products.dto.ProductRequest.UpdateProductDto;
import umc.unimade.domain.products.dto.ProductResponse;
Expand Down Expand Up @@ -36,10 +38,10 @@ public class ProductsController extends BaseEntity {
@Tag(name = "Products", description = "판매 상품 관련 API")
@Operation(summary = "판매 상품 정보 가져오기")
@GetMapping("/{productId}")
//To do : 토큰 구현 시 user 정보 추가
public ResponseEntity<ApiResponse<ProductResponse>> getProductDetails
(@PathVariable Long productId , @RequestParam ViewType viewType, @RequestParam(required = false) Long cursor,
@RequestParam(defaultValue = "10") int pageSize) {
public ResponseEntity<ApiResponse<ProductResponse>> getProductDetails (@PathVariable Long productId ,
@RequestParam ViewType viewType,
@RequestParam(required = false) Long cursor,
@RequestParam(defaultValue = "10") int pageSize) {
try {
return ResponseEntity.ok(ApiResponse.onSuccess(productsQueryService.getProduct(productId, viewType, cursor, pageSize)));
}
Expand All @@ -50,13 +52,12 @@ public class ProductsController extends BaseEntity {
}
}

//To do : buyerId 추후에 토큰으로 변경
@Tag(name = "FavoriteProduct")
@Operation(summary = "찜하지 않은 상태라면 찜하기. \n 찜한 상태라면 찜하기 취소")
@PostMapping("/favorite/{productId}/{buyerId}")
public ResponseEntity<ApiResponse<Void>> toggleFavoriteProduct(@PathVariable Long productId, @PathVariable Long buyerId) {
@PostMapping("/favorite/{productId}")
public ResponseEntity<ApiResponse<Void>> toggleFavoriteProduct(@AuthenticationPrincipal Buyer currentBuyer, @PathVariable Long productId) {
try {
return ResponseEntity.ok(productsCommandService.toggleFavoriteProduct(productId, buyerId));
return ResponseEntity.ok(productsCommandService.toggleFavoriteProduct(productId, currentBuyer));
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ApiResponse.onFailure(HttpStatus.BAD_REQUEST.name(), e.getMessage()));
} catch (UserExceptionHandler e) {
Expand Down
Loading

0 comments on commit 28e1a43

Please sign in to comment.