fix: exchange method fixes

This commit is contained in:
Piotr Dec 2024-05-24 17:19:30 +02:00
parent c87bcc8b54
commit 71109174f7
Signed by: stawros
GPG key ID: F89F27AD8F881A91
2 changed files with 73 additions and 13 deletions

View file

@ -9,6 +9,8 @@ import eu.ztsh.wymiana.web.model.CurrencyExchangeRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
@ -35,8 +37,13 @@ public class CurrencyService {
}
// End: unlock other currencies
var exchanged = performExchange(user.currencies().get(request.from().toUpperCase()),
user.currencies().get(request.to().toUpperCase()),
var from = user.currencies().get(request.from().toUpperCase());
if (from == null) {
// There is no currency 'from' opened so no need to check if user has funds to exchange
throw new InsufficientFundsException();
}
var exchanged = performExchange(from,
Optional.ofNullable(user.currencies().get(request.to().toUpperCase())).orElse(create(request.to())),
Optional.ofNullable(request.toSell()).orElse(0D),
Optional.ofNullable(request.toBuy()).orElse(0D));
user.currencies().putAll(exchanged);
@ -45,18 +52,23 @@ public class CurrencyService {
.orElseThrow(ExchangeFailedException::new);
}
private Currency create(String symbol) {
// TODO: check if supported
return new Currency(symbol.toUpperCase(), 0D);
}
private Map<String, Currency> performExchange(Currency from, Currency to, double toSell, double toBuy) {
double exchangeRate;
double neededFromAmount;
double requestedToAmount;
if (from.symbol().equalsIgnoreCase("PLN")) {
exchangeRate = nbpService.getSellRate(to.symbol());
neededFromAmount = toBuy != 0 ? toBuy * exchangeRate : toSell;
requestedToAmount = toBuy != 0 ? toBuy : toSell / exchangeRate;
neededFromAmount = round(toBuy != 0 ? toBuy * exchangeRate : toSell);
requestedToAmount = round(toBuy != 0 ? toBuy : toSell / exchangeRate);
} else {
exchangeRate = nbpService.getSellRate(from.symbol());
neededFromAmount = toBuy != 0 ? toBuy / exchangeRate : toSell;
requestedToAmount = toBuy != 0 ? toBuy : toSell * exchangeRate;
exchangeRate = nbpService.getBuyRate(from.symbol());
neededFromAmount = round(toBuy != 0 ? toBuy / exchangeRate : toSell);
requestedToAmount = round(toBuy != 0 ? toBuy : toSell * exchangeRate);
}
if (neededFromAmount > from.amount()) {
throw new InsufficientFundsException();
@ -66,4 +78,8 @@ public class CurrencyService {
return Stream.of(newFrom, newTo).collect(Collectors.toMap(Currency::symbol, currency -> currency));
}
private double round(double input) {
return BigDecimal.valueOf(input).setScale(2, RoundingMode.HALF_UP).doubleValue();
}
}