Skip to content

Commit

Permalink
Merge pull request #118 from Orange-Co/feature/item
Browse files Browse the repository at this point in the history
feat: implement delete item api
  • Loading branch information
Kang1221 authored Oct 8, 2024
2 parents 17ac69f + e2259a5 commit 7c048cb
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 26 deletions.
4 changes: 2 additions & 2 deletions src/main/java/co/orange/ddanzi/common/response/Success.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ public enum Success {
DELETE_USER_SUCCESS(HttpStatus.OK, "Successfully deleted the user."),
DELETE_INTEREST_SUCCESS(HttpStatus.OK, "Successfully removed the product from interest List."),
DELETE_ADDRESS_SUCCESS(HttpStatus.OK, "Successfully deleted the delivery address."),
DELETE_ACCOUNT_SUCCESS(HttpStatus.OK, "Successfully deleted the account"),

DELETE_ACCOUNT_SUCCESS(HttpStatus.OK, "Successfully deleted the account."),
DELETE_ITEM_SUCCESS(HttpStatus.OK, "Successfully deleted the item."),

// 201 CREATED
SIGNIN_KAKAO_SUCCESS(HttpStatus.CREATED, "Successfully sign in using Kakao"),
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/co/orange/ddanzi/controller/ItemController.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ ApiResponse<?> getItem(@PathVariable("id") String id) {
return itemService.getItem(id);
}

@DeleteMapping("/{id}")
ApiResponse<?> deleteItem(@PathVariable("id") String id) {
return itemService.deleteItem(id);
}

@GetMapping("/order/{id}")
ApiResponse<?> getAddressAndOption(@PathVariable("id") String id) {
return itemService.getAddressAndOption(id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ public enum ItemStatus {
ON_SALE("판매중"),
IN_TRANSACTION("거래중"),
EXPIRED("만료됨"),
CLOSED("거래완료")
CLOSED("거래완료"),
DELETED("삭제됨")
;

private final String itemStatus;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public interface OrderRepository extends JpaRepository<Order, String> {
List<Order> findByBuyerAndStatus(User user);

@Query("SELECT o FROM Order o WHERE o.item = :item AND o.status <> 'ORDER_PENDING'")
Optional<Order> findByItemAnAndStatus(@Param("item") Item item);
Optional<Order> findByItemAndStatus(@Param("item") Item item);

@Query("SELECT o FROM Order o WHERE o.status = :orderStatus AND o.updatedAt <= :dateTime")
List<Order> findOverLimitTimeOrders(OrderStatus orderStatus, LocalDateTime dateTime);
Expand Down
51 changes: 42 additions & 9 deletions src/main/java/co/orange/ddanzi/service/ItemService.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
import co.orange.ddanzi.domain.order.Order;
import co.orange.ddanzi.domain.order.OrderOptionDetail;
import co.orange.ddanzi.domain.order.Payment;
import co.orange.ddanzi.domain.order.enums.PayStatus;
import co.orange.ddanzi.domain.product.Discount;
import co.orange.ddanzi.domain.product.Item;
import co.orange.ddanzi.domain.product.Product;
import co.orange.ddanzi.domain.product.enums.ItemStatus;
import co.orange.ddanzi.domain.user.User;
import co.orange.ddanzi.domain.user.enums.FcmCase;
import co.orange.ddanzi.dto.common.AddressSeparateInfo;
import co.orange.ddanzi.dto.item.*;
import co.orange.ddanzi.common.error.Error;
Expand All @@ -22,6 +24,7 @@
import co.orange.ddanzi.repository.*;
import co.orange.ddanzi.service.common.AddressService;
import co.orange.ddanzi.service.common.GcsService;
import co.orange.ddanzi.service.common.HistoryService;
import co.orange.ddanzi.service.common.TermService;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
Expand All @@ -48,14 +51,13 @@ public class ItemService {
private final OrderOptionDetailRepository orderOptionDetailRepository;
private final InterestProductRepository interestProductRepository;

@Autowired
GcsService gcsService;
@Autowired
TermService termService;
@Autowired
AddressService addressService;
@Autowired
private PaymentRepository paymentRepository;
private final GcsService gcsService;
private final TermService termService;
private final AddressService addressService;
private final PaymentService paymentService;
private final PaymentRepository paymentRepository;
private final HistoryService historyService;


@Transactional
public ApiResponse<?> createSignedUrl(String fileName){
Expand Down Expand Up @@ -106,7 +108,7 @@ public ApiResponse<?> getItem(String itemId){
return ApiResponse.onFailure(Error.ITEM_UNAUTHORIZED_USER, null);

//get latest order
Order order = orderRepository.findByItemAnAndStatus(item).orElse(null);
Order order = orderRepository.findByItemAndStatus(item).orElse(null);

Payment payment = null;
if(order!=null)
Expand All @@ -132,6 +134,37 @@ public ApiResponse<?> getItem(String itemId){
return ApiResponse.onSuccess(Success.GET_ITEM_PRODUCT_SUCCESS, responseDto);
}

@Transactional
public ApiResponse<?> deleteItem(String itemId){
User user = authUtils.getUser();
Item item = itemRepository.findById(itemId).orElseThrow(ItemNotFoundException::new);
if(!item.getSeller().equals(user))
return ApiResponse.onFailure(Error.ITEM_UNAUTHORIZED_USER, null);

Order order = orderRepository.findByItemAndStatus(item).orElse(null);
if(order==null){
log.info("거래 취소 중 - 거래중이지 않아 바로 제품을 삭제합니다.");
item.updateStatus(ItemStatus.DELETED);
}
else{
log.info("거래 취소 중 - 거래중인 상품이 있습니다. 대안을 탐색합니다.");
Item newItem = itemRepository.findNearestExpiryItem(item.getProduct()).orElse(null);
if(newItem == null) {
log.info("환불을 진행합니다.");
Payment payment = paymentRepository.findByOrder(order);
User buyer = order.getBuyer();
try {
paymentService.refundPayment(buyer, order, "현재 남은 재고가 없어 고객에게 결제 금액 환불합니다.");
payment.updatePaymentStatusAndEndedAt(PayStatus.CANCELLED);
historyService.createPaymentHistoryWithError(buyer, payment, "재퓸 삭제- 환불 처리 성공");
}catch (Exception e){
historyService.createPaymentHistoryWithError(buyer, payment, "제품 삭제 - 환불 처리 실패");
return ApiResponse.onFailure(Error.REFUND_FAILED, Map.of("orderId", order.getId()));
}
}
}
return ApiResponse.onSuccess(Success.DELETE_ITEM_SUCCESS, true);
}

@Transactional
public ApiResponse<?> getAddressAndOption(String orderId){
Expand Down
6 changes: 1 addition & 5 deletions src/main/java/co/orange/ddanzi/service/OrderService.java
Original file line number Diff line number Diff line change
Expand Up @@ -170,11 +170,6 @@ public Order getOrderRecord(String orderId){
return orderRepository.findById(orderId).orElseThrow(() -> new OrderNotFoundException());
}

/**
* 환불 API 붙이기!!!!!!
*
*
*/
@Transactional
public void checkOrderPlacedOrder(){
//입금 후 1일(24시간)이 지났는데, 판매확정이 되지 않았을 시 - 거래 취소
Expand All @@ -183,6 +178,7 @@ public void checkOrderPlacedOrder(){
for(Order order : orderPlaceOrders){
fcmService.sendMessageToUser(order.getItem().getSeller(), FcmCase.A2, order);
fcmService.sendMessageToUser(order.getBuyer(), FcmCase.B1, order);
paymentService.refundPayment(order.getBuyer(), order, "고객이 판매확정을 하지 않아 거래가 취소되어 결제 금액을 환불합니다.");
order.updateStatus(OrderStatus.CANCELLED);
}
}
Expand Down
16 changes: 8 additions & 8 deletions src/main/java/co/orange/ddanzi/service/PaymentService.java
Original file line number Diff line number Diff line change
Expand Up @@ -86,16 +86,15 @@ public ApiResponse<?> endPayment(UpdatePaymentRequestDto requestDto){
return ApiResponse.onFailure(Error.PAYMENT_CANNOT_CHANGE, null);
}

if(item.getStatus().equals(ItemStatus.IN_TRANSACTION)){
log.info("해당 제품은 이미 결제 되어 새로운 제품을 탐색합니다.");
if(item.getStatus().equals(ItemStatus.IN_TRANSACTION) || item.getStatus().equals(ItemStatus.DELETED)){
log.info("해당 제품은 거래불가능하여 새로운 제품을 탐색합니다.");
Item newItem = itemRepository.findNearestExpiryItem(product).orElse(null);
if(newItem == null){
log.info("환불을 진행합니다.");
try {
refundPayment(buyer, order);
refundPayment(buyer, order, "현재 남은 재고가 없어 고객에게 결제 금액 환불합니다.");
payment.updatePaymentStatusAndEndedAt(PayStatus.CANCELLED);
historyService.createPaymentHistoryWithError(buyer, payment, "재고 없음- 환불 처리");
fcmService.sendMessageToAdmin(FcmCase.C3);
historyService.createPaymentHistoryWithError(buyer, payment, "재고 없음- 환불 처리 성공");
return ApiResponse.onFailure(Error.NO_ITEM_ON_SALE, Map.of("orderId", order.getId()));
}catch (Exception e){
historyService.createPaymentHistoryWithError(buyer, payment, "재고 없음 - 환불 처리 실패");
Expand Down Expand Up @@ -146,7 +145,7 @@ public ApiResponse<?> refundTest(UpdatePaymentRequestDto requestDto){
User buyer = authUtils.getUser();
Order order = orderService.getOrderRecord(requestDto.getOrderId());
Payment payment = paymentRepository.findByOrder(order);
refundPayment(buyer, order);
refundPayment(buyer, order, "테스트용 환불입니다.");
return ApiResponse.onSuccess(Success.SUCCESS, true);
}

Expand Down Expand Up @@ -181,7 +180,7 @@ public String getPortOneAccessToken(){
return response.getBody().getResponse().getAccess_token();
}

public void refundPayment(User user, Order order){
public void refundPayment(User user, Order order, String reason){
if(!user.equals(order.getBuyer()))
throw new RuntimeException("결제자와 요청자가 다르므로 환불이 어렵습니다.");
String baseUrl = "https://api.iamport.kr/payments/cancel";
Expand All @@ -196,7 +195,7 @@ public void refundPayment(User user, Order order){

RefundRequestDto requestDto = RefundRequestDto.builder()
.merchant_uid(order.getId())
.reason("현재 남은 재고가 없어 고객에게 결제 금액 환불합니다.")
.reason(reason)
.build();

HttpEntity<Object> entity = new HttpEntity<>(requestDto, headers);
Expand All @@ -205,6 +204,7 @@ public void refundPayment(User user, Order order){
RestTemplate restTemplate = new RestTemplate();
restTemplate.postForObject(url, entity, String.class);
log.info("결제 취소 api 호출");
fcmService.sendMessageToAdmin(FcmCase.C3);
}

}

0 comments on commit 7c048cb

Please sign in to comment.