Skip to content

Instantly share code, notes, and snippets.

@JohnChangUK
Last active January 9, 2021 14:26
Show Gist options
  • Save JohnChangUK/ccd043432ce94d228bbadd3e06af2132 to your computer and use it in GitHub Desktop.
Save JohnChangUK/ccd043432ce94d228bbadd3e06af2132 to your computer and use it in GitHub Desktop.
OrderPurchaseEventHandler
@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