Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@
import java.util.List;
import java.util.UUID;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface AppliedCouponRepository extends JpaRepository<AppliedCoupon, UUID> {
List<AppliedCoupon> findByCouponId(UUID couponId);

boolean existsByCouponId(UUID couponId);

void deleteByPayment(Payment payment);

List<AppliedCoupon> findByPayment_PaymentId(UUID paymentId);
}
Comment thread
Bal1oon marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.irum.come2us.domain.order.application.service;

import com.irum.come2us.domain.coupon.domain.repository.AppliedCouponRepository;
import com.irum.come2us.domain.order.application.mapper.OrderMapper;
import com.irum.come2us.domain.order.domain.entity.Order;
import com.irum.come2us.domain.order.domain.entity.OrderDetail;
Expand All @@ -9,11 +10,18 @@
import com.irum.come2us.domain.order.infrastructure.repository.dto.OrderDetailRow;
import com.irum.come2us.domain.order.infrastructure.repository.dto.OrderSummaryRow;
import com.irum.come2us.domain.order.presentation.dto.request.OwnerOrderShippedRequest;
import com.irum.come2us.domain.order.presentation.dto.response.AddressResponse;
import com.irum.come2us.domain.order.presentation.dto.response.OrderDetailResponse;
import com.irum.come2us.domain.order.presentation.dto.response.OwnerOrderListResponse;
import com.irum.come2us.domain.payment.domain.repository.PaymentRepository;
import com.irum.come2us.domain.refund.domain.entity.Refund;
import com.irum.come2us.domain.refund.domain.entity.enums.RefundStatus;
import com.irum.come2us.domain.refund.domain.repository.RefundRepository;
import com.irum.come2us.global.presentation.advice.exception.CommonException;
import com.irum.come2us.global.presentation.advice.exception.errorcode.OrderErrorCode;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
Expand All @@ -28,7 +36,10 @@
public class OwnerOrderService {
private final OrderDetailRepository orderDetailRepository;
private final OrderRepository orderRepository;
private final PaymentRepository paymentRepository;
private final RefundRepository refundRepository;
private final OrderMapper orderMapper;
private final AppliedCouponRepository appliedCouponRepository;

@Transactional(readOnly = true)
public OwnerOrderListResponse getPreparingOrderList(UUID storeId, UUID cursor, Integer size) {
Expand Down Expand Up @@ -175,10 +186,12 @@ public void updateOrderStatusToDelivered(UUID orderDetailId) {
/** OrderDetail 상태 목록을 기반으로 집계된(Aggregated) Order의 상태를 결정 */
private OrderStatus aggregateOrderStatus(OrderDetail orderDetail) {

Order order =
orderRepository
.findByOrderId(orderDetail.getOrder().getOrderId())
.orElseThrow(() -> new CommonException(OrderErrorCode.ORDER_NOT_FOUND));
// Order order =
// orderRepository
// .findByOrderId(orderDetail.getOrder().getOrderId())
// .orElseThrow(() -> new
// CommonException(OrderErrorCode.ORDER_NOT_FOUND));
Order order = orderDetail.getOrder();
List<OrderDetail> orderDetailList = orderDetailRepository.findAllByOrder(order);
List<OrderStatus> orderStatusList =
orderDetailList.stream().map(OrderDetail::getOrderStatusIndi).toList();
Expand Down Expand Up @@ -221,4 +234,86 @@ else if (preparingCount == totalCount) {
// 모든 정책에 해당하지 않는 경우
return OrderStatus.PREPARING;
}

@Transactional(readOnly = true)
public OrderDetailResponse detailResponse(UUID orderId) {
Order order =
orderRepository
.findByOrderId(orderId)
.orElseThrow(() -> new CommonException(OrderErrorCode.ORDER_NOT_FOUND));

List<OrderDetailResponse.ProductResponse> productList =
order.getOrderDetails().stream()
.map(
od ->
OrderDetailResponse.ProductResponse.builder()
.productName(od.getProductName())
.optionTitle(od.getOptionName())
.quantity(od.getQuantity())
.price(od.getPrice())
.receivedDate(
od.getArrivedDate() != null
? od.getArrivedDate().toLocalDate()
: null)
.build())
.toList();
String couponName = getCouponName(order.getPayment().getPaymentId());
int discountAmount = getDiscountAmount(order.getPayment().getPaymentId());
// 아직 결제 상태 Field 없음
String trackingNumber =
order.getOrderDetails().stream()
.map(od -> od.getTrackingNumber())
.filter(Objects::nonNull)
.findFirst()
.map(dt -> dt.toString())
.orElse(null);

String arrivedDate =
order.getOrderDetails().stream()
.map(od -> od.getArrivedDate())
.filter(Objects::nonNull)
.findFirst()
.map(dt -> dt.toString())
.orElse(null);

int deliveryFee = order.getDeliveryFee() != null ? order.getDeliveryFee() : 0;
int totalProductPrice = order.getTotalPrice() != null ? order.getTotalPrice() : 0;
int totalPaymentPrice = totalProductPrice + deliveryFee - discountAmount;

RefundStatus refundStatus =
refundRepository
.findFirstByOrderOrderByCreatedAtDesc(order)
.map(Refund::getRefundStatus)
.orElse(null);

AddressResponse address = AddressResponse.from(order.getDeliveryAddress().getAddress());

return new OrderDetailResponse(
order.getCreatedAt(),
order.getPayment() != null ? order.getPayment().getPaymentStatus() : null,
order.getPayment() != null ? order.getPayment().getPaymentMethod() : null,
deliveryFee,
discountAmount,
totalProductPrice,
totalPaymentPrice,
order.getOrderStatusAll(),
refundStatus,
order.getDeliveryRequest(),
address,
order.getDeliveryAddress().getRecipientContact(),
order.getDeliveryAddress().getRecipientName(),
productList);
}

private String getCouponName(UUID paymentId) {
return appliedCouponRepository.findByPayment_PaymentId(paymentId).stream()
.findFirst()
.map(ac -> ac.getCoupon().getName())
.orElse(null);
}

private int getDiscountAmount(UUID paymentId) {
Integer sum = paymentRepository.getTotalDiscountByPaymentId(paymentId);
return sum != null ? sum : 0;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package com.irum.come2us.domain.order.application.service;

import com.irum.come2us.domain.member.domain.entity.Member;
import com.irum.come2us.domain.order.domain.entity.Order;
import com.irum.come2us.domain.order.domain.repository.OrderRepository;
import com.irum.come2us.domain.order.presentation.dto.response.BalanceResponse;
import com.irum.come2us.domain.order.presentation.dto.response.SalesResponse;
import com.irum.come2us.domain.refund.domain.entity.Refund;
import com.irum.come2us.domain.refund.domain.entity.enums.RefundStatus;
import com.irum.come2us.domain.refund.domain.repository.RefundRepository;
import com.irum.come2us.domain.store.domain.entity.Store;
import com.irum.come2us.domain.store.domain.repository.StoreRepository;
import com.irum.come2us.global.presentation.advice.exception.CommonException;
import com.irum.come2us.global.presentation.advice.exception.errorcode.StoreErrorCode;
import com.irum.come2us.global.util.MemberUtil;
import java.util.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class SalesService {
private final StoreRepository storeRepository;
private final OrderRepository orderRepository;
private final RefundRepository refundRepository;
private final MemberUtil memberUtil;

public SalesResponse getSalesList(UUID storeId) {
Member member = memberUtil.getCurrentMember();
Store store =
storeRepository
.findById(storeId)
.orElseThrow(() -> new CommonException(StoreErrorCode.STORE_NOT_FOUND));
Comment thread
Bal1oon marked this conversation as resolved.
memberUtil.assertMemberResourceAccess(store.getMember());

List<Order> orders = orderRepository.findAllByMember(member);
List<SalesResponse.OrderSummary> orderList =
orders.stream().map(this::toOrderSummary).toList();
return new SalesResponse(orderList, null, false);
}

private SalesResponse.OrderSummary toOrderSummary(Order order) {
String displayStatus = DisplayStatus(order);

List<SalesResponse.ProductSummary> productList =
order.getOrderDetails().stream()
.map(
detail ->
new SalesResponse.ProductSummary(
detail.getOrderDetailId(),
detail.getProduct().getName(),
detail.getQuantity(),
detail.getPrice(),
detail.getOptionName()))
.toList();

return new SalesResponse.OrderSummary(
order.getOrderId(),
order.getDeliveryAddress().getRecipientName(),
order.getDeliveryAddress().getRecipientContact(),
order.getDeliveryAddress().getAddress().toString(),
order.getCreatedAt(),
order.getTotalPrice(),
0,
order.getTotalPrice() + order.getDeliveryFee(),
order.getDeliveryFee(),
productList,
displayStatus);
}

// 환불 존재시 환불 상태 반환, 환불 존재하지 않으면 주문 상태 반환
private String DisplayStatus(Order order) {
Optional<Refund> latestRefundOpt =
refundRepository.findFirstByOrderOrderByCreatedAtDesc(order);

if (latestRefundOpt.isPresent()) {
Refund latestRefund = latestRefundOpt.get();
RefundStatus refundStatus = latestRefund.getRefundStatus();

if (refundStatus != RefundStatus.REJECTED) {
return refundStatus.name();
}
}
return order.getOrderStatusAll().name();
}

@Transactional(readOnly = true)
public BalanceResponse getBalance(UUID storeId) {
// 1. 해당 스토어의 모든 주문 가져오기
List<Order> orders = orderRepository.findAllByMember(memberUtil.getCurrentMember());

// 2. 총 결제 금액 계산
int totalPaymentAmount =
orders.stream().map(Order::getTotalPrice).mapToInt(Integer::intValue).sum();

// 3. 환불된 금액 계산
List<Refund> refunds =
refundRepository.findAll(); // 또는 findByOrder_StoreIdAndRefundStatus(...)
int totalRefundAmount =
refunds.stream()
.filter(refund -> refund.getOrder().getStore().getId().equals(storeId))
.mapToInt(Refund::getPrice)
.sum();

// 4. 정산 금액 계산
int settlementAmount = totalPaymentAmount - totalRefundAmount;

return new BalanceResponse(totalPaymentAmount, totalRefundAmount, settlementAmount);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import com.irum.come2us.domain.store.domain.entity.Store;
import com.irum.come2us.global.domain.BaseEntity;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import lombok.*;
import org.hibernate.annotations.SQLDelete;
Expand Down Expand Up @@ -56,6 +58,11 @@ public class Order extends BaseEntity {
@JoinColumn(name = "delivery_address_id")
private DeliveryAddress deliveryAddress;

@OneToMany(mappedBy = "order", fetch = FetchType.LAZY)
private List<OrderDetail> orderDetails = new ArrayList<>();

// 한 주문당 여러 상품이 담겨있기 때문에 List 추가

public void updateOrderStatus(OrderStatus os) {
this.orderStatusAll = os;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.irum.come2us.domain.order.presentation.controller;

import com.irum.come2us.domain.order.application.service.OwnerOrderService;
import com.irum.come2us.domain.order.application.service.SalesService;
import com.irum.come2us.domain.order.presentation.dto.request.OwnerOrderShippedRequest;
import com.irum.come2us.domain.order.presentation.dto.response.OrderDetailResponse;
import com.irum.come2us.domain.order.presentation.dto.response.OwnerOrderListResponse;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
Expand All @@ -15,6 +17,7 @@
@Slf4j
public class OwnerOrderController {
private final OwnerOrderService ownerOrderService;
private final SalesService salesService;

/** [상점] 배송 준비 중 목록 조회 * */
@GetMapping("/{storeId}/preparing")
Expand Down Expand Up @@ -73,4 +76,11 @@ public ResponseEntity<Void> orderStatusToDeliveredUpdate(@PathVariable UUID orde
ownerOrderService.updateOrderStatusToDelivered(orderDetailId);
return ResponseEntity.noContent().build();
}

/* [상점] 주문 상세 */
@GetMapping("/{orderId}")
public ResponseEntity<OrderDetailResponse> ownerOrderDetail(@PathVariable UUID orderId) {
OrderDetailResponse response = ownerOrderService.detailResponse(orderId);
return ResponseEntity.ok(response);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.irum.come2us.domain.order.presentation.controller;

import com.irum.come2us.domain.order.application.service.SalesService;
import com.irum.come2us.domain.order.presentation.dto.response.BalanceResponse;
import com.irum.come2us.domain.order.presentation.dto.response.SalesResponse;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("/orders")
public class SalesController {
private final SalesService salesService;

// 총 주문 내역
@GetMapping("/{storeId}/sales")
public ResponseEntity<SalesResponse> salesResponse(@PathVariable UUID storeId) {
SalesResponse response = salesService.getSalesList(storeId);
return ResponseEntity.ok(response);
}

// 정산 내역 조회
@GetMapping("/{storeId}/balance")
public ResponseEntity<BalanceResponse> getBalance(@PathVariable UUID storeId) {
BalanceResponse response = salesService.getBalance(storeId);
return ResponseEntity.ok(response);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.irum.come2us.domain.order.presentation.dto.response;

public record BalanceResponse(
int totalSalesAmount, // 총 결제 금액 합계
int totalRefundAmount, // 총 환불 금액 합계
int settlementAmount // 정산 금액 (총 금액 - 환불 금액)
) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.irum.come2us.domain.order.presentation.dto.response;

import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

public record OwnerOrderDetailResponse(
List<OrderSummary> orderList, UUID nextCursor, boolean hasNext) {
public record OrderSummary(
UUID orderId,
String recipientName,
String recipientContact,
String recipientAddress,
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime orderDate,
int totalProductPrice,
int discountAmount,
int payingAmount,
int deliveryFee,
List<ProductSummary> productList) {}

public record ProductSummary(
UUID orderDetailId,
String productName,
int productCounts,
int productPrice,
String optionTitle) {}
}
Loading