Last active
January 9, 2021 14:26
-
-
Save JohnChangUK/ccd043432ce94d228bbadd3e06af2132 to your computer and use it in GitHub Desktop.
OrderPurchaseEventHandler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Component | |
public class OrderPurchaseEventHandler implements EventHandler<OrderPurchaseEvent, PaymentEvent> { | |
private final UserRepository userRepository; | |
@Autowired | |
public OrderPurchaseEventHandler(UserRepository userRepository) { | |
this.userRepository = userRepository; | |
} | |
@Transactional | |
public PaymentEvent handleEvent(OrderPurchaseEvent event) { | |
double orderPrice = event.getPrice(); | |
Integer userId = event.getUserId(); | |
PaymentEvent paymentEvent = new PaymentEvent() | |
.orderId(event.getOrderId()) | |
.price(event.getPrice()) | |
.status(DECLINED); | |
userRepository | |
.findById(userId) | |
.ifPresent(user -> deductUserBalance(orderPrice, paymentEvent, user)); | |
return paymentEvent; | |
} | |
private void deductUserBalance(double orderPrice, PaymentEvent paymentEvent, User user) { | |
double userBalance = user.getBalance(); | |
if (userBalance >= orderPrice) { | |
user.setBalance(userBalance - orderPrice); | |
userRepository.save(user); | |
paymentEvent.status(APPROVED); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment