fix: Double to BigDecimal

This commit is contained in:
Piotr Dec 2024-06-10 23:52:47 +02:00
parent b11607088a
commit f42dcce74b
Signed by: stawros
GPG key ID: F89F27AD8F881A91
15 changed files with 93 additions and 57 deletions

View file

@ -110,6 +110,7 @@
<configuration> <configuration>
<sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory> <sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
<targetPackage>eu.ztsh.wymiana.model</targetPackage> <targetPackage>eu.ztsh.wymiana.model</targetPackage>
<useBigDecimals>true</useBigDecimals>
</configuration> </configuration>
<executions> <executions>
<execution> <execution>

View file

@ -37,7 +37,7 @@ Prosty mikroserwis stworzony na potrzeby rekrutacji
"name", "name",
"surname", "surname",
"pesel", "pesel",
"pln" "initial"
] ]
} }
``` ```

View file

@ -7,6 +7,8 @@ import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import java.math.BigDecimal;
@Data @Data
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@ -18,6 +20,6 @@ public class CurrencyEntity {
String pesel; String pesel;
@Id @Id
String symbol; String symbol;
Double amount; BigDecimal amount;
} }

View file

@ -1,5 +1,7 @@
package eu.ztsh.wymiana.model; package eu.ztsh.wymiana.model;
public record Currency(String symbol, double amount) { import java.math.BigDecimal;
public record Currency(String symbol, BigDecimal amount) {
} }

View file

@ -45,8 +45,8 @@ public class CurrencyService {
} }
var exchanged = performExchange(from, var exchanged = performExchange(from,
Optional.ofNullable(user.currencies().get(request.to().toUpperCase())).orElse(create(request.to())), Optional.ofNullable(user.currencies().get(request.to().toUpperCase())).orElse(create(request.to())),
Optional.ofNullable(request.toSell()).orElse(0D), Optional.ofNullable(request.toSell()).orElse(BigDecimal.ZERO),
Optional.ofNullable(request.toBuy()).orElse(0D)); Optional.ofNullable(request.toBuy()).orElse(BigDecimal.ZERO));
user.currencies().putAll(exchanged); user.currencies().putAll(exchanged);
return userService.update(user); return userService.update(user);
}) })
@ -55,32 +55,36 @@ public class CurrencyService {
private Currency create(String symbol) { private Currency create(String symbol) {
// TODO: check if supported - now limited to PLN <-> USD // TODO: check if supported - now limited to PLN <-> USD
return new Currency(symbol.toUpperCase(), 0D); return new Currency(symbol.toUpperCase(), BigDecimal.ZERO);
} }
private Map<String, Currency> performExchange(Currency from, Currency to, double toSell, double toBuy) { private Map<String, Currency> performExchange(Currency from, Currency to, BigDecimal toSell, BigDecimal toBuy) {
double exchangeRate; BigDecimal exchangeRate;
double neededFromAmount; BigDecimal neededFromAmount;
double requestedToAmount; BigDecimal requestedToAmount;
if (from.symbol().equalsIgnoreCase("PLN")) { if (from.symbol().equalsIgnoreCase("PLN")) {
exchangeRate = nbpService.getSellRate(to.symbol()); exchangeRate = nbpService.getSellRate(to.symbol());
neededFromAmount = round(toBuy != 0 ? toBuy * exchangeRate : toSell); neededFromAmount = round(toBuy.signum() != 0 ? toBuy.multiply(exchangeRate) : toSell);
requestedToAmount = round(toBuy != 0 ? toBuy : toSell / exchangeRate); requestedToAmount = round(toBuy.signum() != 0 ? toBuy : divide(toSell, exchangeRate));
} else { } else {
exchangeRate = nbpService.getBuyRate(from.symbol()); exchangeRate = nbpService.getBuyRate(from.symbol());
neededFromAmount = round(toBuy != 0 ? toBuy / exchangeRate : toSell); neededFromAmount = round(toBuy.signum() != 0 ? divide(toBuy, exchangeRate) : toSell);
requestedToAmount = round(toBuy != 0 ? toBuy : toSell * exchangeRate); requestedToAmount = round(toBuy.signum() != 0 ? toBuy : toSell.multiply(exchangeRate));
} }
if (neededFromAmount > from.amount()) { if (neededFromAmount.compareTo(from.amount()) > 0) {
throw new InsufficientFundsException(); throw new InsufficientFundsException();
} }
var newFrom = new Currency(from.symbol(), from.amount() - neededFromAmount); var newFrom = new Currency(from.symbol(), from.amount().subtract(neededFromAmount));
var newTo = new Currency(to.symbol(), to.amount() + requestedToAmount); var newTo = new Currency(to.symbol(), to.amount().add(requestedToAmount));
return Stream.of(newFrom, newTo).collect(Collectors.toMap(Currency::symbol, currency -> currency)); return Stream.of(newFrom, newTo).collect(Collectors.toMap(Currency::symbol, currency -> currency));
} }
private double round(double input) { private BigDecimal round(BigDecimal input) {
return BigDecimal.valueOf(input).setScale(2, RoundingMode.HALF_UP).doubleValue(); return input.setScale(2, RoundingMode.HALF_UP);
}
private BigDecimal divide(BigDecimal input, BigDecimal division) {
return input.setScale(2, RoundingMode.HALF_UP).divide(division, RoundingMode.HALF_UP);
} }
} }

View file

@ -8,6 +8,7 @@ import org.springframework.http.HttpStatusCode;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient; import org.springframework.web.client.RestClient;
import java.math.BigDecimal;
import java.time.Clock; import java.time.Clock;
import java.time.DayOfWeek; import java.time.DayOfWeek;
import java.time.LocalDate; import java.time.LocalDate;
@ -30,11 +31,11 @@ public class NbpService {
private final ConcurrentMap<String, RatesCache> cache = new ConcurrentHashMap<>(1); private final ConcurrentMap<String, RatesCache> cache = new ConcurrentHashMap<>(1);
public double getSellRate(String currency) { public BigDecimal getSellRate(String currency) {
return getCurrency(currency.toUpperCase()).sell(); return getCurrency(currency.toUpperCase()).sell();
} }
public double getBuyRate(String currency) { public BigDecimal getBuyRate(String currency) {
return getCurrency(currency.toUpperCase()).buy(); return getCurrency(currency.toUpperCase()).buy();
} }
@ -43,7 +44,7 @@ public class NbpService {
var cacheObject = cache.get(currency); var cacheObject = cache.get(currency);
if (cacheObject == null || cacheObject.date().isBefore(today)) { if (cacheObject == null || cacheObject.date().isBefore(today)) {
var fresh = fetchData(currency, dtf.format(today)); var fresh = fetchData(currency, dtf.format(today));
var rate = fresh.getRates().get(0); var rate = fresh.getRates().getFirst();
cacheObject = new RatesCache( cacheObject = new RatesCache(
LocalDate.parse(rate.getEffectiveDate(), dtf), LocalDate.parse(rate.getEffectiveDate(), dtf),
rate.getBid(), rate.getBid(),
@ -82,7 +83,7 @@ public class NbpService {
|| today.getDayOfWeek() == DayOfWeek.SUNDAY; || today.getDayOfWeek() == DayOfWeek.SUNDAY;
} }
private record RatesCache(LocalDate date, double buy, double sell) { private record RatesCache(LocalDate date, BigDecimal buy, BigDecimal sell) {
} }

View file

@ -21,7 +21,7 @@ public class UserMapper {
public static UserEntity requestToEntity(UserCreateRequest request) { public static UserEntity requestToEntity(UserCreateRequest request) {
return new UserEntity(request.pesel(), request.name(), request.surname(), return new UserEntity(request.pesel(), request.name(), request.surname(),
List.of(new CurrencyEntity(request.pesel(), "PLN", request.pln()))); List.of(new CurrencyEntity(request.pesel(), "PLN", request.initial())));
} }
private UserMapper() { private UserMapper() {

View file

@ -18,8 +18,8 @@ public class ValidExchangeRequestValidator implements
return (request.from() != null && !request.from().equals(request.to())) return (request.from() != null && !request.from().equals(request.to()))
&& !((request.toBuy() == null && request.toSell() == null) && !((request.toBuy() == null && request.toSell() == null)
|| (request.toBuy() != null && request.toSell() != null)) || (request.toBuy() != null && request.toSell() != null))
&& ((request.toBuy() != null && request.toBuy() >= 0) && ((request.toBuy() != null && request.toBuy().signum() >= 0)
|| (request.toSell() != null && request.toSell() >= 0)); || (request.toSell() != null && request.toSell().signum() >= 0));
} }
} }

View file

@ -5,14 +5,16 @@ import jakarta.validation.constraints.NotNull;
import lombok.Builder; import lombok.Builder;
import org.hibernate.validator.constraints.pl.PESEL; import org.hibernate.validator.constraints.pl.PESEL;
import java.math.BigDecimal;
@Builder @Builder
@ValidExchangeRequest @ValidExchangeRequest
public record CurrencyExchangeRequest( public record CurrencyExchangeRequest(
@PESEL String pesel, @PESEL String pesel,
@NotNull String from, @NotNull String from,
@NotNull String to, @NotNull String to,
Double toBuy, BigDecimal toBuy,
Double toSell BigDecimal toSell
) { ) {
} }

View file

@ -6,11 +6,13 @@ import jakarta.validation.constraints.NotNull;
import lombok.Builder; import lombok.Builder;
import org.hibernate.validator.constraints.pl.PESEL; import org.hibernate.validator.constraints.pl.PESEL;
import java.math.BigDecimal;
@Builder @Builder
public record UserCreateRequest( public record UserCreateRequest(
@NotNull String name, @NotNull String name,
@NotNull String surname, @NotNull String surname,
@PESEL @Adult String pesel, @PESEL @Adult String pesel,
@Min(0) double pln) { @Min(0) BigDecimal initial) {
} }

View file

@ -9,6 +9,8 @@ import eu.ztsh.wymiana.model.User;
import eu.ztsh.wymiana.web.model.CurrencyExchangeRequest; import eu.ztsh.wymiana.web.model.CurrencyExchangeRequest;
import eu.ztsh.wymiana.web.model.UserCreateRequest; import eu.ztsh.wymiana.web.model.UserCreateRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -24,13 +26,13 @@ public class EntityCreator {
public static String ANOTHER_PESEL = "08280959342"; public static String ANOTHER_PESEL = "08280959342";
public static String NAME = "Janina"; public static String NAME = "Janina";
public static String SURNAME = "Kowalska"; public static String SURNAME = "Kowalska";
public static double PLN = 20.10; public static BigDecimal PLN = createScaled(20.10, 2);
public static double USD_SELL = 5.18; public static BigDecimal USD_SELL = createScaled(5.18, 2);
public static double USD_BUY = 5.08; public static BigDecimal USD_BUY = createScaled(5.08, 2);
public static String PLN_SYMBOL = "PLN"; public static String PLN_SYMBOL = "PLN";
public static String USD_SYMBOL = "USD"; public static String USD_SYMBOL = "USD";
public static double BUY_RATE = 3.8804; public static BigDecimal BUY_RATE = createScaled(3.8804, 4);
public static double SELL_RATE = 3.9572; public static BigDecimal SELL_RATE = createScaled(3.9572, 4);
} }
@ -39,25 +41,29 @@ public class EntityCreator {
} }
public static User user() { public static User user() {
return user(Constants.PLN, 0); return user(Constants.PLN, BigDecimal.ZERO);
} }
public static User user(double pln, double usd) { public static User user(BigDecimal pln, BigDecimal usd) {
Map<String, Currency> currencies = new HashMap<>(); Map<String, Currency> currencies = new HashMap<>();
if (pln > 0) { if (pln.signum() > 0) {
currencies.put("PLN", new Currency("PLN", pln)); currencies.put("PLN", new Currency("PLN", pln));
} }
if (usd > 0) { if (usd.signum() > 0) {
currencies.put("USD", new Currency("USD", usd)); currencies.put("USD", new Currency("USD", usd));
} }
return new User(Constants.NAME, Constants.SURNAME, Constants.PESEL, currencies); return new User(Constants.NAME, Constants.SURNAME, Constants.PESEL, currencies);
} }
public static UserCreateRequest.UserCreateRequestBuilder userRequest() { public static UserCreateRequest.UserCreateRequestBuilder userRequest() {
return userRequest(null);
}
public static UserCreateRequest.UserCreateRequestBuilder userRequest(Double initial) {
return UserCreateRequest.builder().name(Constants.NAME) return UserCreateRequest.builder().name(Constants.NAME)
.surname(Constants.SURNAME) .surname(Constants.SURNAME)
.pesel(Constants.PESEL) .pesel(Constants.PESEL)
.pln(Constants.PLN); .initial(initial != null ? createScaled(initial, 2) : Constants.PLN);
} }
public static CurrencyExchangeRequest.CurrencyExchangeRequestBuilder exchangeRequest() { public static CurrencyExchangeRequest.CurrencyExchangeRequestBuilder exchangeRequest() {
@ -83,8 +89,8 @@ public class EntityCreator {
String name; String name;
String surname; String surname;
String pesel; String pesel;
double pln = -1; BigDecimal pln = BigDecimal.valueOf(-1);
double usd = -1; BigDecimal usd = BigDecimal.valueOf(-1);
public UserEntityBuilder name(String name) { public UserEntityBuilder name(String name) {
this.name = name; this.name = name;
@ -102,22 +108,30 @@ public class EntityCreator {
} }
public UserEntityBuilder pln(double pln) { public UserEntityBuilder pln(double pln) {
this.pln = pln; return this.pln(BigDecimal.valueOf(pln));
}
public UserEntityBuilder pln(BigDecimal pln) {
this.pln = pln.setScale(2, RoundingMode.HALF_UP);
return this; return this;
} }
public UserEntityBuilder usd(double usd) { public UserEntityBuilder usd(double usd) {
this.usd = usd; return this.usd(BigDecimal.valueOf(usd));
}
public UserEntityBuilder usd(BigDecimal usd) {
this.usd = usd.setScale(2, RoundingMode.HALF_UP);
return this; return this;
} }
public UserEntity build() { public UserEntity build() {
var nonnulPesel = Optional.ofNullable(pesel).orElse(Constants.PESEL); var nonnulPesel = Optional.ofNullable(pesel).orElse(Constants.PESEL);
List<CurrencyEntity> currencies = new ArrayList<>(); List<CurrencyEntity> currencies = new ArrayList<>();
if (pln > -1) { if (pln.signum() > -1) {
currencies.add(new CurrencyEntity(nonnulPesel, "PLN", pln)); currencies.add(new CurrencyEntity(nonnulPesel, "PLN", pln));
} }
if (usd > -1) { if (usd.signum() > -1) {
currencies.add(new CurrencyEntity(nonnulPesel, "USD", usd)); currencies.add(new CurrencyEntity(nonnulPesel, "USD", usd));
} }
if (currencies.isEmpty()) { if (currencies.isEmpty()) {
@ -133,4 +147,8 @@ public class EntityCreator {
} }
private static BigDecimal createScaled(double input, int scale) {
return BigDecimal.valueOf(input).setScale(scale, RoundingMode.HALF_UP);
}
} }

View file

@ -16,6 +16,8 @@ import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import java.math.BigDecimal;
import java.util.Objects;
import java.util.stream.Stream; import java.util.stream.Stream;
import static eu.ztsh.wymiana.EntityCreator.Constants.*; import static eu.ztsh.wymiana.EntityCreator.Constants.*;
@ -46,7 +48,7 @@ class CurrencyServiceTest extends RepositoryBasedTest {
.toSell(PLN) .toSell(PLN)
.build()); .build());
assertThat(result.currencies()) assertThat(result.currencies())
.matches(map -> map.get(PLN_SYMBOL).amount() == 0 && map.get(USD_SYMBOL).amount() == USD_BUY); .matches(map -> map.get(PLN_SYMBOL).amount().signum() == 0 && Objects.equals(map.get(USD_SYMBOL).amount(), USD_BUY), "USD 5.08");
var expected = EntityCreator.userEntity().pln(0).usd(USD_BUY).build(); var expected = EntityCreator.userEntity().pln(0).usd(USD_BUY).build();
expect(expected); expect(expected);
} }
@ -62,7 +64,7 @@ class CurrencyServiceTest extends RepositoryBasedTest {
.toBuy(USD_BUY) .toBuy(USD_BUY)
.build()); .build());
assertThat(result.currencies()) assertThat(result.currencies())
.matches(map -> map.get(PLN_SYMBOL).amount() == 0 && map.get(USD_SYMBOL).amount() == USD_BUY); .matches(map -> map.get(PLN_SYMBOL).amount().signum() == 0 && Objects.equals(map.get(USD_SYMBOL).amount(), USD_BUY));
var expected = EntityCreator.userEntity().pln(0).usd(USD_BUY).build(); var expected = EntityCreator.userEntity().pln(0).usd(USD_BUY).build();
expect(expected); expect(expected);
} }
@ -78,7 +80,7 @@ class CurrencyServiceTest extends RepositoryBasedTest {
.toSell(USD_SELL) .toSell(USD_SELL)
.build()); .build());
assertThat(result.currencies()) assertThat(result.currencies())
.matches(map -> map.get(PLN_SYMBOL).amount() == PLN && map.get(USD_SYMBOL).amount() == 0); .matches(map -> Objects.equals(map.get(PLN_SYMBOL).amount(), PLN) && map.get(USD_SYMBOL).amount().signum() == 0, "PLN 20.10");
var expected = EntityCreator.userEntity().pln(PLN).usd(0).build(); var expected = EntityCreator.userEntity().pln(PLN).usd(0).build();
expect(expected); expect(expected);
} }
@ -94,7 +96,7 @@ class CurrencyServiceTest extends RepositoryBasedTest {
.toBuy(PLN) .toBuy(PLN)
.build()); .build());
assertThat(result.currencies()) assertThat(result.currencies())
.matches(map -> map.get(PLN_SYMBOL).amount() == PLN && map.get(USD_SYMBOL).amount() == 0); .matches(map -> Objects.equals(map.get(PLN_SYMBOL).amount(), PLN) && map.get(USD_SYMBOL).amount().signum() == 0, "PLN 20.10");
var expected = EntityCreator.userEntity().pln(PLN).usd(0).build(); var expected = EntityCreator.userEntity().pln(PLN).usd(0).build();
expect(expected); expect(expected);
} }
@ -116,7 +118,7 @@ class CurrencyServiceTest extends RepositoryBasedTest {
@Transactional @Transactional
@Test @Test
void doubleExchangeTest() { void doubleExchangeTest() {
var initialValue = 100; var initialValue = BigDecimal.valueOf(100);
var entity = EntityCreator.userEntity().pln(initialValue).build(); var entity = EntityCreator.userEntity().pln(initialValue).build();
userRepository.save(entity); userRepository.save(entity);
var result1 = currencyService.exchange(EntityCreator.exchangeRequest() var result1 = currencyService.exchange(EntityCreator.exchangeRequest()
@ -136,7 +138,7 @@ class CurrencyServiceTest extends RepositoryBasedTest {
assertThat(resultEntity.getCurrencies() assertThat(resultEntity.getCurrencies()
.stream() .stream()
.filter(c -> c.getSymbol().equalsIgnoreCase("PLN")) .filter(c -> c.getSymbol().equalsIgnoreCase("PLN"))
.findFirst()).isNotEmpty().get().matches(currencyEntity -> currencyEntity.getAmount() < initialValue); .findFirst()).isNotEmpty().get().matches(currencyEntity -> currencyEntity.getAmount().compareTo(initialValue) < 0);
} }
@Transactional @Transactional

View file

@ -50,10 +50,9 @@ class UserServiceTest extends RepositoryBasedTest {
@DisplayName("Try to create another user with same PESEL") @DisplayName("Try to create another user with same PESEL")
void createDuplicatedPeselTest() { void createDuplicatedPeselTest() {
var first = EntityCreator.userRequest().build(); var first = EntityCreator.userRequest().build();
var second = EntityCreator.userRequest() var second = EntityCreator.userRequest(30.30)
.name("Jan") .name("Jan")
.surname("Kowalski") .surname("Kowalski")
.pln(30.30)
.build(); .build();
userService.create(first); userService.create(first);
assertThatThrownBy(() -> userService.create(second)) assertThatThrownBy(() -> userService.create(second))

View file

@ -5,6 +5,8 @@ import eu.ztsh.wymiana.web.model.CurrencyExchangeRequest;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import static eu.ztsh.wymiana.EntityCreator.Constants.PLN_SYMBOL; import static eu.ztsh.wymiana.EntityCreator.Constants.PLN_SYMBOL;
import static eu.ztsh.wymiana.EntityCreator.Constants.USD_BUY; import static eu.ztsh.wymiana.EntityCreator.Constants.USD_BUY;
import static eu.ztsh.wymiana.EntityCreator.Constants.USD_SELL; import static eu.ztsh.wymiana.EntityCreator.Constants.USD_SELL;
@ -72,7 +74,7 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
assertThatValidation(EntityCreator.exchangeRequest() assertThatValidation(EntityCreator.exchangeRequest()
.from(PLN_SYMBOL) .from(PLN_SYMBOL)
.to(USD_SYMBOL) .to(USD_SYMBOL)
.toBuy(-1.0) .toBuy(BigDecimal.valueOf(-1.0))
.build()).isFalse(); .build()).isFalse();
} }
@ -82,7 +84,7 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
assertThatValidation(EntityCreator.exchangeRequest() assertThatValidation(EntityCreator.exchangeRequest()
.from(PLN_SYMBOL) .from(PLN_SYMBOL)
.to(USD_SYMBOL) .to(USD_SYMBOL)
.toSell(-1.0) .toSell(BigDecimal.valueOf(-1.0))
.build()).isFalse(); .build()).isFalse();
} }

View file

@ -18,6 +18,7 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient;
import java.math.BigDecimal;
import java.time.DayOfWeek; import java.time.DayOfWeek;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
@ -80,7 +81,7 @@ class ApplicationIntegrationTests {
void createUserTest() { void createUserTest() {
webTestClient.post() webTestClient.post()
.uri(endpoint) .uri(endpoint)
.bodyValue(EntityCreator.userRequest().pln(100).build()) .bodyValue(EntityCreator.userRequest(100D).build())
.exchange() .exchange()
.expectStatus().isNoContent(); .expectStatus().isNoContent();
} }
@ -169,7 +170,7 @@ class ApplicationIntegrationTests {
200, 200,
asJson(EntityCreator.rates(date)) asJson(EntityCreator.rates(date))
); );
var expected = asJson(EntityCreator.user(100 - PLN, USD_BUY)); var expected = asJson(EntityCreator.user(BigDecimal.valueOf(100).subtract(PLN), USD_BUY));
webTestClient.post() webTestClient.post()
.uri(endpoint) .uri(endpoint)
.bodyValue(EntityCreator.exchangeRequest() .bodyValue(EntityCreator.exchangeRequest()