wiki:WikiStart/Development

Напреден развој на апликација

Оптимизиран dashboard

schema

schema

Функции во Java Spring services


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.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

@Service
public class AccountService implements UserDetailsService {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private TransactionRepository transactionRepository;

    @Transactional 
    public Account findAccountByUsername(String username) {
        return accountRepository.findByUsername(username).orElseThrow(() -> new RuntimeException("Account not found"));
    }

    @Transactional 
    public Account registerAccount(String username,String email, String password) {
        if (accountRepository.findByUsername(username).isPresent()) {
            throw new RuntimeException("Username already exists");
        }

        Account account = new Account();
        account.setUsername(username);
        account.setEmail(email);
        account.setPassword(passwordEncoder.encode(password)); // Encrypt password
        account.setBalance(BigDecimal.ZERO); // Initial balance set to 0
        return accountRepository.save(account);
    }

    @Transactional 
    public void deposit(Account account, BigDecimal amount) {
        account.setBalance(account.getBalance().add(amount));
        accountRepository.save(account);

        Transaction transaction = new Transaction(
                amount,
                "(MKD)",
                "Deposit",
                LocalDateTime.now(),
                account
        );
        transactionRepository.save(transaction);
    }

    @Transactional 
    public void withdraw(Account account, BigDecimal amount) {
        if (account.getBalance().compareTo(amount) < 0) {
            throw new RuntimeException("Insufficient funds");
        }
        account.setBalance(account.getBalance().subtract(amount));
        accountRepository.save(account);

        Transaction transaction = new Transaction(
                amount,
                "(MKD)",
                "Withdrawal",
                LocalDateTime.now(),
                account
        );
        transactionRepository.save(transaction);
    }


    @Transactional 
    public List<Transaction> getTransactionHistory(Account account) {
        return transactionRepository.findByAccountId(account.getId());
    }

    @Transactional 
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Account account = findAccountByUsername(username);
        if (account == null) {
            throw new UsernameNotFoundException("Username or Password not found");
        }
        return new Account(
                account.getUsername(),
                account.getEmail(),
                account.getPassword(),
                account.getBalance(),
                account.getTransactions(),
                authorities());
    }

    public Collection<? extends GrantedAuthority> authorities() {
        return Arrays.asList(new SimpleGrantedAuthority("USER"));
    }

 
    @Transactional 
    public void transferAmount(Account fromAccount, String toUsername, BigDecimal amount, String currency) {

        if(fromAccount.getUsername().compareTo(toUsername) == 0){
            throw new RuntimeException("No transaction allowed to yourself");
        }

        Account toAccount = accountRepository.findByUsername(toUsername)
                .orElseThrow(() -> new RuntimeException("Recipient account not found"));


        if(currency.compareTo("(MKD)")==0){
            if (fromAccount.getBalance().compareTo(amount) < 0) {
                throw new RuntimeException("Insufficient funds");
            }
            else{
                // Deduct from sender's account
                fromAccount.setBalance(fromAccount.getBalance().subtract(amount));
                accountRepository.save(fromAccount);

                // Add to recipient's account
                toAccount.setBalance(toAccount.getBalance().add(amount));
                accountRepository.save(toAccount);

                // Create transaction records for both accounts
                Transaction debitTransaction = new Transaction(
                        amount,
                        currency,
                        "(MKD) Transfer Out to " + toAccount.getUsername(),
                        LocalDateTime.now(),
                        fromAccount
                );
                transactionRepository.save(debitTransaction);

                Transaction creditTransaction = new Transaction(
                        amount,
                        currency,
                        "(MKD) Transfer In from " + fromAccount.getUsername(),
                        LocalDateTime.now(),
                        toAccount
                );
                transactionRepository.save(creditTransaction);
            }
        }

        if(currency.compareTo("(EUR)")==0){
            if (fromAccount.getBalance().compareTo(amount.multiply(BigDecimal.valueOf(60.00))) < 0) {
                throw new RuntimeException("Insufficient funds");
            }
            else{
                    // Deduct from sender's account
                    fromAccount.setBalance(fromAccount.getBalance().subtract(amount.multiply(BigDecimal.valueOf(60.00))));
                    accountRepository.save(fromAccount);

                    // Add to recipient's account
                    toAccount.setBalance(toAccount.getBalance().add(amount.multiply(BigDecimal.valueOf(60.00))));
                    accountRepository.save(toAccount);

                    // Create transaction records for both accounts
                    Transaction debitTransaction = new Transaction(
                            amount,
                            currency,
                            "(EUR) Transfer Out to " + toAccount.getUsername(),
                            LocalDateTime.now(),
                            fromAccount
                    );

                    transactionRepository.save(debitTransaction);

                    Transaction creditTransaction = new Transaction(
                        amount,
                        currency,
                        "(EUR) Transfer In from " + fromAccount.getUsername(),
                        LocalDateTime.now(),
                        toAccount
                    );
                    transactionRepository.save(creditTransaction);
            }
        }

        if(currency.compareTo("(USD)")==0){
            if (fromAccount.getBalance().compareTo(amount.multiply(BigDecimal.valueOf(60.00))) < 0) {
                throw new RuntimeException("Insufficient funds");
            }
            else{
                // Deduct from sender's account
                fromAccount.setBalance(fromAccount.getBalance().subtract(amount.multiply(BigDecimal.valueOf(60.00))));
                accountRepository.save(fromAccount);

                // Add to recipient's account
                toAccount.setBalance(toAccount.getBalance().add(amount.multiply(BigDecimal.valueOf(60.00))));
                accountRepository.save(toAccount);

                // Create transaction records for both accounts
                Transaction debitTransaction = new Transaction(
                        amount,
                        currency,
                  "(USD) Transfer Out to " + toAccount.getUsername(),
                        LocalDateTime.now(),
                         fromAccount
                );
                transactionRepository.save(debitTransaction);

                Transaction creditTransaction = new Transaction(
                        amount,
                        currency,
                        "(USD) Transfer In from " + fromAccount.getUsername(),
                        LocalDateTime.now(),
                        toAccount
                );
                transactionRepository.save(creditTransaction);
            }
        }

        if(currency.compareTo("(GBP)")==0){
            if (fromAccount.getBalance().compareTo(amount.multiply(BigDecimal.valueOf(70.00))) < 0) {
                throw new RuntimeException("Insufficient funds");
            }
            else{
                    // Deduct from sender's account
                    fromAccount.setBalance(fromAccount.getBalance().subtract(amount.multiply(BigDecimal.valueOf(70.00))));
                    accountRepository.save(fromAccount);

                    // Add to recipient's account
                    toAccount.setBalance(toAccount.getBalance().add(amount.multiply(BigDecimal.valueOf(70.00))));
                    accountRepository.save(toAccount);

                    // Create transaction records for both accounts
                    Transaction debitTransaction = new Transaction(
                            amount,
                            currency,
                            "(GBP) Transfer Out to " + toAccount.getUsername(),
                            LocalDateTime.now(),
                            fromAccount
                    );
                    transactionRepository.save(debitTransaction);

                    Transaction creditTransaction = new Transaction(
                            amount,
                            currency,
                            "(GBP) Transfer In from " + fromAccount.getUsername(),
                            LocalDateTime.now(),
                            toAccount
                    );
                    transactionRepository.save(creditTransaction);
            }
        }

    }

}

Функции во контролерот

package com.example.bankapp.controller;

import com.example.bankapp.model.Account;
import com.example.bankapp.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;

@Controller
public class BankController {

    @Autowired
    private AccountService accountService;

    @GetMapping("/dashboard")
    public String dashboard(Model model) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        Account account = accountService.findAccountByUsername(username);
        model.addAttribute("account", account);
        return "dashboard";
    }

    @GetMapping("/register")
    public String showRegistrationForm() {
        return "register";
    }

    @PostMapping("/register")
    public String registerAccount(@RequestParam String username,@RequestParam String email, @RequestParam String password, Model model) {
        try {
            accountService.registerAccount(username,email, password);
            return "redirect:/login";
        } catch (RuntimeException e) {
            model.addAttribute("error", e.getMessage());
            return "register";
        }
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/deposit")
    public String deposit(@RequestParam BigDecimal amount) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        Account account = accountService.findAccountByUsername(username);
        accountService.deposit(account, amount);
        return "redirect:/dashboard";
    }

    @PostMapping("/withdraw")
    public String withdraw(@RequestParam BigDecimal amount, Model model) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        Account account = accountService.findAccountByUsername(username);

        try {
            accountService.withdraw(account, amount);
        } catch (RuntimeException e) {
            model.addAttribute("error", e.getMessage());
            model.addAttribute("account", account);
            return "dashboard";
        }

        return "redirect:/dashboard";
    }

    @GetMapping("/transactions")
    public String transactionHistory(Model model) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        Account account = accountService.findAccountByUsername(username);
        model.addAttribute("transactions", accountService.getTransactionHistory(account));
        return "transactions";
    }

    @PostMapping("/transfer")
    public String transferAmount(@RequestParam String toUsername, @RequestParam BigDecimal amount, @RequestParam String currency, Model model) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        Account fromAccount = accountService.findAccountByUsername(username);

        try {
            accountService.transferAmount(fromAccount, toUsername, amount, currency);
        } catch (RuntimeException e) {
            model.addAttribute("error", e.getMessage());
            model.addAttribute("account", fromAccount);
            return "dashboard";
        }

        return "redirect:/dashboard";
    }


}

Last modified 12 hours ago Last modified on 04/03/25 12:08:07

Attachments (2)

Download all attachments as: .zip

Note: See TracWiki for help on using the wiki.