From 8f7af0ab20a9f36a18f3b51a47d7099ecdc4eb90 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:29:37 +0000 Subject: [PATCH] bug: fix funds check, date-range end day, negative amounts and unknown-user exception in AccountService Co-Authored-By: Grace Juan --- .../bankapp/controller/BankController.java | 12 +- .../bankapp/service/AccountService.java | 19 ++- .../bankapp/service/AccountServiceTest.java | 139 ++++++++++++++++++ 3 files changed, 162 insertions(+), 8 deletions(-) create mode 100644 src/test/java/com/example/bankapp/service/AccountServiceTest.java diff --git a/src/main/java/com/example/bankapp/controller/BankController.java b/src/main/java/com/example/bankapp/controller/BankController.java index 19fcded7..62724436 100644 --- a/src/main/java/com/example/bankapp/controller/BankController.java +++ b/src/main/java/com/example/bankapp/controller/BankController.java @@ -48,10 +48,18 @@ public String login() { } @PostMapping("/deposit") - public String deposit(@RequestParam BigDecimal amount) { + public String deposit(@RequestParam BigDecimal amount, Model model) { String username = SecurityContextHolder.getContext().getAuthentication().getName(); Account account = accountService.findAccountByUsername(username); - accountService.deposit(account, amount); + + try { + accountService.deposit(account, amount); + } catch (RuntimeException e) { + model.addAttribute("error", e.getMessage()); + model.addAttribute("account", account); + return "dashboard"; + } + return "redirect:/dashboard"; } diff --git a/src/main/java/com/example/bankapp/service/AccountService.java b/src/main/java/com/example/bankapp/service/AccountService.java index ba1a81ea..f66559cf 100644 --- a/src/main/java/com/example/bankapp/service/AccountService.java +++ b/src/main/java/com/example/bankapp/service/AccountService.java @@ -51,7 +51,14 @@ public Account registerAccount(String username, String password) { } + private void requireNonNegative(BigDecimal amount) { + if (amount.signum() < 0) { + throw new RuntimeException("Amount must not be negative"); + } + } + public void deposit(Account account, BigDecimal amount) { + requireNonNegative(amount); account.setBalance(account.getBalance().add(amount)); accountRepository.save(account); @@ -68,10 +75,11 @@ public void deposit(Account account, BigDecimal amount) { * Returns true when the account balance is at least {@code amount}. */ public boolean hasSufficientFunds(Account account, BigDecimal amount) { - return account.getBalance().compareTo(amount) > 0; + return account.getBalance().compareTo(amount) >= 0; } public void withdraw(Account account, BigDecimal amount) { + requireNonNegative(amount); if (!hasSufficientFunds(account, amount)) { throw new RuntimeException("Insufficient funds"); } @@ -97,7 +105,7 @@ public List getTransactionHistory(Account account) { */ public List getTransactionHistory(Account account, LocalDate from, LocalDate to) { LocalDateTime start = from.atStartOfDay(); - LocalDateTime end = to.atStartOfDay(); + LocalDateTime end = to.plusDays(1).atStartOfDay(); return transactionRepository.findByAccountId(account.getId()).stream() .filter(t -> !t.getTimestamp().isBefore(start) && t.getTimestamp().isBefore(end)) .sorted(Comparator.comparing(Transaction::getTimestamp)) @@ -107,10 +115,8 @@ public List getTransactionHistory(Account account, LocalDate from, @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - Account account = findAccountByUsername(username); - if (account == null) { - throw new UsernameNotFoundException("Username or Password not found"); - } + Account account = accountRepository.findByUsername(username) + .orElseThrow(() -> new UsernameNotFoundException("Username or Password not found")); return new Account( account.getUsername(), account.getPassword(), @@ -124,6 +130,7 @@ public Collection authorities() { } public void transferAmount(Account fromAccount, String toUsername, BigDecimal amount) { + requireNonNegative(amount); if (!hasSufficientFunds(fromAccount, amount)) { throw new RuntimeException("Insufficient funds"); } diff --git a/src/test/java/com/example/bankapp/service/AccountServiceTest.java b/src/test/java/com/example/bankapp/service/AccountServiceTest.java new file mode 100644 index 00000000..fc281ce3 --- /dev/null +++ b/src/test/java/com/example/bankapp/service/AccountServiceTest.java @@ -0,0 +1,139 @@ +package com.example.bankapp.service; + +import com.example.bankapp.model.Account; +import com.example.bankapp.model.Transaction; +import com.example.bankapp.repository.AccountRepository; +import com.example.bankapp.repository.TransactionRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.core.userdetails.UsernameNotFoundException; + +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class AccountServiceTest { + + @Mock + private AccountRepository accountRepository; + + @Mock + private TransactionRepository transactionRepository; + + @InjectMocks + private AccountService accountService; + + private Account account; + + @BeforeEach + void setUp() { + account = new Account(); + account.setId(1L); + account.setUsername("alice"); + account.setBalance(new BigDecimal("100.00")); + } + + private Account recipient(String balance) { + Account bob = new Account(); + bob.setId(2L); + bob.setUsername("bob"); + bob.setBalance(new BigDecimal(balance)); + lenient().when(accountRepository.findByUsername("bob")).thenReturn(Optional.of(bob)); + return bob; + } + + private Transaction txAt(LocalDateTime timestamp) { + return new Transaction(BigDecimal.ONE, "Deposit", timestamp, account); + } + + @Test + void hasSufficientFundsIsTrueWhenBalanceEqualsAmount() { + assertTrue(accountService.hasSufficientFunds(account, new BigDecimal("100.00"))); + } + + @Test + void withdrawingTheFullBalanceSucceeds() { + accountService.withdraw(account, new BigDecimal("100.00")); + + assertEquals(0, account.getBalance().compareTo(BigDecimal.ZERO)); + } + + @Test + void transferringTheFullBalanceSucceeds() { + Account bob = recipient("0.00"); + + accountService.transferAmount(account, "bob", new BigDecimal("100.00")); + + assertEquals(0, account.getBalance().compareTo(BigDecimal.ZERO)); + assertEquals(0, bob.getBalance().compareTo(new BigDecimal("100.00"))); + } + + @Test + void dateRangeHistoryIncludesTransactionsOnTheEndDay() { + Transaction onEndDay = txAt(LocalDateTime.of(2026, 11, 18, 14, 30)); + when(transactionRepository.findByAccountId(1L)).thenReturn(List.of(onEndDay)); + + List result = accountService.getTransactionHistory( + account, LocalDate.of(2026, 11, 17), LocalDate.of(2026, 11, 18)); + + assertEquals(List.of(onEndDay), result); + } + + @Test + void singleDayRangeReturnsThatDaysTransactions() { + Transaction morning = txAt(LocalDateTime.of(2026, 11, 18, 9, 0)); + Transaction lastSecond = txAt(LocalDateTime.of(2026, 11, 18, 23, 59, 59)); + Transaction nextDay = txAt(LocalDateTime.of(2026, 11, 19, 0, 0)); + when(transactionRepository.findByAccountId(1L)).thenReturn(List.of(nextDay, lastSecond, morning)); + + LocalDate day = LocalDate.of(2026, 11, 18); + List result = accountService.getTransactionHistory(account, day, day); + + assertEquals(List.of(morning, lastSecond), result); + } + + @Test + void negativeWithdrawalIsRejectedAndDoesNotIncreaseBalance() { + assertThrows(RuntimeException.class, + () -> accountService.withdraw(account, new BigDecimal("-50.00"))); + assertEquals(0, account.getBalance().compareTo(new BigDecimal("100.00"))); + } + + @Test + void negativeTransferIsRejectedAndDoesNotTakeRecipientFunds() { + Account bob = recipient("500.00"); + + assertThrows(RuntimeException.class, + () -> accountService.transferAmount(account, "bob", new BigDecimal("-200.00"))); + assertEquals(0, account.getBalance().compareTo(new BigDecimal("100.00"))); + assertEquals(0, bob.getBalance().compareTo(new BigDecimal("500.00"))); + } + + @Test + void negativeDepositIsRejectedAndDoesNotDecreaseBalance() { + assertThrows(RuntimeException.class, + () -> accountService.deposit(account, new BigDecimal("-50.00"))); + assertEquals(0, account.getBalance().compareTo(new BigDecimal("100.00"))); + } + + @Test + void loadUserByUsernameThrowsUsernameNotFoundForUnknownUser() { + when(accountRepository.findByUsername("ghost")).thenReturn(Optional.empty()); + + assertThrows(UsernameNotFoundException.class, + () -> accountService.loadUserByUsername("ghost")); + } +}