36 lines
2.7 KiB
Java
36 lines
2.7 KiB
Java
if (initialBalance != null) {
|
|
log.info("editWallet: initialBalance is not null: {}", initialBalance);
|
|
return transactionRepository.findByWalletAndDescription(walletId, "Opening Balance")
|
|
.collectList()
|
|
.flatMap(txList -> {
|
|
if (txList.isEmpty()) {
|
|
log.info("editWallet: No old opening balance tx found. Calling handleOpeningBalance.");
|
|
return walletRepository.save(w).flatMap(saved -> handleOpeningBalance(ownerId, saved, initialBalance, initialBalanceDate));
|
|
} else {
|
|
Transaction oldTx = txList.get(0);
|
|
log.info("editWallet: Found old opening balance tx: {}", oldTx.getId());
|
|
// Reverse old transaction impact on w in memory
|
|
if (oldTx.getFromWalletId().equals(w.getId())) {
|
|
w.setBalance(w.getBalance().add(oldTx.getAmount()));
|
|
} else if (oldTx.getToWalletId().equals(w.getId())) {
|
|
w.setBalance(w.getBalance().subtract(oldTx.getAmount()));
|
|
}
|
|
|
|
Long otherWalletId = oldTx.getFromWalletId().equals(w.getId()) ? oldTx.getToWalletId() : oldTx.getFromWalletId();
|
|
|
|
return walletRepository.findById(otherWalletId)
|
|
.flatMap(otherW -> {
|
|
if (oldTx.getFromWalletId().equals(otherW.getId())) {
|
|
otherW.setBalance(otherW.getBalance().add(oldTx.getAmount()));
|
|
} else if (oldTx.getToWalletId().equals(otherW.getId())) {
|
|
otherW.setBalance(otherW.getBalance().subtract(oldTx.getAmount()));
|
|
}
|
|
return walletRepository.save(otherW);
|
|
})
|
|
.then(transactionRepository.delete(oldTx))
|
|
.then(walletRepository.save(w))
|
|
.flatMap(saved -> handleOpeningBalance(ownerId, saved, initialBalance, initialBalanceDate));
|
|
}
|
|
});
|
|
}
|