|
| 1 | +package eureca.capstone.project.orchestrator.transaction_feed.service.impl; |
| 2 | + |
| 3 | +import eureca.capstone.project.orchestrator.alarm.dto.AlarmCreationDto; |
| 4 | +import eureca.capstone.project.orchestrator.alarm.service.impl.NotificationProducer; |
| 5 | +import eureca.capstone.project.orchestrator.common.entity.Status; |
| 6 | +import eureca.capstone.project.orchestrator.common.exception.code.ErrorCode; |
| 7 | +import eureca.capstone.project.orchestrator.common.exception.custom.BidException; |
| 8 | +import eureca.capstone.project.orchestrator.common.exception.custom.TransactionFeedNotFoundException; |
| 9 | +import eureca.capstone.project.orchestrator.common.exception.custom.UserNotFoundException; |
| 10 | +import eureca.capstone.project.orchestrator.common.util.SalesTypeManager; |
| 11 | +import eureca.capstone.project.orchestrator.common.util.StatusManager; |
| 12 | +import eureca.capstone.project.orchestrator.pay.service.UserPayService; |
| 13 | +import eureca.capstone.project.orchestrator.transaction_feed.document.TransactionFeedDocument; |
| 14 | +import eureca.capstone.project.orchestrator.transaction_feed.dto.request.PlaceBidRequestDto; |
| 15 | +import eureca.capstone.project.orchestrator.transaction_feed.entity.Bids; |
| 16 | +import eureca.capstone.project.orchestrator.transaction_feed.entity.SalesType; |
| 17 | +import eureca.capstone.project.orchestrator.transaction_feed.entity.TransactionFeed; |
| 18 | +import eureca.capstone.project.orchestrator.transaction_feed.repository.BidsRepository; |
| 19 | +import eureca.capstone.project.orchestrator.transaction_feed.repository.TransactionFeedRepository; |
| 20 | +import eureca.capstone.project.orchestrator.transaction_feed.repository.TransactionFeedSearchRepository; |
| 21 | +import eureca.capstone.project.orchestrator.user.entity.User; |
| 22 | +import eureca.capstone.project.orchestrator.user.repository.UserRepository; |
| 23 | +import java.time.LocalDateTime; |
| 24 | +import java.util.List; |
| 25 | +import java.util.Optional; |
| 26 | +import lombok.RequiredArgsConstructor; |
| 27 | +import lombok.extern.slf4j.Slf4j; |
| 28 | +import org.springframework.stereotype.Service; |
| 29 | +import org.springframework.transaction.annotation.Transactional; |
| 30 | + |
| 31 | +@Slf4j |
| 32 | +@Service |
| 33 | +@RequiredArgsConstructor |
| 34 | +public class BidServiceWithLock { |
| 35 | + private final UserRepository userRepository; |
| 36 | + private final TransactionFeedRepository transactionFeedRepository; |
| 37 | + private final TransactionFeedSearchRepository transactionFeedSearchRepository; |
| 38 | + private final BidsRepository bidsRepository; |
| 39 | + private final UserPayService userPayService; |
| 40 | + private final StatusManager statusManager; |
| 41 | + private final SalesTypeManager salesTypeManager; |
| 42 | + private final NotificationProducer notificationProducer; |
| 43 | + |
| 44 | + @Transactional |
| 45 | + public void placeBidWithDbLock(String email, PlaceBidRequestDto request) { |
| 46 | + TransactionFeed feed = transactionFeedRepository.findByIdWithLock(request.getTransactionFeedId()) |
| 47 | + .orElseThrow(TransactionFeedNotFoundException::new); |
| 48 | + log.info("[placeBidWithDbLock] 입찰 판매글 비관적 락 적용 ID: {}", feed.getTransactionFeedId()); |
| 49 | + |
| 50 | + User bidder = findUserByEmail(email); |
| 51 | + log.info("[placeBidWithDbLock] 사용자 ID: {}, 판매글 ID: {}, 입찰금액: {}", bidder.getUserId(), feed.getTransactionFeedId(), request.getBidAmount()); |
| 52 | + |
| 53 | + validateBidPrecondition(bidder, feed, request.getBidAmount()); |
| 54 | + log.info("[placeBidWithDbLock] 입찰 사전 검증 통과"); |
| 55 | + |
| 56 | + Optional<Bids> highestBidOptional = bidsRepository.findHighestBidByFeed(feed); |
| 57 | + log.info("[placeBidWithDbLock] 입찰 최고가 조회"); |
| 58 | + |
| 59 | + if (highestBidOptional.isPresent()) { |
| 60 | + Bids highestBid = highestBidOptional.get(); |
| 61 | + |
| 62 | + if (request.getBidAmount() <= highestBid.getBidAmount()) { |
| 63 | + throw new BidException(ErrorCode.BID_AMOUNT_TOO_LOW); |
| 64 | + } |
| 65 | + |
| 66 | + if (highestBid.getUser().getUserId().equals(bidder.getUserId())) { |
| 67 | + throw new BidException(ErrorCode.CANNOT_BID_ON_OWN_HIGHEST); |
| 68 | + } |
| 69 | + } else { |
| 70 | + if (request.getBidAmount() < feed.getSalesPrice()) { |
| 71 | + throw new BidException(ErrorCode.BID_AMOUNT_TOO_LOW); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + LocalDateTime bidTimeStamp = LocalDateTime.now(); |
| 76 | + |
| 77 | + if (highestBidOptional.isPresent()) { |
| 78 | + Bids prevHighestBid = highestBidOptional.get(); |
| 79 | + userPayService.refundPay(prevHighestBid.getUser(), prevHighestBid.getBidAmount()); |
| 80 | + log.info("[placeBidWithDbLock] 이전 입찰자 페이 환불 완료. 사용자 ID: {}, 환불 금액: {}", prevHighestBid.getUser().getUserId(), prevHighestBid.getBidAmount()); |
| 81 | + } |
| 82 | + |
| 83 | + userPayService.usePay(bidder, request.getBidAmount()); |
| 84 | + log.info("[placeBidWithDbLock] 새로운 입찰자 페이 사용 완료. 사용자 ID: {}, 사용 금액: {}", bidder.getUserId(), request.getBidAmount()); |
| 85 | + |
| 86 | + saveBidHistory(feed, bidder, request.getBidAmount(), bidTimeStamp); |
| 87 | + log.info("입찰 성공 - 사용자 ID: {}, 게시글 ID: {}, 입찰가: {}", bidder.getUserId(), feed.getTransactionFeedId(), request.getBidAmount()); |
| 88 | + |
| 89 | + updateFeedDocumentHighestPrice(feed.getTransactionFeedId(), request.getBidAmount()); |
| 90 | + |
| 91 | + List<User> participants = bidsRepository.findBidsWithUserByTransactionFeed(feed) |
| 92 | + .stream() |
| 93 | + .map(Bids::getUser) |
| 94 | + .distinct() |
| 95 | + .toList(); |
| 96 | + log.info("[handleBidResult] 입찰 참여자 {}명 조회 완료", participants.size()); |
| 97 | + |
| 98 | + for (User participant : participants) { |
| 99 | + log.info("transaction_feed_id: {}", feed.getTransactionFeedId()); |
| 100 | + if (participant.getUserId().equals(bidder.getUserId())) { |
| 101 | + notificationProducer.send(AlarmCreationDto.builder() |
| 102 | + .userId(participant.getUserId()) |
| 103 | + .alarmType("입찰 성공") |
| 104 | + .transactionFeedId(feed.getTransactionFeedId()) |
| 105 | + .content("'" + feed.getTitle() + "'를(을) (다챠페이)" + request.getBidAmount() + "원에 입찰했습니다.") |
| 106 | + .build()); |
| 107 | + } else { |
| 108 | + notificationProducer.send(AlarmCreationDto.builder() |
| 109 | + .userId(participant.getUserId()) |
| 110 | + .alarmType("입찰 갱신") |
| 111 | + .transactionFeedId(feed.getTransactionFeedId()) |
| 112 | + .content(bidder + "님이 '" + feed.getTitle() + "'를(을) (다챠페이)" + request.getBidAmount() + "원에 입찰했습니다.") |
| 113 | + .build()); |
| 114 | + } |
| 115 | + } |
| 116 | + log.info("[placeBidWithDbLock] 입찰 알림 전송 완료"); |
| 117 | + } |
| 118 | + |
| 119 | + private User findUserByEmail(String email) { |
| 120 | + return userRepository.findByEmail(email) |
| 121 | + .orElseThrow(UserNotFoundException::new); |
| 122 | + } |
| 123 | + |
| 124 | + private void validateBidPrecondition(User bidder, TransactionFeed feed, Long bidAmount) { |
| 125 | + Status salesStatus = statusManager.getStatus("FEED", "ON_SALE"); |
| 126 | + SalesType bidSalesType = salesTypeManager.getBidSaleType(); |
| 127 | + |
| 128 | + if (feed.getUser().getUserId().equals(bidder.getUserId())) { |
| 129 | + throw new BidException(ErrorCode.SELLER_CANNOT_BID); |
| 130 | + } |
| 131 | + if (!feed.getTelecomCompany().getTelecomCompanyId().equals(bidder.getTelecomCompany().getTelecomCompanyId())) { |
| 132 | + throw new BidException(ErrorCode.INVALID_TELECOM_COMPANY); |
| 133 | + } |
| 134 | + if (!feed.getStatus().equals(salesStatus)) { |
| 135 | + throw new BidException(ErrorCode.AUCTION_NOT_ON_SALE); |
| 136 | + } |
| 137 | + if (!feed.getSalesType().equals(bidSalesType)) { |
| 138 | + throw new BidException(ErrorCode.FEED_NOT_AUCTION); |
| 139 | + } |
| 140 | + if (feed.getExpiresAt().isBefore(LocalDateTime.now())) { |
| 141 | + throw new BidException(ErrorCode.AUCTION_EXPIRED); |
| 142 | + } |
| 143 | + if (bidAmount % 100 != 0) { |
| 144 | + throw new BidException(ErrorCode.BID_AMOUNT_100_DIVISIBLE); |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + private void saveBidHistory(TransactionFeed feed, User bidder, Long bidAmount, LocalDateTime bidTimeStamp) { |
| 149 | + bidsRepository.save(Bids.builder() |
| 150 | + .transactionFeed(feed) |
| 151 | + .user(bidder) |
| 152 | + .bidAmount(bidAmount) |
| 153 | + .bidTime(bidTimeStamp) |
| 154 | + .build()); |
| 155 | + } |
| 156 | + |
| 157 | + |
| 158 | + private void updateFeedDocumentHighestPrice(Long feedId, Long highestPrice) { |
| 159 | + try { |
| 160 | + TransactionFeedDocument document = transactionFeedSearchRepository.findById(feedId) |
| 161 | + .orElseThrow(TransactionFeedNotFoundException::new); |
| 162 | + document.updateHighestPrice(highestPrice); |
| 163 | + transactionFeedSearchRepository.save(document); |
| 164 | + } catch (Exception e) { |
| 165 | + log.error("[updateFeedDocumentHighestPrice] Elasticsearch 문서 업데이트 실패. Document ID: {}. Error: {}", feedId, e.getMessage()); |
| 166 | + } |
| 167 | + } |
| 168 | +} |
0 commit comments