-
Notifications
You must be signed in to change notification settings - Fork 0
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
Changes from all commits
700d0d8
d62f2a3
0e7668f
6ac59cb
7881ce6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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; | ||
|
@@ -8,7 +9,16 @@ | |
|
||
public class PageConverter { | ||
public static <T> Page<T> getPage(List<T> content, Pageable pageable) { | ||
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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이건 어떤 경우를 처리하는거에요? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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()); | ||
|
This file was deleted.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
package org.example.commerce_site.config; | ||
|
||
import java.io.IOException; | ||
import java.util.concurrent.TimeUnit; | ||
|
||
import org.apache.hc.client5.http.config.RequestConfig; | ||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; | ||
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; | ||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; | ||
import org.example.commerce_site.common.exception.CustomException; | ||
import org.example.commerce_site.common.exception.ErrorCode; | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.http.client.ClientHttpResponse; | ||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; | ||
import org.springframework.web.client.ResponseErrorHandler; | ||
import org.springframework.web.client.RestTemplate; | ||
|
||
import lombok.extern.slf4j.Slf4j; | ||
|
||
@Slf4j | ||
@Configuration | ||
public class RestTemplateConfig { | ||
@Bean | ||
RestTemplate restTemplate() { | ||
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); | ||
connectionManager.setMaxTotal(100); | ||
connectionManager.setDefaultMaxPerRoute(30); | ||
|
||
RequestConfig requestConfig = RequestConfig.custom() | ||
.setResponseTimeout(5000, TimeUnit.MILLISECONDS) | ||
.build(); | ||
|
||
CloseableHttpClient httpClient = HttpClientBuilder.create() | ||
.setDefaultRequestConfig(requestConfig) | ||
.setConnectionManager(connectionManager) | ||
.build(); | ||
|
||
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); | ||
factory.setConnectTimeout(3000); | ||
factory.setHttpClient(httpClient); | ||
|
||
RestTemplate restTemplate = new RestTemplate(factory); | ||
|
||
restTemplate.setErrorHandler(new ResponseErrorHandler() { | ||
@Override | ||
public boolean hasError(ClientHttpResponse response) throws IOException { | ||
return response.getStatusCode().is4xxClientError() || response.getStatusCode().is5xxServerError(); | ||
} | ||
|
||
@Override | ||
public void handleError(ClientHttpResponse response) throws IOException { | ||
log.error("Error occurred : {} ", response.getStatusCode()); | ||
log.error("Error response message : {}", response.getBody()); | ||
throw new CustomException(ErrorCode.REST_TEMPLATE_CONNECTION_ERROR); | ||
} | ||
}); | ||
|
||
return restTemplate; | ||
} | ||
} |
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; | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
content 전체를 받고 일부를 잘라서 사용하는 것 같은데, 전체 row의 갯수가 엄청 많아지면 무슨일이 생길까요?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
굳이 필요없는 데이터까지 가져오므로 많이 느려질것같네요.. 쿼리에서 limit 을 주고 Total 값을 얻는 쿼리를 한번 더 돌리는 방법으로 수정 하겠습니다..!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이부분 [48] 파트너회원 order list 브랜치에서 반영했습니다..!