transactions

This commit is contained in:
2024-12-01 15:00:08 +01:00
parent 313821ef7b
commit 22e52ea46c
12 changed files with 299 additions and 50 deletions
@@ -32,4 +32,6 @@ public interface UserAccountRepository extends UserAccountRepositoryWithBagRelat
@Query("select userAccount from UserAccount userAccount join fetch userAccount.users")
// List<UserAccount> findByUserLogin(String login);
List<UserAccount> findAllFetchAccounts();
List<UserAccount> findByName(String name);
}
@@ -3,4 +3,10 @@ package com.sasiedzi.event.service;
public enum Account {
Boisko,
Skarbiec,
Counter {
@Override
public String toString() {
return "Subkonto Tomka";
}
},
}
@@ -1,17 +1,16 @@
package com.sasiedzi.event.service;
import com.sasiedzi.event.domain.Event;
import com.sasiedzi.event.domain.Transaction;
import com.sasiedzi.event.domain.TransactionItem;
import com.sasiedzi.event.domain.UserAccount;
import com.sasiedzi.event.domain.enumeration.TransactionType;
import com.sasiedzi.event.repository.TransactionItemRepository;
import com.sasiedzi.event.repository.TransactionRepository;
import com.sasiedzi.event.repository.UserAccountRepository;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.*;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -27,52 +26,61 @@ public class TransactionService {
@Autowired
UserAccountRepository userAccountRepository;
@Autowired
private TransactionItemRepository transactionItemRepository;
@Autowired
private EventService eventService;
public Transaction save(Transaction transaction) {
Set<TransactionItem> items = transaction.getTransactionItems();
Set<TransactionItem> vaults = items
String beneficiaryAccountName = transaction.getBeneficiary() == null
? Account.Skarbiec.toString()
: transaction.getBeneficiary().getName();
Set<TransactionItem> beneficiaryItems = items
.stream()
.filter(item -> Account.Skarbiec.name().equals(item.getUserAccount().getName()))
.filter(item -> beneficiaryAccountName.equals(item.getUserAccount().getName()))
.collect(Collectors.toSet());
Set<TransactionItem> nonVaults = items
Set<TransactionItem> nonBeneficiaryItems = items
.stream()
.filter(item -> !Account.Skarbiec.name().equals(item.getUserAccount().getName()))
.filter(item -> !beneficiaryAccountName.equals(item.getUserAccount().getName()))
.collect(Collectors.toSet());
BigDecimal vaultValue = nonVaults
BigDecimal beneficiaryValue = nonBeneficiaryItems
.stream()
.map(TransactionItem::getAmount)
.map(BigDecimal::negate)
.reduce(BigDecimal.ZERO, BigDecimal::add);
boolean vaultIsNeeded = vaultValue.compareTo(BigDecimal.ZERO) != 0;
boolean beneficiaryItemIsNeeded = beneficiaryValue.compareTo(BigDecimal.ZERO) != 0;
HashSet<TransactionItem> itemsToBeRemoved = new HashSet<>();
if (vaultIsNeeded) {
if (vaults.isEmpty()) {
if (beneficiaryItemIsNeeded) {
if (beneficiaryItems.isEmpty()) {
TransactionItem transactionItem = new TransactionItem();
UserAccount vaultAccount = userAccountRepository
UserAccount beneficiaryAccount = userAccountRepository
.findAll()
.stream()
.filter(item -> Account.Skarbiec.name().equals(item.getName()))
.filter(item -> beneficiaryAccountName.equals(item.getName()))
.findFirst()
.orElse(null);
transactionItem.setUserAccount(vaultAccount);
transactionItem.setAmount(vaultValue);
transactionItem.setUserAccount(beneficiaryAccount);
transactionItem.setAmount(beneficiaryValue);
transactionItem.setTransaction(transaction);
transaction.getTransactionItems().add(transactionItem);
} else {
TransactionItem first = null;
for (TransactionItem item : vaults) {
for (TransactionItem item : beneficiaryItems) {
if (first == null) {
first = item;
} else {
itemsToBeRemoved.add(item);
}
}
first.setAmount(vaultValue);
first.setAmount(beneficiaryValue);
}
} else {
itemsToBeRemoved.addAll(vaults);
itemsToBeRemoved.addAll(beneficiaryItems);
}
itemsToBeRemoved.forEach(transactionItem -> {
@@ -100,4 +108,84 @@ public class TransactionService {
}
return newTransaction;
}
public Transaction createPayments(Long id) {
Transaction existing = transactionRepository.findOneWithEagerRelationships(id).orElseGet(Transaction::new);
Transaction newTransaction = new Transaction();
newTransaction.setType(TransactionType.INTERNALTRANSFER);
setBeneficiary(newTransaction);
newTransaction.setEvent(existing.getEvent());
calculateBalances(existing.getTransactionItems().stream().map(TransactionItem::getUserAccount).toList());
for (TransactionItem item : existing.getTransactionItems()) {
BigDecimal accountBalance = item.getUserAccount().getBalance();
if (accountBalance == null) {
accountBalance = BigDecimal.ZERO;
}
if (accountBalance.compareTo(BigDecimal.ZERO) < 0 && !Account.Skarbiec.toString().equals(item.getUserAccount().getName())) {
TransactionItem newItem = new TransactionItem();
newItem.setAmount(accountBalance.negate());
newItem.setTransaction(newTransaction);
newItem.setUserAccount(item.getUserAccount());
newItem.setEvent(item.getEvent());
newItem.setRegistration(item.getRegistration());
newItem.setComment(item.getComment());
newTransaction.getTransactionItems().add(newItem);
}
}
return newTransaction;
}
public Transaction createFieldPayment(Long eventId) {
Transaction newTransaction = new Transaction();
newTransaction.setType(TransactionType.FIELDPAYMENT);
setBeneficiary(newTransaction);
Event event = null;
if (eventId != null) {
event = eventService.findOne(eventId).orElse(null);
newTransaction.setEvent(event);
}
TransactionItem newItem = new TransactionItem();
newItem.setAmount(new BigDecimal("375"));
newItem.setTransaction(newTransaction);
newItem.setUserAccount(getAccount(Account.Counter));
newItem.setEvent(event);
newTransaction.getTransactionItems().add(newItem);
return newTransaction;
}
private void calculateBalances(List<UserAccount> userAccounts) {
Map<Long, List<TransactionItem>> itemsByUserAccountId = transactionItemRepository
.findAll()
.stream()
.collect(Collectors.groupingBy(item -> item.getUserAccount().getId()));
for (UserAccount userAccount : userAccounts) {
List<TransactionItem> itemsForAccount = itemsByUserAccountId.get(userAccount.getId());
BigDecimal balance = itemsForAccount.stream().map(TransactionItem::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
userAccount.setBalance(balance);
}
}
public Transaction get(Long id) {
Transaction transaction = transactionRepository.findOneWithEagerRelationships(id).orElse(null);
setBeneficiary(transaction);
return transaction;
}
private void setBeneficiary(Transaction transaction) {
switch (transaction.getType()) {
case INTERNALTRANSFER -> {
transaction.setBeneficiary(getAccount(Account.Counter));
}
case MATCH, PURCHASE -> {
transaction.setBeneficiary(getAccount(Account.Skarbiec));
}
case FIELDPAYMENT -> {
transaction.setBeneficiary(getAccount(Account.Boisko));
}
}
}
public UserAccount getAccount(Account account) {
return userAccountRepository.findByName(account.toString()).stream().min(Comparator.comparing(UserAccount::getId)).orElse(null);
}
}
@@ -271,19 +271,44 @@ public class TransactionResource {
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the transaction, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/{id}")
public ResponseEntity<Transaction> getTransaction(@PathVariable("id") Long id) {
public Transaction getTransaction(@PathVariable("id") Long id) {
LOG.debug("REST request to get Transaction : {}", id);
Optional<Transaction> transaction = transactionRepository.findOneWithEagerRelationships(id);
// if (transaction.isPresent()) {
// transaction.get().getTransactionItems().stream().sorted();
// transaction.get().getTransactionItems().sort(Comparator.comparing(item -> item.getUserAccount().getName()));
// }
return ResponseUtil.wrapOrNotFound(transaction);
return transactionService.get(id);
// Optional<Transaction> transaction = transactionRepository.findOneWithEagerRelationships(id);
// // if (transaction.isPresent()) {
// // transaction.get().getTransactionItems().stream().sorted();
// // transaction.get().getTransactionItems().sort(Comparator.comparing(item -> item.getUserAccount().getName()));
// // }
// return ResponseUtil.wrapOrNotFound(transaction);
}
@Autowired
TransactionService transactionService;
/**
* {@code GET /transactions/:id} : get the "id" transaction.
*
* @param id the id of the transaction to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the transaction, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/payments/{id}")
public Transaction createPayments(@PathVariable("id") Long id) {
LOG.debug("REST request to get Transaction : {}", id);
return transactionService.createPayments(id);
}
/**
* {@code GET /transactions/:id} : get the "id" transaction.
*
* @param id the id of the transaction to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the transaction, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/field-payment/{id}")
public Transaction getTransactionPayments(@PathVariable("id") Long id) {
LOG.debug("REST request to get Transaction : {}", id);
return transactionService.createFieldPayment(id);
}
/**
* {@code GET /transactions/:id} : get the "id" transaction.
*