Compare commits

..

No commits in common. "master" and "rest-api" have entirely different histories.

24 changed files with 134 additions and 282 deletions

View file

@ -13,7 +13,7 @@
<groupId>eu.ztsh</groupId>
<artifactId>wymiana-walut</artifactId>
<version>1.1.0</version>
<version>1.0.0</version>
<properties>
<!-- encoding -->

View file

@ -28,9 +28,9 @@ Prosty mikroserwis stworzony na potrzeby rekrutacji
"pesel": {
"type": "string"
},
"initial": {
"pln": {
"type": "number",
"description": "początkowy stan konta w domyślnej walucie"
"description": "początkowy stan konta w złotówkach"
}
},
"required": [
@ -171,32 +171,3 @@ Prosty mikroserwis stworzony na potrzeby rekrutacji
core <-- hsql.port --> hsqldb
```
## Konfiguracja
Aplikacja posiada dostosowaną konfigurację, która obejmuje własności:
### `hsqldb`
Konfiguracja bazy danych
| Nazwa | Opis | Typ | Wartość domyślna |
|-------|------------------|--------|------------------|
| name | host bazy danych | string | db |
| port | port bazy danych | int | 9090 |
### `nbp`
Konfiguracja połączenia z Narodowym Bankiem Polskim
| Nazwa | Opis | Typ | Wartość domyślna |
|---------|--------------|--------|-------------------|
| baseurl | host API nbp | string | http://api.nbp.pl |
### `currency`
Konfiguracja walut
| Nazwa | Opis | Typ | Wartość domyślna |
|---------|-----------------------------------------|--------|------------------|
| initial | waluta początkowa przy zakładaniu konta | string | PLN |

View file

@ -1,9 +0,0 @@
package eu.ztsh.wymiana.config;
import eu.ztsh.wymiana.model.Symbol;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("currency")
public record CurrencyProperties(Symbol initial) {
}

View file

@ -1,9 +1,6 @@
package eu.ztsh.wymiana.data.entity;
import eu.ztsh.wymiana.model.Symbol;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
@ -22,8 +19,7 @@ public class CurrencyEntity {
@Id
String pesel;
@Id
@Enumerated(EnumType.STRING)
Symbol symbol;
String symbol;
BigDecimal amount;
}

View file

@ -1,10 +1,8 @@
package eu.ztsh.wymiana.exception;
import eu.ztsh.wymiana.model.Symbol;
public class NoDataException extends RuntimeException {
public NoDataException(Symbol code, String date) {
public NoDataException(String code, String date) {
super("No data for code %s and date %s".formatted(code, date));
}

View file

@ -2,6 +2,6 @@ package eu.ztsh.wymiana.model;
import java.math.BigDecimal;
public record Currency(Symbol symbol, BigDecimal amount) {
public record Currency(String symbol, BigDecimal amount) {
}

View file

@ -1,6 +0,0 @@
package eu.ztsh.wymiana.model;
public enum Symbol {
PLN,
USD
}

View file

@ -2,6 +2,6 @@ package eu.ztsh.wymiana.model;
import java.util.Map;
public record User(String name, String surname, String pesel, Map<Symbol, Currency> currencies) {
public record User(String name, String surname, String pesel, Map<String, Currency> currencies) {
}

View file

@ -1,65 +0,0 @@
package eu.ztsh.wymiana.model;
import eu.ztsh.wymiana.web.model.UserCreateRequest;
import java.math.BigDecimal;
public class UserCreateRequestConfiguredWrapper {
private final UserCreateRequest request;
private final Symbol initialSymbol;
public String name() {
return request.name();
}
public String surname() {
return request.surname();
}
public String pesel() {
return request.pesel();
}
public BigDecimal initial() {
return request.initial();
}
public Symbol initialSymbol() {
return initialSymbol;
}
private UserCreateRequestConfiguredWrapper(Builder builder) {
this.request = builder.request;
this.initialSymbol = builder.initial;
}
public static Builder wrap(UserCreateRequest request) {
return new Builder().withRequest(request);
}
public static final class Builder {
private UserCreateRequest request;
private Symbol initial;
private Builder() {
}
private Builder withRequest(UserCreateRequest request) {
this.request = request;
return this;
}
public Builder withInitial(Symbol initial) {
this.initial = initial;
return this;
}
public UserCreateRequestConfiguredWrapper build() {
return new UserCreateRequestConfiguredWrapper(this);
}
}
}

View file

@ -4,7 +4,6 @@ import eu.ztsh.wymiana.exception.ExchangeFailedException;
import eu.ztsh.wymiana.exception.InsufficientFundsException;
import eu.ztsh.wymiana.exception.UserNotFoundException;
import eu.ztsh.wymiana.model.Currency;
import eu.ztsh.wymiana.model.Symbol;
import eu.ztsh.wymiana.model.User;
import eu.ztsh.wymiana.validation.InstanceValidator;
import eu.ztsh.wymiana.web.model.CurrencyExchangeRequest;
@ -29,17 +28,23 @@ public class CurrencyService {
public User exchange(CurrencyExchangeRequest request) {
validator.validate(request);
return userService.get(request.pesel()).map(user -> {
if (!request.from().equals(Symbol.PLN) && !request.to().equals(Symbol.PLN)) {
if (!request.from().equalsIgnoreCase("PLN") && !request.to().equalsIgnoreCase("PLN")) {
throw new ExchangeFailedException("Either 'from' or 'to' has to be PLN");
}
// As we support only USD now, we need to limit second parameter too
// Begin: unlock other currencies
if (!request.from().equalsIgnoreCase("USD") && !request.to().equalsIgnoreCase("USD")) {
throw new ExchangeFailedException("Either 'from' or 'to' has to be USD");
}
// End: unlock other currencies
var from = user.currencies().get(request.from());
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())).orElse(create(request.to())),
Optional.ofNullable(user.currencies().get(request.to().toUpperCase())).orElse(create(request.to())),
Optional.ofNullable(request.toSell()).orElse(BigDecimal.ZERO),
Optional.ofNullable(request.toBuy()).orElse(BigDecimal.ZERO));
user.currencies().putAll(exchanged);
@ -48,15 +53,16 @@ public class CurrencyService {
.orElseThrow(() -> new UserNotFoundException(request));
}
private Currency create(Symbol symbol) {
return new Currency(symbol, BigDecimal.ZERO);
private Currency create(String symbol) {
// TODO: check if supported - now limited to PLN <-> USD
return new Currency(symbol.toUpperCase(), BigDecimal.ZERO);
}
private Map<Symbol, Currency> performExchange(Currency from, Currency to, BigDecimal toSell, BigDecimal toBuy) {
private Map<String, Currency> performExchange(Currency from, Currency to, BigDecimal toSell, BigDecimal toBuy) {
BigDecimal exchangeRate;
BigDecimal neededFromAmount;
BigDecimal requestedToAmount;
if (from.symbol().equals(Symbol.PLN)) {
if (from.symbol().equalsIgnoreCase("PLN")) {
exchangeRate = nbpService.getSellRate(to.symbol());
neededFromAmount = round(toBuy.signum() != 0 ? toBuy.multiply(exchangeRate) : toSell);
requestedToAmount = round(toBuy.signum() != 0 ? toBuy : divide(toSell, exchangeRate));

View file

@ -2,7 +2,6 @@ package eu.ztsh.wymiana.service;
import eu.ztsh.wymiana.exception.NoDataException;
import eu.ztsh.wymiana.model.Rates;
import eu.ztsh.wymiana.model.Symbol;
import lombok.RequiredArgsConstructor;
import org.assertj.core.util.VisibleForTesting;
import org.springframework.http.HttpStatusCode;
@ -30,17 +29,17 @@ public class NbpService {
private static final String URI_PATTERN = "/api/exchangerates/rates/c/{code}/{date}/";
private final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private final ConcurrentMap<Symbol, RatesCache> cache = new ConcurrentHashMap<>(1);
private final ConcurrentMap<String, RatesCache> cache = new ConcurrentHashMap<>(1);
public BigDecimal getSellRate(Symbol currency) {
return getCurrency(currency).sell();
public BigDecimal getSellRate(String currency) {
return getCurrency(currency.toUpperCase()).sell();
}
public BigDecimal getBuyRate(Symbol currency) {
return getCurrency(currency).buy();
public BigDecimal getBuyRate(String currency) {
return getCurrency(currency.toUpperCase()).buy();
}
private synchronized RatesCache getCurrency(Symbol currency) {
private synchronized RatesCache getCurrency(String currency) {
var today = getFetchDate();
var cacheObject = cache.get(currency);
if (cacheObject == null || cacheObject.date().isBefore(today)) {
@ -51,7 +50,7 @@ public class NbpService {
rate.getBid(),
rate.getAsk()
);
cache.put(Symbol.valueOf(fresh.getCode().toUpperCase()), cacheObject);
cache.put(fresh.getCode(), cacheObject);
}
return cacheObject;
}
@ -70,8 +69,8 @@ public class NbpService {
}
@VisibleForTesting
Rates fetchData(Symbol code, String date) {
return restClient.get().uri(URI_PATTERN, code.name().toLowerCase(), date)
Rates fetchData(String code, String date) {
return restClient.get().uri(URI_PATTERN, code.toLowerCase(), date)
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError, ((request, response) -> {
throw new NoDataException(code, date);

View file

@ -1,10 +1,8 @@
package eu.ztsh.wymiana.service;
import eu.ztsh.wymiana.config.CurrencyProperties;
import eu.ztsh.wymiana.data.repository.UserRepository;
import eu.ztsh.wymiana.exception.UserAlreadyExistsException;
import eu.ztsh.wymiana.model.User;
import eu.ztsh.wymiana.model.UserCreateRequestConfiguredWrapper;
import eu.ztsh.wymiana.util.UserMapper;
import eu.ztsh.wymiana.validation.InstanceValidator;
import eu.ztsh.wymiana.web.model.UserCreateRequest;
@ -22,16 +20,13 @@ public class UserService {
private final UserRepository userRepository;
private final InstanceValidator validator;
private final CurrencyProperties currencyProperties;
public User create(UserCreateRequest request) {
validator.validate(request);
if (userRepository.findById(request.pesel()).isPresent()) {
throw new UserAlreadyExistsException(request);
}
return UserMapper.entityToPojo(userRepository.save(UserMapper.requestToEntity(
UserCreateRequestConfiguredWrapper.wrap(request).withInitial(currencyProperties.initial()).build()
)));
return UserMapper.entityToPojo(userRepository.save(UserMapper.requestToEntity(request)));
}
public Optional<User> get(@PESEL String pesel) {

View file

@ -2,7 +2,6 @@ package eu.ztsh.wymiana.util;
import eu.ztsh.wymiana.data.entity.CurrencyEntity;
import eu.ztsh.wymiana.model.Currency;
import eu.ztsh.wymiana.model.Symbol;
import java.util.List;
import java.util.Map;
@ -18,12 +17,12 @@ public class CurrencyMapper {
return new CurrencyEntity(pesel, pojo.symbol(), pojo.amount());
}
public static Map<Symbol, Currency> entitiesToPojoMap(List<CurrencyEntity> values) {
public static Map<String, Currency> entitiesToPojoMap(List<CurrencyEntity> values) {
return values.stream().map(CurrencyMapper::entityToPojo)
.collect(Collectors.toMap(Currency::symbol, pojo -> pojo));
}
public static List<CurrencyEntity> pojoMapToEntities(Map<Symbol, Currency> currencies, String pesel) {
public static List<CurrencyEntity> pojoMapToEntities(Map<String, Currency> currencies, String pesel) {
return currencies.values().stream().map(entry -> pojoToEntity(entry, pesel)).toList();
}

View file

@ -3,7 +3,7 @@ package eu.ztsh.wymiana.util;
import eu.ztsh.wymiana.data.entity.CurrencyEntity;
import eu.ztsh.wymiana.data.entity.UserEntity;
import eu.ztsh.wymiana.model.User;
import eu.ztsh.wymiana.model.UserCreateRequestConfiguredWrapper;
import eu.ztsh.wymiana.web.model.UserCreateRequest;
import eu.ztsh.wymiana.web.model.UserResponse;
import java.util.List;
@ -24,9 +24,9 @@ public class UserMapper {
return new UserResponse(pojo.name(), pojo.surname(), pojo.pesel(), pojo.currencies().values().stream().toList());
}
public static UserEntity requestToEntity(UserCreateRequestConfiguredWrapper request) {
public static UserEntity requestToEntity(UserCreateRequest request) {
return new UserEntity(request.pesel(), request.name(), request.surname(),
List.of(new CurrencyEntity(request.pesel(), request.initialSymbol(), request.initial())));
List.of(new CurrencyEntity(request.pesel(), "PLN", request.initial())));
}
private UserMapper() {

View file

@ -1,6 +1,5 @@
package eu.ztsh.wymiana.web.model;
import eu.ztsh.wymiana.model.Symbol;
import eu.ztsh.wymiana.validation.ValidExchangeRequest;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
@ -13,8 +12,8 @@ import java.math.BigDecimal;
@ValidExchangeRequest
public record CurrencyExchangeRequest(
@NotNull @PESEL String pesel,
@NotNull Symbol from,
@NotNull Symbol to,
@NotNull String from,
@NotNull String to,
@Min(0) BigDecimal toBuy,
@Min(0) BigDecimal toSell
) {

View file

@ -4,8 +4,6 @@ hsqldb:
nbp:
baseurl: "http://api.nbp.pl"
currency:
initial: PLN
spring:
datasource:
@ -16,9 +14,6 @@ spring:
jpa:
hibernate:
ddl-auto: create
jackson:
mapper:
ACCEPT_CASE_INSENSITIVE_ENUMS: true
management:
endpoints:

View file

@ -5,7 +5,6 @@ import eu.ztsh.wymiana.data.entity.UserEntity;
import eu.ztsh.wymiana.model.Currency;
import eu.ztsh.wymiana.model.Rate;
import eu.ztsh.wymiana.model.Rates;
import eu.ztsh.wymiana.model.Symbol;
import eu.ztsh.wymiana.model.User;
import eu.ztsh.wymiana.web.model.CurrencyExchangeRequest;
import eu.ztsh.wymiana.web.model.UserCreateRequest;
@ -30,6 +29,8 @@ public class EntityCreator {
public static BigDecimal PLN = createScaled(20.10, 2);
public static BigDecimal USD_SELL = createScaled(5.18, 2);
public static BigDecimal USD_BUY = createScaled(5.08, 2);
public static String PLN_SYMBOL = "PLN";
public static String USD_SYMBOL = "USD";
public static BigDecimal BUY_RATE = createScaled(3.8804, 4);
public static BigDecimal SELL_RATE = createScaled(3.9572, 4);
@ -44,12 +45,12 @@ public class EntityCreator {
}
public static User user(BigDecimal pln, BigDecimal usd) {
Map<Symbol, Currency> currencies = new HashMap<>();
Map<String, Currency> currencies = new HashMap<>();
if (pln.signum() > 0) {
currencies.put(Symbol.PLN, new Currency(Symbol.PLN, pln));
currencies.put("PLN", new Currency("PLN", pln));
}
if (usd.signum() > 0) {
currencies.put(Symbol.USD, new Currency(Symbol.USD, usd));
currencies.put("USD", new Currency("USD", usd));
}
return new User(Constants.NAME, Constants.SURNAME, Constants.PESEL, currencies);
}
@ -73,7 +74,7 @@ public class EntityCreator {
var rates = new Rates();
rates.setTable("C");
rates.setCurrency("dolar amerykański");
rates.setCode(Symbol.USD.toString());
rates.setCode("USD");
var rate = new Rate();
rate.setNo("096/C/NBP/2024");
rate.setEffectiveDate(date);
@ -128,13 +129,13 @@ public class EntityCreator {
var nonnulPesel = Optional.ofNullable(pesel).orElse(Constants.PESEL);
List<CurrencyEntity> currencies = new ArrayList<>();
if (pln.signum() > -1) {
currencies.add(new CurrencyEntity(nonnulPesel, Symbol.PLN, pln));
currencies.add(new CurrencyEntity(nonnulPesel, "PLN", pln));
}
if (usd.signum() > -1) {
currencies.add(new CurrencyEntity(nonnulPesel, Symbol.USD, usd));
currencies.add(new CurrencyEntity(nonnulPesel, "USD", usd));
}
if (currencies.isEmpty()) {
currencies.add(new CurrencyEntity(nonnulPesel, Symbol.PLN, Constants.PLN));
currencies.add(new CurrencyEntity(nonnulPesel, "PLN", Constants.PLN));
}
return new UserEntity(
nonnulPesel,

View file

@ -29,7 +29,6 @@ public abstract class RepositoryBasedTest {
.isNotEmpty()
.get()
.usingRecursiveComparison()
.ignoringCollectionOrder()
.isEqualTo(entity);
}

View file

@ -2,11 +2,10 @@ package eu.ztsh.wymiana.service;
import eu.ztsh.wymiana.EntityCreator;
import eu.ztsh.wymiana.RepositoryBasedTest;
import eu.ztsh.wymiana.config.CurrencyProperties;
import eu.ztsh.wymiana.data.repository.UserRepository;
import eu.ztsh.wymiana.exception.ExchangeFailedException;
import eu.ztsh.wymiana.exception.InsufficientFundsException;
import eu.ztsh.wymiana.exception.UserNotFoundException;
import eu.ztsh.wymiana.model.Symbol;
import eu.ztsh.wymiana.validation.InstanceValidator;
import eu.ztsh.wymiana.validation.ValidationFailedException;
import jakarta.transaction.Transactional;
@ -30,14 +29,12 @@ class CurrencyServiceTest extends RepositoryBasedTest {
private final CurrencyService currencyService;
@Autowired
public CurrencyServiceTest(UserRepository userRepository, InstanceValidator instanceValidator,
CurrencyProperties currencyProperties) {
public CurrencyServiceTest(UserRepository userRepository, InstanceValidator instanceValidator) {
super(userRepository);
var nbp = Mockito.mock(NbpService.class);
Mockito.when(nbp.getSellRate(Symbol.USD)).thenReturn(SELL_RATE);
Mockito.when(nbp.getBuyRate(Symbol.USD)).thenReturn(BUY_RATE);
currencyService = new CurrencyService(new UserService(userRepository, instanceValidator, currencyProperties),
nbp, instanceValidator);
Mockito.when(nbp.getSellRate("USD")).thenReturn(SELL_RATE);
Mockito.when(nbp.getBuyRate("USD")).thenReturn(BUY_RATE);
currencyService = new CurrencyService(new UserService(userRepository, instanceValidator), nbp, instanceValidator);
}
@Transactional
@ -46,12 +43,12 @@ class CurrencyServiceTest extends RepositoryBasedTest {
var entity = EntityCreator.userEntity().build();
userRepository.save(entity);
var result = currencyService.exchange(EntityCreator.exchangeRequest()
.from(Symbol.PLN)
.to(Symbol.USD)
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.toSell(PLN)
.build());
assertThat(result.currencies())
.matches(map -> map.get(Symbol.PLN).amount().signum() == 0 && Objects.equals(map.get(Symbol.USD).amount(), USD_BUY), "USD 5.08");
.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();
expect(expected);
}
@ -62,12 +59,12 @@ class CurrencyServiceTest extends RepositoryBasedTest {
var entity = EntityCreator.userEntity().build();
userRepository.save(entity);
var result = currencyService.exchange(EntityCreator.exchangeRequest()
.from(Symbol.PLN)
.to(Symbol.USD)
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.toBuy(USD_BUY)
.build());
assertThat(result.currencies())
.matches(map -> map.get(Symbol.PLN).amount().signum() == 0 && Objects.equals(map.get(Symbol.USD).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();
expect(expected);
}
@ -78,12 +75,12 @@ class CurrencyServiceTest extends RepositoryBasedTest {
var entity = EntityCreator.userEntity().pln(-1).usd(USD_SELL).build();
userRepository.save(entity);
var result = currencyService.exchange(EntityCreator.exchangeRequest()
.from(Symbol.USD)
.to(Symbol.PLN)
.from(USD_SYMBOL)
.to(PLN_SYMBOL)
.toSell(USD_SELL)
.build());
assertThat(result.currencies())
.matches(map -> Objects.equals(map.get(Symbol.PLN).amount(), PLN) && map.get(Symbol.USD).amount().signum() == 0, "PLN 20.10");
.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();
expect(expected);
}
@ -94,12 +91,12 @@ class CurrencyServiceTest extends RepositoryBasedTest {
var entity = EntityCreator.userEntity().pln(-1).usd(USD_SELL).build();
userRepository.save(entity);
var result = currencyService.exchange(EntityCreator.exchangeRequest()
.from(Symbol.USD)
.to(Symbol.PLN)
.from(USD_SYMBOL)
.to(PLN_SYMBOL)
.toBuy(PLN)
.build());
assertThat(result.currencies())
.matches(map -> Objects.equals(map.get(Symbol.PLN).amount(), PLN) && map.get(Symbol.USD).amount().signum() == 0, "PLN 20.10");
.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();
expect(expected);
}
@ -110,8 +107,8 @@ class CurrencyServiceTest extends RepositoryBasedTest {
var entity = EntityCreator.userEntity().build();
userRepository.save(entity);
var request = EntityCreator.exchangeRequest()
.from(Symbol.USD)
.to(Symbol.PLN)
.from(USD_SYMBOL)
.to(PLN_SYMBOL)
.toBuy(PLN)
.build();
assertThatThrownBy(() -> currencyService.exchange(request))
@ -124,14 +121,14 @@ class CurrencyServiceTest extends RepositoryBasedTest {
var initialValue = BigDecimal.valueOf(100);
var entity = EntityCreator.userEntity().pln(initialValue).build();
userRepository.save(entity);
currencyService.exchange(EntityCreator.exchangeRequest()
.from(Symbol.PLN)
.to(Symbol.USD)
var result1 = currencyService.exchange(EntityCreator.exchangeRequest()
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.toBuy(USD_BUY)
.build());
currencyService.exchange(EntityCreator.exchangeRequest()
.from(Symbol.USD)
.to(Symbol.PLN)
var result2 = currencyService.exchange(EntityCreator.exchangeRequest()
.from(USD_SYMBOL)
.to(PLN_SYMBOL)
.toSell(USD_BUY)
.build());
var resultOptional = userRepository.findById(entity.getPesel());
@ -140,7 +137,7 @@ class CurrencyServiceTest extends RepositoryBasedTest {
var resultEntity = resultOptional.get();
assertThat(resultEntity.getCurrencies()
.stream()
.filter(c -> c.getSymbol().equals(Symbol.PLN))
.filter(c -> c.getSymbol().equalsIgnoreCase("PLN"))
.findFirst()).isNotEmpty().get().matches(currencyEntity -> currencyEntity.getAmount().compareTo(initialValue) < 0);
}
@ -150,8 +147,8 @@ class CurrencyServiceTest extends RepositoryBasedTest {
var entity = EntityCreator.userEntity().build();
userRepository.save(entity);
var request = EntityCreator.exchangeRequest()
.from(Symbol.PLN)
.to(Symbol.USD)
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.toBuy(PLN)
.build();
assertThatThrownBy(() -> currencyService.exchange(request))
@ -164,8 +161,8 @@ class CurrencyServiceTest extends RepositoryBasedTest {
void invalidPeselTest(String pesel) {
var entity = EntityCreator.exchangeRequest()
.pesel(pesel)
.from(Symbol.PLN)
.to(Symbol.USD)
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.toSell(USD_SELL)
.build();
assertThatThrownBy(() -> currencyService.exchange(entity))
@ -176,8 +173,8 @@ class CurrencyServiceTest extends RepositoryBasedTest {
@Test
void notExistingUserTest() {
var entity = EntityCreator.exchangeRequest()
.from(Symbol.PLN)
.to(Symbol.USD)
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.toSell(USD_SELL)
.build();
assertThatThrownBy(() -> currencyService.exchange(entity))
@ -188,7 +185,7 @@ class CurrencyServiceTest extends RepositoryBasedTest {
@DisplayName("Empty 'from' value")
void emptyFromTest() {
var entity = EntityCreator.exchangeRequest()
.to(Symbol.USD)
.to(USD_SYMBOL)
.toSell(USD_SELL)
.build();
assertThatThrownBy(() -> currencyService.exchange(entity))
@ -200,7 +197,7 @@ class CurrencyServiceTest extends RepositoryBasedTest {
@DisplayName("Empty 'to' value")
void emptyToTest() {
var entity = EntityCreator.exchangeRequest()
.from(Symbol.PLN)
.from(PLN_SYMBOL)
.toSell(USD_SELL)
.build();
assertThatThrownBy(() -> currencyService.exchange(entity))

View file

@ -5,7 +5,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import eu.ztsh.wymiana.EntityCreator;
import eu.ztsh.wymiana.WireMockExtension;
import eu.ztsh.wymiana.exception.NoDataException;
import eu.ztsh.wymiana.model.Symbol;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
@ -80,7 +79,7 @@ class NbpServiceTest {
var url = "/api/exchangerates/rates/c/usd/%s/".formatted(date);
WireMockExtension.response(url, 200, new ObjectMapper().writeValueAsString(EntityCreator.rates(date)));
try {
assertThat(nbpService.getSellRate(Symbol.USD)).isEqualTo(EntityCreator.Constants.SELL_RATE);
assertThat(nbpService.getSellRate(EntityCreator.Constants.USD_SYMBOL)).isEqualTo(EntityCreator.Constants.SELL_RATE);
} finally {
WireMockExtension.verifyGet(1, url);
}
@ -93,9 +92,9 @@ class NbpServiceTest {
var url = "/api/exchangerates/rates/c/usd/%s/".formatted(date);
WireMockExtension.response(url, 200, new ObjectMapper().writeValueAsString(EntityCreator.rates(date)));
// save to cache
assertThat(nbpService.getSellRate(Symbol.USD)).isEqualTo(EntityCreator.Constants.SELL_RATE);
assertThat(nbpService.getSellRate(EntityCreator.Constants.USD_SYMBOL)).isEqualTo(EntityCreator.Constants.SELL_RATE);
// get from cache
assertThat(nbpService.getBuyRate(Symbol.USD)).isEqualTo(EntityCreator.Constants.BUY_RATE);
assertThat(nbpService.getBuyRate(EntityCreator.Constants.USD_SYMBOL)).isEqualTo(EntityCreator.Constants.BUY_RATE);
WireMockExtension.verifyGet(1, url);
}
@ -103,9 +102,9 @@ class NbpServiceTest {
@Test
void getInvalidCurrencyTest() {
var date = dtf.format(updateClock(DayOfWeek.FRIDAY));
var url = "/api/exchangerates/rates/c/usd/%s/".formatted(date);
var url = "/api/exchangerates/rates/c/usb/%s/".formatted(date);
WireMockExtension.response(url, 404, "404 NotFound - Not Found - Brak danych");
assertThatThrownBy(() -> nbpService.getSellRate(Symbol.USD)).isInstanceOf(NoDataException.class);
assertThatThrownBy(() -> nbpService.getSellRate("usb")).isInstanceOf(NoDataException.class);
WireMockExtension.verifyGet(1, url);
}

View file

@ -2,7 +2,6 @@ package eu.ztsh.wymiana.service;
import eu.ztsh.wymiana.EntityCreator;
import eu.ztsh.wymiana.RepositoryBasedTest;
import eu.ztsh.wymiana.config.CurrencyProperties;
import eu.ztsh.wymiana.data.repository.UserRepository;
import eu.ztsh.wymiana.exception.UserAlreadyExistsException;
import eu.ztsh.wymiana.util.UserMapper;
@ -22,10 +21,9 @@ class UserServiceTest extends RepositoryBasedTest {
private final UserService userService;
@Autowired
public UserServiceTest(UserRepository userRepository, InstanceValidator instanceValidator,
CurrencyProperties currencyProperties) {
public UserServiceTest(UserRepository userRepository, InstanceValidator instanceValidator) {
super(userRepository);
userService = new UserService(userRepository, instanceValidator, currencyProperties);
userService = new UserService(userRepository, instanceValidator);
}
@Test

View file

@ -1,10 +1,12 @@
package eu.ztsh.wymiana.util;
import eu.ztsh.wymiana.EntityCreator;
import eu.ztsh.wymiana.model.Symbol;
import eu.ztsh.wymiana.model.UserCreateRequestConfiguredWrapper;
import eu.ztsh.wymiana.model.Currency;
import eu.ztsh.wymiana.model.User;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
class UserMapperTest {
@ -29,9 +31,7 @@ class UserMapperTest {
@Test
void requestToEntityTest() {
var request = UserCreateRequestConfiguredWrapper.wrap(EntityCreator.userRequest().build())
.withInitial(Symbol.PLN)
.build() ;
var request = EntityCreator.userRequest().build();
var expected = EntityCreator.userEntity().build();
assertThat(UserMapper.requestToEntity(request))
.usingRecursiveComparison()

View file

@ -1,15 +1,16 @@
package eu.ztsh.wymiana.validation;
import eu.ztsh.wymiana.EntityCreator;
import eu.ztsh.wymiana.model.Symbol;
import eu.ztsh.wymiana.web.model.CurrencyExchangeRequest;
import org.junit.jupiter.api.DisplayName;
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.USD_BUY;
import static eu.ztsh.wymiana.EntityCreator.Constants.USD_SELL;
import static eu.ztsh.wymiana.EntityCreator.Constants.USD_SYMBOL;
class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeRequestValidator, CurrencyExchangeRequest> {
@ -21,8 +22,8 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
@DisplayName("Valid request with buy value specified")
void validRequestWithBuyTest() {
assertThatValidation(EntityCreator.exchangeRequest()
.from(Symbol.PLN)
.to(Symbol.USD)
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.toBuy(USD_BUY)
.build()).isTrue();
}
@ -31,8 +32,8 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
@DisplayName("Valid request with sell value specified")
void validRequestWithSellTest() {
assertThatValidation(EntityCreator.exchangeRequest()
.from(Symbol.PLN)
.to(Symbol.USD)
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.toSell(USD_SELL)
.build()).isTrue();
}
@ -41,8 +42,8 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
@DisplayName("From and To have same value")
void sameFromToTest() {
assertThatValidation(EntityCreator.exchangeRequest()
.from(Symbol.USD)
.to(Symbol.USD)
.from(USD_SYMBOL)
.to(USD_SYMBOL)
.toSell(USD_SELL)
.build()).isFalse();
}
@ -51,8 +52,8 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
@DisplayName("Empty amounts")
void emptyBuySellTest() {
assertThatValidation(EntityCreator.exchangeRequest()
.from(Symbol.PLN)
.to(Symbol.USD)
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.build()).isFalse();
}
@ -60,8 +61,8 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
@DisplayName("Both Buy and Sell params filled in")
void bothFilledBuySellTest() {
assertThatValidation(EntityCreator.exchangeRequest()
.from(Symbol.PLN)
.to(Symbol.USD)
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.toBuy(USD_BUY)
.toSell(USD_SELL)
.build()).isFalse();
@ -71,8 +72,8 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
@DisplayName("Negative buy amount value")
void negativeBuyAmountTest() {
assertThatValidation(EntityCreator.exchangeRequest()
.from(Symbol.PLN)
.to(Symbol.USD)
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.toBuy(BigDecimal.valueOf(-1.0))
.build()).isFalse();
}
@ -81,8 +82,8 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
@DisplayName("Negative sell amount value")
void negativeSellAmountTest() {
assertThatValidation(EntityCreator.exchangeRequest()
.from(Symbol.PLN)
.to(Symbol.USD)
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.toSell(BigDecimal.valueOf(-1.0))
.build()).isFalse();
}

View file

@ -4,7 +4,6 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.ztsh.wymiana.EntityCreator;
import eu.ztsh.wymiana.WireMockExtension;
import eu.ztsh.wymiana.model.Symbol;
import eu.ztsh.wymiana.util.UserMapper;
import org.junit.jupiter.api.ClassOrderer;
import org.junit.jupiter.api.DisplayName;
@ -116,7 +115,7 @@ class ApplicationIntegrationTests {
.uri(endpoint.concat("/").concat(PESEL))
.exchange()
.expectStatus().isOk()
.expectBody().json(asJson(UserMapper.pojoToResponse(UserMapper.entityToPojo(EntityCreator.userEntity().pln(100).build()))));
.expectBody().json(asJson(UserMapper.entityToPojo(EntityCreator.userEntity().pln(100).build())));
}
@Test
@ -154,8 +153,8 @@ class ApplicationIntegrationTests {
webTestClient.post()
.uri(endpoint)
.bodyValue(EntityCreator.exchangeRequest()
.from(Symbol.PLN)
.to(Symbol.USD)
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.toSell(PLN)
.build())
.exchange()
@ -175,8 +174,8 @@ class ApplicationIntegrationTests {
webTestClient.post()
.uri(endpoint)
.bodyValue(EntityCreator.exchangeRequest()
.from(Symbol.PLN)
.to(Symbol.USD)
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.toSell(PLN)
.build())
.exchange()
@ -192,8 +191,8 @@ class ApplicationIntegrationTests {
.uri(endpoint)
.bodyValue(EntityCreator.exchangeRequest()
.pesel(ANOTHER_PESEL)
.from(Symbol.PLN)
.to(Symbol.USD)
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.toSell(PLN)
.build())
.exchange()
@ -208,8 +207,8 @@ class ApplicationIntegrationTests {
.uri(endpoint)
.bodyValue(EntityCreator.exchangeRequest()
.pesel(INVALID_PESEL)
.from(Symbol.PLN)
.to(Symbol.USD)
.from(PLN_SYMBOL)
.to(USD_SYMBOL)
.toSell(PLN)
.build())
.exchange()
@ -222,34 +221,14 @@ class ApplicationIntegrationTests {
webTestClient.post()
.uri(endpoint)
.bodyValue(EntityCreator.exchangeRequest()
.from(Symbol.USD)
.to(Symbol.PLN)
.from(USD_SYMBOL)
.to(PLN_SYMBOL)
.toBuy(PLN)
.build())
.exchange()
.expectStatus().isBadRequest();
}
@Test
@DisplayName("03.6: Perform valid money exchange with lower case currency symbols")
void ignoreCaseTest() {
var date = getTodayOrLastFriday();
var expected = asJson(EntityCreator.user(BigDecimal.valueOf(100).subtract(PLN.multiply(BigDecimal.TWO)), USD_BUY.multiply(BigDecimal.TWO)));
webTestClient.post()
.uri(endpoint)
.header("Content-Type", "application/json")
.bodyValue(asJson(EntityCreator.exchangeRequest()
.from(Symbol.PLN)
.to(Symbol.USD)
.toSell(PLN)
.build()).replace("USD", "usd").replace("PLN", "pln"))
.exchange()
.expectStatus().isOk()
.expectBody().json(expected);
// cache
WireMockExtension.verifyGet(0, URI_PATTERN.formatted(date));
}
private String getTodayOrLastFriday() {
var today = LocalDate.now();
if (today.getDayOfWeek() == DayOfWeek.SATURDAY