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 2 commits
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,15 +4,18 @@
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;
Expand Down Expand Up @@ -47,4 +50,19 @@ public static List<OrderDetailResponseDto.Get> toDtoList(List<OrderDetail> order
return orderDetails.stream().map(Get::toDto).toList();
}
}

@Getter
@AllArgsConstructor
public static class GetList {
private Long id;
private LocalDateTime createdAt;
private Long productId;
private Long quantity;
private Long orderId;
private BigDecimal unitPrice;
private String productName;
private ShipmentStatus shipmentStatus;
private LocalDateTime shipmentCreatedAt;
private LocalDateTime shipmentUpdatedAt;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
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.Getter;

public class OrderResponseDto {
@Getter
@AllArgsConstructor
public static class Get {
private Long id;
private BigDecimal totalAmount;
private OrderStatus status;
private List<OrderDetailResponseDto.GetList> 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,100 @@
package org.example.commerce_site.infrastructure.order;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.example.commerce_site.common.util.PageConverter;
import org.flywaydb.core.internal.util.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Repository
@RequiredArgsConstructor
public class CustomOrderRepositoryImpl implements CustomOrderRepository {
@PersistenceContext
private final EntityManager entityManager;

@Override
public Page<OrderResponseDto.Get> getOrders(Pageable pageable, String keyword, Long userId) {
StringBuilder sql = new StringBuilder("SELECT o.id, o.total_amount, o.status, " +
"od.id AS order_detail_id, od.created_at, od.product_id, od.quantity, " +
"od.order_id, od.unit_price, p.name AS product_name, s.status AS shipment_status, " +
"s.created_at AS shipment_created_at, s.updated_at AS shipment_updated_at " +
"FROM orders o " +
"INNER JOIN order_details od ON o.id = od.order_id " +
"LEFT JOIN products p ON od.product_id = p.id " +
"LEFT JOIN shipments s ON od.id = s.order_detail_id " +
"WHERE o.user_id = :userId ");

if (StringUtils.hasText(keyword)) {
sql.append("AND p.name IS NOT NULL AND (MATCH(p.name) AGAINST (:keyword IN BOOLEAN MODE) " +
"OR p.name LIKE CONCAT(:keyword, '%')) ");
}

sql.append("ORDER BY o.created_at LIMIT :pageSize OFFSET :offset");

Query query = entityManager.createNativeQuery(sql.toString());
query.setParameter("userId", userId);
query.setParameter("pageSize", pageable.getPageSize());
query.setParameter("offset", pageable.getOffset());

if (StringUtils.hasText(keyword)) {
query.setParameter("keyword", keyword);
}

List<Object[]> resultList = query.getResultList();

Map<Long, OrderResponseDto.Get> orderMap = new HashMap<>();
for (Object[] row : resultList) {
Long orderId = (Long) row[0]; // 주문 ID
BigDecimal totalAmount = BigDecimal.valueOf((Long) row[1]); // 총 금액
OrderStatus orderStatus = OrderStatus.valueOf((String) row[2]); // 주문 상태

OrderDetailResponseDto.GetList orderDetail = new OrderDetailResponseDto.GetList(
(Long) row[3], // orderDetailId
convertTimestampToLocalDateTime((Timestamp) row[4]), // createdAt
(Long) row[5], // productId
(Long) row[6], // quantity
(Long) row[7], // orderId
BigDecimal.valueOf((Long) row[8]), // unitPrice
(String) row[9], // productName
ShipmentStatus.valueOf((String) row[10]), // shipmentStatus
convertTimestampToLocalDateTime((Timestamp) row[11]), // shipmentCreatedAt
convertTimestampToLocalDateTime((Timestamp) row[12]) // shipmentUpdatedAt
);

OrderResponseDto.Get orderResponse = orderMap.get(orderId);
if (orderResponse == null) {
orderResponse = new OrderResponseDto.Get(orderId, totalAmount, orderStatus, new ArrayList<>());
orderMap.put(orderId, orderResponse);
}

orderResponse.getOrderDetails().add(orderDetail);
}

List<OrderResponseDto.Get> orderList = new ArrayList<>(orderMap.values());

return PageConverter.getPage(orderList, pageable);
}

private LocalDateTime convertTimestampToLocalDateTime(Timestamp timestamp) {
return timestamp != null ? timestamp.toLocalDateTime() : null;
}
}
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.GetList 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.GetList> dtos) {
return dtos.stream().map(DetailGet::of).toList();
}
}
}
Loading
Loading