Skip to content

Commit

Permalink
[48] partner 회원이 보는 주문리스트
Browse files Browse the repository at this point in the history
- 자신이 등록한 상품의 주문 리스트
  • Loading branch information
ohsuha committed Oct 28, 2024
1 parent 0e7668f commit d122f0a
Show file tree
Hide file tree
Showing 7 changed files with 108 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@
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.partner.PartnerService;
import org.example.commerce_site.application.product.ProductService;
import org.example.commerce_site.application.shipment.ShipmentService;
import org.example.commerce_site.application.user.UserService;
import org.example.commerce_site.attribute.OrderStatus;
import org.example.commerce_site.common.domain.BaseTimeEntity;
import org.example.commerce_site.common.domain.IdKeyEntity;
import org.example.commerce_site.common.exception.CustomException;
import org.example.commerce_site.common.exception.ErrorCode;
import org.example.commerce_site.domain.Address;
import org.example.commerce_site.domain.Order;
import org.example.commerce_site.domain.Partner;
import org.example.commerce_site.domain.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
Expand All @@ -27,6 +31,7 @@
@Service
@RequiredArgsConstructor
public class OrderFacade {
private final PartnerService partnerService;
private final UserService userService;
private final OrderService orderService;
private final OrderDetailService orderDetailService;
Expand Down Expand Up @@ -57,8 +62,15 @@ public void cancel(String userAuthId, Long orderId) {
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());
public Page<OrderResponseDto.Get> getOrderList(int page, int size, String keyword, String userAuthId,
String authority) {
IdKeyEntity user = null;
if (authority.equals("ROLE_USER")) {
user = userService.getUser(userAuthId);
} else if (authority.equals("ROLE_PARTNER")) {
user = partnerService.getPartner(userAuthId);
}
return orderService.getOrderList(PageRequest.of(page - 1, size), keyword, user);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
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.domain.IdKeyEntity;
import org.example.commerce_site.common.exception.CustomException;
import org.example.commerce_site.common.exception.ErrorCode;
import org.example.commerce_site.domain.Order;
Expand Down Expand Up @@ -40,7 +41,7 @@ public void updateStatus(Order order, OrderStatus orderStatus) {
}

@Transactional(readOnly = true)
public Page<OrderResponseDto.Get> getOrderList(PageRequest pageRequest, String keyword, Long userId) {
return customOrderRepository.getOrders(pageRequest, keyword, userId);
public <T extends IdKeyEntity> Page<OrderResponseDto.Get> getOrderList(PageRequest pageRequest, String keyword, T user) {
return customOrderRepository.getOrders(pageRequest, keyword, user);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,5 +64,10 @@ public static class GetList {
private ShipmentStatus shipmentStatus;
private LocalDateTime shipmentCreatedAt;
private LocalDateTime shipmentUpdatedAt;
private String phoneNumber;
private String postalCode;
private String roadAddress;
private String jibunAddress;
private String addressDetail;
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package org.example.commerce_site.infrastructure.order;

import org.example.commerce_site.application.order.dto.OrderResponseDto;
import org.example.commerce_site.common.domain.IdKeyEntity;
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);
<T extends IdKeyEntity> Page<OrderResponseDto.Get> getOrders(Pageable pageable, String keyword, T user);
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
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.domain.IdKeyEntity;
import org.example.commerce_site.common.util.PageConverter;
import org.example.commerce_site.domain.Partner;
import org.flywaydb.core.internal.util.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
Expand All @@ -32,16 +34,32 @@ public class CustomOrderRepositoryImpl implements CustomOrderRepository {
private final EntityManager entityManager;

@Override
public Page<OrderResponseDto.Get> getOrders(Pageable pageable, String keyword, Long userId) {
public <T extends IdKeyEntity> Page<OrderResponseDto.Get> getOrders(Pageable pageable, String keyword, T user) {
boolean isPartner = false;

if (user instanceof Partner) {
isPartner = true;
}

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 " +
"s.created_at AS shipment_created_at, s.updated_at AS shipment_updated_at, " +
"a.phone_number AS phone_number, a.postal_code AS postal_code, " +
"a.road_address AS road_address, a.jibun_address AS jibun_address, " +
"a.address_detail AS address_detail " +
"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 ");
"LEFT JOIN addresses a ON s.address_id = a.id "
);

if (isPartner) {
sql.append("WHERE p.partner_id = :partnerId ");
} else {
sql.append("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) " +
Expand All @@ -51,7 +69,13 @@ public Page<OrderResponseDto.Get> getOrders(Pageable pageable, String keyword, L
sql.append("ORDER BY o.created_at LIMIT :pageSize OFFSET :offset");

Query query = entityManager.createNativeQuery(sql.toString());
query.setParameter("userId", userId);

if (isPartner) {
query.setParameter("partnerId", user.getId());
} else {
query.setParameter("userId", user.getId());
}

query.setParameter("pageSize", pageable.getPageSize());
query.setParameter("offset", pageable.getOffset());

Expand All @@ -63,21 +87,26 @@ public Page<OrderResponseDto.Get> getOrders(Pageable pageable, String keyword, L

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]); // 주문 상태
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
(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
(String)row[13],
(String)row[14],
(String)row[15],
(String)row[16],
(String)row[17]
);

OrderResponseDto.Get orderResponse = orderMap.get(orderId);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
package org.example.commerce_site.representation.order;

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

import org.example.commerce_site.application.order.OrderFacade;
import org.example.commerce_site.common.exception.CustomException;
import org.example.commerce_site.common.exception.ErrorCode;
import org.example.commerce_site.common.response.ApiSuccessResponse;
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.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
Expand All @@ -16,14 +24,16 @@
import org.springframework.web.bind.annotation.RestController;

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

@Slf4j
@RestController
@RequiredArgsConstructor
@PreAuthorize("hasAuthority('ROLE_USER')")
@RequestMapping("/orders")
public class OrderController {
private final OrderFacade orderFacade;

@PreAuthorize("hasAuthority('ROLE_USER')")
@PostMapping()
public ApiSuccessResponse createOrder(
@RequestAttribute("user_id") String userAuthId,
Expand All @@ -33,6 +43,7 @@ public ApiSuccessResponse createOrder(
return ApiSuccessResponse.success();
}

@PreAuthorize("hasAuthority('ROLE_USER')")
@DeleteMapping("/{order_id}")
public ApiSuccessResponse cancelOrder(
@RequestAttribute("user_id") String userAuthId,
Expand All @@ -49,7 +60,20 @@ public ApiSuccessResponse.PageList<OrderResponse.Get> getOrders(
@RequestParam(value = "keyword", required = false) String keyword,
@RequestAttribute("user_id") String userAuthId
) {
Collection<? extends GrantedAuthority> authorities = SecurityContextHolder
.getContext()
.getAuthentication()
.getAuthorities();

Optional<String> primaryAuthority = authorities.stream()
.findFirst()
.map(GrantedAuthority::getAuthority);

if (primaryAuthority.isEmpty()) {
throw new CustomException(ErrorCode.ACCESS_DENIED);
}

return ApiSuccessResponse.success(
OrderResponse.Get.of(orderFacade.getOrderList(page, size, keyword, userAuthId)));
OrderResponse.Get.of(orderFacade.getOrderList(page, size, keyword, userAuthId, primaryAuthority.get())));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ public static class DetailGet {
private ShipmentStatus shipmentStatus;
private LocalDateTime shipmentCreatedAt;
private LocalDateTime shipmentUpdatedAt;
private String phoneNumber;
private String postalCode;
private String roadAddress;
private String jibunAddress;
private String addressDetail;


public static DetailGet of(OrderDetailResponseDto.GetList dto) {
return DetailGet.builder()
Expand All @@ -62,6 +68,11 @@ public static DetailGet of(OrderDetailResponseDto.GetList dto) {
.shipmentStatus(dto.getShipmentStatus())
.shipmentCreatedAt(dto.getShipmentCreatedAt())
.shipmentUpdatedAt(dto.getShipmentUpdatedAt())
.phoneNumber(dto.getPhoneNumber())
.postalCode(dto.getPostalCode())
.roadAddress(dto.getRoadAddress())
.jibunAddress(dto.getJibunAddress())
.addressDetail(dto.getAddressDetail())
.build();
}

Expand Down

0 comments on commit d122f0a

Please sign in to comment.