package ufrn.imd.service.impl; import lombok.AllArgsConstructor; import lombok.extern.java.Log; import ufrn.imd.domain.Account; import ufrn.imd.domain.Client; import ufrn.imd.repository.Repository; import ufrn.imd.repository.impl.ClientRepository; import ufrn.imd.service.Service; import ufrn.imd.utils.ServerResponse; import java.rmi.RemoteException; import java.util.Optional; @Log @AllArgsConstructor public class TransferServiceImpl implements Service { private final Repository<Client> clientRepository; public ServerResponse transfer(Double value, Optional<Client> from, Optional<Account> to) throws RemoteException, RuntimeException { Client fromUser = from.orElseThrow(() -> new RuntimeException("Null user!")); Client fromClient = clientRepository.find(fromUser.getId()) .orElseThrow(() -> new RuntimeException("Invalid user!")); Account toUserAccount = to.orElseThrow(() -> new RuntimeException("Null account")); Client toClient = ((ClientRepository) clientRepository).findByAccountNumber(toUserAccount.getNumber()) .orElseThrow(() -> new RuntimeException( String.format("Customer not found with account number %s", toUserAccount.getNumber()))); if(fromClient.getId().equals(toClient.getId())) throw new RuntimeException("Invalid account"); Account fromAccount = fromClient.getAccount(); if(value > fromAccount.getBalance()) throw new RuntimeException("Insufficient balance"); fromAccount.setBalance(fromAccount.getBalance() - value); Account toAccount = toClient.getAccount(); toAccount.setBalance(toAccount.getBalance() + value); log.info("Transfer concluded!"); log.info(String.format("Account balance: R$ %.2f", fromClient.getAccount().getBalance())); return ServerResponse.builder() .status(200) .message("Operation sucessed!") .body(fromClient.getAccount()) .build(); } }