Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions src/main/java/com/example/bankapp/controller/BankController.java
Original file line number Diff line number Diff line change
Expand Up @@ -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";
}

Expand Down
19 changes: 13 additions & 6 deletions src/main/java/com/example/bankapp/service/AccountService.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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");
}
Expand All @@ -97,7 +105,7 @@ public List<Transaction> getTransactionHistory(Account account) {
*/
public List<Transaction> 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))
Expand All @@ -107,10 +115,8 @@ public List<Transaction> 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(),
Expand All @@ -124,6 +130,7 @@ public Collection<? extends GrantedAuthority> authorities() {
}

public void transferAmount(Account fromAccount, String toUsername, BigDecimal amount) {
requireNonNegative(amount);
if (!hasSufficientFunds(fromAccount, amount)) {
throw new RuntimeException("Insufficient funds");
}
Expand Down
139 changes: 139 additions & 0 deletions src/test/java/com/example/bankapp/service/AccountServiceTest.java
Original file line number Diff line number Diff line change
@@ -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<Transaction> 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<Transaction> 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"));
}
}
Loading