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 all 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
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ dependencies {
runtimeOnly 'com.mysql:mysql-connector-j'
annotationProcessor 'org.projectlombok:lombok'
// Project Common Dependency End ----------------------------------------
// HttpComponent for restTemplate connection pool
implementation 'org.apache.httpcomponents.client5:httpclient5:5.3'
implementation 'org.apache.httpcomponents.core5:httpcore5:5.3'

// QueryDsl
implementation 'com.querydsl:querydsl-jpa:5.0.0:jakarta'
Expand Down
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
Expand Up @@ -46,7 +46,11 @@ public enum ErrorCode {
CATEGORY_NOT_FOUND(HttpStatus.NOT_FOUND, 404, "카테고리 정보를 찾을 수 없습니다."),

//shipment
SHIPMENT_NOT_FOUND(HttpStatus.NOT_FOUND, 404, "배송 정보를 찾을 수 없습니다.");
SHIPMENT_NOT_FOUND(HttpStatus.NOT_FOUND, 404, "배송 정보를 찾을 수 없습니다."),

//rest template
REST_TEMPLATE_CONNECTION_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, 500, "Rest template 에러");


private final HttpStatus httpStatus;
private final int code;
Expand Down
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
13 changes: 0 additions & 13 deletions src/main/java/org/example/commerce_site/config/AppConfig.java

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;
}
}
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
Loading
Loading