Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[47] 일반 사용자 주문 리스트 #50

Merged
merged 5 commits into from
Nov 3, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.example.commerce_site.application.address.AddressService;
import org.example.commerce_site.application.order.dto.OrderDetailResponseDto;
import org.example.commerce_site.application.order.dto.OrderRequestDto;
import org.example.commerce_site.application.order.dto.OrderResponseDto;
import org.example.commerce_site.application.product.ProductService;
import org.example.commerce_site.application.shipment.ShipmentService;
import org.example.commerce_site.application.user.UserService;
Expand All @@ -14,11 +15,15 @@
import org.example.commerce_site.domain.Address;
import org.example.commerce_site.domain.Order;
import org.example.commerce_site.domain.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
public class OrderFacade {
Expand Down Expand Up @@ -51,4 +56,9 @@ public void cancel(String userAuthId, Long orderId) {
List<OrderDetailResponseDto.Get> orderDetails = orderDetailService.getOrderDetails(order.getId());
productService.restoreStockOnCancel(orderDetails);
}

public Page<OrderResponseDto.Get> getOrderList(int page, int size, String keyword, String userAuthId) {
User user = userService.getUser(userAuthId);
return orderService.getOrderList(PageRequest.of(page - 1, size), keyword, user.getId());
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
package org.example.commerce_site.application.order;

import org.example.commerce_site.application.order.dto.OrderRequestDto;
import org.example.commerce_site.application.order.dto.OrderResponseDto;
import org.example.commerce_site.attribute.OrderStatus;
import org.example.commerce_site.common.exception.CustomException;
import org.example.commerce_site.common.exception.ErrorCode;
import org.example.commerce_site.domain.Order;
import org.example.commerce_site.infrastructure.order.CustomOrderRepository;
import org.example.commerce_site.infrastructure.order.OrderRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Expand All @@ -15,6 +19,7 @@
@RequiredArgsConstructor
public class OrderService {
private final OrderRepository orderRepository;
private final CustomOrderRepository customOrderRepository;

@Transactional
public Order createOrder(OrderRequestDto.Create dto, Long userId) {
Expand All @@ -33,4 +38,9 @@ public void updateStatus(Order order, OrderStatus orderStatus) {
order.updateOrderStatus(orderStatus);
orderRepository.save(order);
}

@Transactional(readOnly = true)
public Page<OrderResponseDto.Get> getOrderList(PageRequest pageRequest, String keyword, Long userId) {
return customOrderRepository.getOrders(pageRequest, keyword, userId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,29 @@
import java.time.LocalDateTime;
import java.util.List;

import org.example.commerce_site.attribute.ShipmentStatus;
import org.example.commerce_site.domain.Order;
import org.example.commerce_site.domain.OrderDetail;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;

public class OrderDetailResponseDto {
@Getter
@Builder
@AllArgsConstructor
public static class Get {
private LocalDateTime createdAt;
private Long id;
private Long productId;
private Long quantity;
private Long orderId;
private BigDecimal unitPrice;
private String productName;
private ShipmentStatus shipmentStatus;
private LocalDateTime shipmentCreatedAt;
private LocalDateTime shipmentUpdatedAt;

public static Get toDto(OrderDetail orderDetail) {
return Get.builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package org.example.commerce_site.application.order.dto;

import java.math.BigDecimal;
import java.util.List;

import org.example.commerce_site.attribute.OrderStatus;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;

public class OrderResponseDto {
@Builder
@Getter
@AllArgsConstructor
public static class Get {
private Long id;
private BigDecimal totalAmount;
private OrderStatus status;
private List<OrderDetailResponseDto.Get> orderDetails;

public Get(Long id, BigDecimal totalAmount, OrderStatus status) {
this.id = id;
this.totalAmount = totalAmount;
this.status = status;
}

public void setOrderDetails(List<OrderDetailResponseDto.Get> orderDetails) {
this.orderDetails = orderDetails;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.example.commerce_site.common.util;

import java.util.Collections;
import java.util.List;

import org.springframework.data.domain.Page;
Expand All @@ -8,7 +9,16 @@

public class PageConverter {
public static <T> Page<T> getPage(List<T> content, Pageable pageable) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

content 전체를 받고 일부를 잘라서 사용하는 것 같은데, 전체 row의 갯수가 엄청 많아지면 무슨일이 생길까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

굳이 필요없는 데이터까지 가져오므로 많이 느려질것같네요.. 쿼리에서 limit 을 주고 Total 값을 얻는 쿼리를 한번 더 돌리는 방법으로 수정 하겠습니다..!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이부분 [48] 파트너회원 order list 브랜치에서 반영했습니다..!

if (content == null || pageable == null) {
return new PageImpl<>(Collections.emptyList(), pageable != null ? pageable : Pageable.unpaged(), 0);
}

int start = (int)pageable.getOffset();

if (start >= content.size()) {
return new PageImpl<>(Collections.emptyList(), pageable, content.size());
}
Comment on lines +18 to +20

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이건 어떤 경우를 처리하는거에요?

Copy link
Collaborator Author

@ohsuha ohsuha Oct 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

입력받은 페이지가 전체 페이지보다 클 경우(예: 총 3페이지인데 6페이지 보여달라고 요청 받았을때) 예외가 발생해, empty리스트를 반환하도록 했습니다


int end = Math.min((start + pageable.getPageSize()), content.size());

return new PageImpl<>(content.subList(start, end), pageable, content.size());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package org.example.commerce_site.infrastructure.order;

import org.example.commerce_site.application.order.dto.OrderResponseDto;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

public interface CustomOrderRepository {
Page<OrderResponseDto.Get> getOrders(Pageable pageable, String keyword, Long userId);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package org.example.commerce_site.infrastructure.order;

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

import org.example.commerce_site.application.order.dto.OrderDetailResponseDto;
import org.example.commerce_site.application.order.dto.OrderResponseDto;
import org.example.commerce_site.common.util.PageConverter;
import org.example.commerce_site.domain.QOrder;
import org.example.commerce_site.domain.QOrderDetail;
import org.example.commerce_site.domain.QProduct;
import org.example.commerce_site.domain.QShipment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;

import lombok.RequiredArgsConstructor;

@Repository
@RequiredArgsConstructor
public class CustomOrderRepositoryImpl implements CustomOrderRepository {
private final JPAQueryFactory queryFactory;

@Override
public Page<OrderResponseDto.Get> getOrders(Pageable pageable, String keyword, Long userId) {
BooleanBuilder builder = new BooleanBuilder();

if (StringUtils.hasText(keyword)) {
builder.and(QProduct.product.name.contains(keyword));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 조건을 위한 index를 설정한다고 어떻게 하면 될까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fullText 인덱스로 설정하는 방법과 일반 like 인덱스로 설정하는 방법 두가지를 찾았습니다.

  • like : 부분 문자열 검색(예: %apple%)에 대해서는 일반적으로 인덱스를 사용할 수 없다. 패턴이 문자열의 시작에서부터 일치해야한다.
  • FullText : 단어 단위로 검색하면 의미 있는 결과를 보다 쉽게 얻을 수 있다. 예를 들어, "apple"을 검색할 때 "apple"이라는 단어를 포함하는 모든 문서를 찾을 수 있다. FULLTEXT 검색은 같은 의미를 가진 다른 형태의 단어(예: "running", "run")도 처리할 수 있다.

이런 이유로 FullText 인덱스로 설정하려고합니다.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FullText 만으로는 iphone16 이라는 상품을 검색할때 'iph' 만으로 찾아지지 않아 like 와 FullText 를 병행하여 사용하도록 수정했습니다. 쿼리 성능은 인덱스를 사용하지 않을때는 0.246 에서 0.121 로 빨라졌습니다

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fulltext를 사용하면 어떻게 이런것들이 가능한걸까요?

}

List<OrderResponseDto.Get> orderList = queryFactory.select(Projections.constructor(OrderResponseDto.Get.class,
QOrder.order.id,
QOrder.order.totalAmount,
QOrder.order.status,
Projections.list(Projections.constructor(OrderDetailResponseDto.Get.class,
QOrderDetail.orderDetail.createdAt,
QOrderDetail.orderDetail.id,
QOrderDetail.orderDetail.productId,
QOrderDetail.orderDetail.quantity,
QOrderDetail.orderDetail.order.id,
QOrderDetail.orderDetail.unitPrice,
QProduct.product.name,
QShipment.shipment.status,
QShipment.shipment.createdAt,
QShipment.shipment.updatedAt
))
))
.from(QOrder.order)
.leftJoin(QOrderDetail.orderDetail).on(QOrder.order.id.eq(QOrderDetail.orderDetail.order.id))
.leftJoin(QProduct.product).on(QOrderDetail.orderDetail.productId.eq(QProduct.product.id))
.leftJoin(QShipment.shipment).on(QOrderDetail.orderDetail.id.eq(QShipment.shipment.orderDetail.id))
.where(QOrder.order.userId.eq(userId).and(builder))
.offset(pageable.getOffset())
.limit(pageable.getPageSize())
.fetch();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 쿼리의 성능은 어느정도가 나올까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

EXPLAIN ANALYZE 를 돌려본 결과 검색어가 없는경우 0.246 검색어가 있는경우는 0.266 이 나왔습니다.
orderDetail 을 inner join 으로 바꾸면 양쪽 테이블에 조건에 맞는 데이터가 있을 때만 조인을 성사하기 때문에 불필요한 orderDetail 데이터를 가져오지 않아 조금 더 빨라진다고 해서 innerJoin 으로 변경하고,
상품명으로 검색하는 부분 products 테이블의 name 을 fullText 인덱스로 사용하려합니다


List<OrderResponseDto.Get> groupedOrderList = orderList.stream()
.collect(Collectors.groupingBy(OrderResponseDto.Get::getId))
.values()
.stream()
.map(orderGroup -> {
OrderResponseDto.Get firstOrder = orderGroup.get(0);
List<OrderDetailResponseDto.Get> allDetails = orderGroup.stream()
.flatMap(order -> order.getOrderDetails().stream())
.collect(Collectors.toList());
firstOrder.setOrderDetails(allDetails);
return firstOrder;
})
.collect(Collectors.toList());

return PageConverter.getPage(groupedOrderList, pageable);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,6 @@ public Page<ProductResponseDto.Get> getProducts(Pageable pageable, String keywor
.leftJoin(QPartner.partner)
.on(QProduct.product.partnerId.eq(QPartner.partner.id))
.where(builder)

//sort, order by
.fetch();

return PageConverter.getPage(products, pageable);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@

import org.example.commerce_site.application.order.OrderFacade;
import org.example.commerce_site.common.response.ApiSuccessResponse;
import org.example.commerce_site.representation.order.request.OrderRequest;
import org.example.commerce_site.representation.order.dto.OrderRequest;
import org.example.commerce_site.representation.order.dto.OrderResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -38,4 +41,15 @@ public ApiSuccessResponse cancelOrder(
orderFacade.cancel(userAuthId, orderId);
return ApiSuccessResponse.success();
}

@GetMapping
public ApiSuccessResponse.PageList<OrderResponse.Get> getOrders(
@RequestParam(value = "page", defaultValue = "1") int page,
@RequestParam(value = "size", defaultValue = "10") int size,
@RequestParam(value = "keyword", required = false) String keyword,
@RequestAttribute("user_id") String userAuthId
) {
return ApiSuccessResponse.success(
OrderResponse.Get.of(orderFacade.getOrderList(page, size, keyword, userAuthId)));
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.example.commerce_site.representation.order.request;
package org.example.commerce_site.representation.order.dto;

import java.math.BigDecimal;
import java.util.List;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package org.example.commerce_site.representation.order.dto;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

import org.example.commerce_site.application.order.dto.OrderDetailResponseDto;
import org.example.commerce_site.application.order.dto.OrderResponseDto;
import org.example.commerce_site.attribute.OrderStatus;
import org.example.commerce_site.attribute.ShipmentStatus;
import org.springframework.data.domain.Page;

import lombok.Builder;
import lombok.Getter;

public class OrderResponse {
@Getter
@Builder
public static class Get {
private Long id;
private BigDecimal totalAmount;
private OrderStatus status;
private List<DetailGet> orderDetails;

public static Get of(OrderResponseDto.Get dto) {
return Get.builder()
.id(dto.getId())
.totalAmount(dto.getTotalAmount())
.status(dto.getStatus())
.orderDetails(DetailGet.of(dto.getOrderDetails()))
.build();
}

public static Page<Get> of(Page<OrderResponseDto.Get> dtos) {
return dtos.map(Get::of);
}
}

@Getter
@Builder
public static class DetailGet {
private LocalDateTime createdAt;
private Long id;
private Long productId;
private Long quantity;
private Long orderId;
private BigDecimal unitPrice;
private String productName;
private ShipmentStatus shipmentStatus;
private LocalDateTime shipmentCreatedAt;
private LocalDateTime shipmentUpdatedAt;

public static DetailGet of(OrderDetailResponseDto.Get dto) {
return DetailGet.builder()
.createdAt(dto.getCreatedAt())
.id(dto.getId())
.productId(dto.getProductId())
.quantity(dto.getQuantity())
.orderId(dto.getOrderId())
.unitPrice(dto.getUnitPrice())
.productName(dto.getProductName())
.shipmentStatus(dto.getShipmentStatus())
.shipmentCreatedAt(dto.getShipmentCreatedAt())
.shipmentUpdatedAt(dto.getShipmentUpdatedAt())
.build();
}

public static List<DetailGet> of(List<OrderDetailResponseDto.Get> dtos) {
return dtos.stream().map(DetailGet::of).toList();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public class ProductController {
@PostMapping()
public ApiSuccessResponse createProduct(
@Valid @RequestBody ProductRequest.Create request,
@RequestAttribute("userId") String userAuthId) {
@RequestAttribute("user_id") String userAuthId) {
productFacade.createProduct(ProductRequest.Create.toDTO(request, userAuthId));
return ApiSuccessResponse.success();
}
Expand All @@ -38,7 +38,7 @@ public ApiSuccessResponse createProduct(
@PatchMapping("/{product_id}")
public ApiSuccessResponse updateProduct(
@PathVariable(name = "product_id") Long productId,
@RequestAttribute("userId") String userAuthId,
@RequestAttribute("user_id") String userAuthId,
@Valid @RequestBody ProductRequest.Update request
) {
productFacade.updateProduct(productId, ProductRequest.Update.toDTO(request, userAuthId));
Expand Down
Loading