Merge pull request 'Fixes after code review' from fixes into master
This commit is contained in:
commit
4e9f41cdcf
29 changed files with 435 additions and 185 deletions
7
pom.xml
7
pom.xml
|
@ -28,6 +28,7 @@
|
|||
|
||||
<!-- dependencies -->
|
||||
<wiremock.version>3.5.4</wiremock.version>
|
||||
<openapi.version>2.5.0</openapi.version>
|
||||
|
||||
<!-- plugins -->
|
||||
<jsonschema2pojo.version>1.2.1</jsonschema2pojo.version>
|
||||
|
@ -62,6 +63,11 @@
|
|||
<artifactId>lombok</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
|
||||
<version>${openapi.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Database -->
|
||||
<dependency>
|
||||
|
@ -110,6 +116,7 @@
|
|||
<configuration>
|
||||
<sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
|
||||
<targetPackage>eu.ztsh.wymiana.model</targetPackage>
|
||||
<useBigDecimals>true</useBigDecimals>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
|
|
38
readme.md
38
readme.md
|
@ -28,16 +28,16 @@ Prosty mikroserwis stworzony na potrzeby rekrutacji
|
|||
"pesel": {
|
||||
"type": "string"
|
||||
},
|
||||
"pln": {
|
||||
"initial": {
|
||||
"type": "number",
|
||||
"description": "początkowy stan konta w złotówkach"
|
||||
"description": "początkowy stan konta w domyślnej walucie"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"surname",
|
||||
"pesel",
|
||||
"pln"
|
||||
"initial"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
@ -79,7 +79,6 @@ Prosty mikroserwis stworzony na potrzeby rekrutacji
|
|||
"type": "string"
|
||||
},
|
||||
"currencies": {
|
||||
"$comment": "TODO: Map -> List",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/def/currency"
|
||||
|
@ -169,6 +168,35 @@ Prosty mikroserwis stworzony na potrzeby rekrutacji
|
|||
actor <--> exchange
|
||||
endpoint <--> core
|
||||
core <--> tabC
|
||||
core <-- hsql.port --> hsqldb
|
||||
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 |
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
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) {
|
||||
|
||||
}
|
|
@ -1,12 +1,17 @@
|
|||
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;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
|
@ -17,7 +22,8 @@ public class CurrencyEntity {
|
|||
@Id
|
||||
String pesel;
|
||||
@Id
|
||||
String symbol;
|
||||
Double amount;
|
||||
@Enumerated(EnumType.STRING)
|
||||
Symbol symbol;
|
||||
BigDecimal amount;
|
||||
|
||||
}
|
||||
|
|
|
@ -1,8 +1,10 @@
|
|||
package eu.ztsh.wymiana.exception;
|
||||
|
||||
import eu.ztsh.wymiana.model.Symbol;
|
||||
|
||||
public class NoDataException extends RuntimeException {
|
||||
|
||||
public NoDataException(String code, String date) {
|
||||
public NoDataException(Symbol code, String date) {
|
||||
super("No data for code %s and date %s".formatted(code, date));
|
||||
}
|
||||
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
package eu.ztsh.wymiana.model;
|
||||
|
||||
public record Currency(String symbol, double amount) {
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public record Currency(Symbol symbol, BigDecimal amount) {
|
||||
|
||||
}
|
||||
|
|
6
src/main/java/eu/ztsh/wymiana/model/Symbol.java
Normal file
6
src/main/java/eu/ztsh/wymiana/model/Symbol.java
Normal file
|
@ -0,0 +1,6 @@
|
|||
package eu.ztsh.wymiana.model;
|
||||
|
||||
public enum Symbol {
|
||||
PLN,
|
||||
USD
|
||||
}
|
|
@ -2,6 +2,6 @@ package eu.ztsh.wymiana.model;
|
|||
|
||||
import java.util.Map;
|
||||
|
||||
public record User(String name, String surname, String pesel, Map<String, Currency> currencies) {
|
||||
public record User(String name, String surname, String pesel, Map<Symbol, Currency> currencies) {
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,65 @@
|
|||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -4,6 +4,7 @@ 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;
|
||||
|
@ -28,59 +29,56 @@ public class CurrencyService {
|
|||
public User exchange(CurrencyExchangeRequest request) {
|
||||
validator.validate(request);
|
||||
return userService.get(request.pesel()).map(user -> {
|
||||
if (!request.from().equalsIgnoreCase("PLN") && !request.to().equalsIgnoreCase("PLN")) {
|
||||
if (!request.from().equals(Symbol.PLN) && !request.to().equals(Symbol.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().toUpperCase());
|
||||
var from = user.currencies().get(request.from());
|
||||
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));
|
||||
Optional.ofNullable(user.currencies().get(request.to())).orElse(create(request.to())),
|
||||
Optional.ofNullable(request.toSell()).orElse(BigDecimal.ZERO),
|
||||
Optional.ofNullable(request.toBuy()).orElse(BigDecimal.ZERO));
|
||||
user.currencies().putAll(exchanged);
|
||||
return userService.update(user);
|
||||
})
|
||||
.orElseThrow(() -> new UserNotFoundException(request));
|
||||
}
|
||||
|
||||
private Currency create(String symbol) {
|
||||
// TODO: check if supported - now limited to PLN <-> USD
|
||||
return new Currency(symbol.toUpperCase(), 0D);
|
||||
private Currency create(Symbol symbol) {
|
||||
return new Currency(symbol, BigDecimal.ZERO);
|
||||
}
|
||||
|
||||
private Map<String, Currency> performExchange(Currency from, Currency to, double toSell, double toBuy) {
|
||||
double exchangeRate;
|
||||
double neededFromAmount;
|
||||
double requestedToAmount;
|
||||
if (from.symbol().equalsIgnoreCase("PLN")) {
|
||||
private Map<Symbol, Currency> performExchange(Currency from, Currency to, BigDecimal toSell, BigDecimal toBuy) {
|
||||
BigDecimal exchangeRate;
|
||||
BigDecimal neededFromAmount;
|
||||
BigDecimal requestedToAmount;
|
||||
if (from.symbol().equals(Symbol.PLN)) {
|
||||
exchangeRate = nbpService.getSellRate(to.symbol());
|
||||
neededFromAmount = round(toBuy != 0 ? toBuy * exchangeRate : toSell);
|
||||
requestedToAmount = round(toBuy != 0 ? toBuy : toSell / exchangeRate);
|
||||
neededFromAmount = round(toBuy.signum() != 0 ? toBuy.multiply(exchangeRate) : toSell);
|
||||
requestedToAmount = round(toBuy.signum() != 0 ? toBuy : divide(toSell, exchangeRate));
|
||||
} else {
|
||||
exchangeRate = nbpService.getBuyRate(from.symbol());
|
||||
neededFromAmount = round(toBuy != 0 ? toBuy / exchangeRate : toSell);
|
||||
requestedToAmount = round(toBuy != 0 ? toBuy : toSell * exchangeRate);
|
||||
neededFromAmount = round(toBuy.signum() != 0 ? divide(toBuy, exchangeRate) : toSell);
|
||||
requestedToAmount = round(toBuy.signum() != 0 ? toBuy : toSell.multiply(exchangeRate));
|
||||
}
|
||||
if (neededFromAmount > from.amount()) {
|
||||
if (neededFromAmount.compareTo(from.amount()) > 0) {
|
||||
throw new InsufficientFundsException();
|
||||
}
|
||||
var newFrom = new Currency(from.symbol(), from.amount() - neededFromAmount);
|
||||
var newTo = new Currency(to.symbol(), to.amount() + requestedToAmount);
|
||||
var newFrom = new Currency(from.symbol(), from.amount().subtract(neededFromAmount));
|
||||
var newTo = new Currency(to.symbol(), to.amount().add(requestedToAmount));
|
||||
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();
|
||||
private BigDecimal round(BigDecimal input) {
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -2,12 +2,14 @@ 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;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestClient;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Clock;
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
|
@ -28,28 +30,28 @@ 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<String, RatesCache> cache = new ConcurrentHashMap<>(1);
|
||||
private final ConcurrentMap<Symbol, RatesCache> cache = new ConcurrentHashMap<>(1);
|
||||
|
||||
public double getSellRate(String currency) {
|
||||
return getCurrency(currency.toUpperCase()).sell();
|
||||
public BigDecimal getSellRate(Symbol currency) {
|
||||
return getCurrency(currency).sell();
|
||||
}
|
||||
|
||||
public double getBuyRate(String currency) {
|
||||
return getCurrency(currency.toUpperCase()).buy();
|
||||
public BigDecimal getBuyRate(Symbol currency) {
|
||||
return getCurrency(currency).buy();
|
||||
}
|
||||
|
||||
private synchronized RatesCache getCurrency(String currency) {
|
||||
private synchronized RatesCache getCurrency(Symbol currency) {
|
||||
var today = getFetchDate();
|
||||
var cacheObject = cache.get(currency);
|
||||
if (cacheObject == null || cacheObject.date().isBefore(today)) {
|
||||
var fresh = fetchData(currency, dtf.format(today));
|
||||
var rate = fresh.getRates().get(0);
|
||||
var rate = fresh.getRates().getFirst();
|
||||
cacheObject = new RatesCache(
|
||||
LocalDate.parse(rate.getEffectiveDate(), dtf),
|
||||
rate.getBid(),
|
||||
rate.getAsk()
|
||||
);
|
||||
cache.put(fresh.getCode(), cacheObject);
|
||||
cache.put(Symbol.valueOf(fresh.getCode().toUpperCase()), cacheObject);
|
||||
}
|
||||
return cacheObject;
|
||||
}
|
||||
|
@ -68,8 +70,8 @@ public class NbpService {
|
|||
}
|
||||
|
||||
@VisibleForTesting
|
||||
Rates fetchData(String code, String date) {
|
||||
return restClient.get().uri(URI_PATTERN, code.toLowerCase(), date)
|
||||
Rates fetchData(Symbol code, String date) {
|
||||
return restClient.get().uri(URI_PATTERN, code.name().toLowerCase(), date)
|
||||
.retrieve()
|
||||
.onStatus(HttpStatusCode::is4xxClientError, ((request, response) -> {
|
||||
throw new NoDataException(code, date);
|
||||
|
@ -82,7 +84,7 @@ public class NbpService {
|
|||
|| today.getDayOfWeek() == DayOfWeek.SUNDAY;
|
||||
}
|
||||
|
||||
private record RatesCache(LocalDate date, double buy, double sell) {
|
||||
private record RatesCache(LocalDate date, BigDecimal buy, BigDecimal sell) {
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -1,8 +1,10 @@
|
|||
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;
|
||||
|
@ -20,13 +22,16 @@ 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(request)));
|
||||
return UserMapper.entityToPojo(userRepository.save(UserMapper.requestToEntity(
|
||||
UserCreateRequestConfiguredWrapper.wrap(request).withInitial(currencyProperties.initial()).build()
|
||||
)));
|
||||
}
|
||||
|
||||
public Optional<User> get(@PESEL String pesel) {
|
||||
|
|
|
@ -2,6 +2,7 @@ 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;
|
||||
|
@ -17,12 +18,12 @@ public class CurrencyMapper {
|
|||
return new CurrencyEntity(pesel, pojo.symbol(), pojo.amount());
|
||||
}
|
||||
|
||||
public static Map<String, Currency> entitiesToPojoMap(List<CurrencyEntity> values) {
|
||||
public static Map<Symbol, Currency> entitiesToPojoMap(List<CurrencyEntity> values) {
|
||||
return values.stream().map(CurrencyMapper::entityToPojo)
|
||||
.collect(Collectors.toMap(Currency::symbol, pojo -> pojo));
|
||||
}
|
||||
|
||||
public static List<CurrencyEntity> pojoMapToEntities(Map<String, Currency> currencies, String pesel) {
|
||||
public static List<CurrencyEntity> pojoMapToEntities(Map<Symbol, Currency> currencies, String pesel) {
|
||||
return currencies.values().stream().map(entry -> pojoToEntity(entry, pesel)).toList();
|
||||
}
|
||||
|
||||
|
|
|
@ -3,7 +3,8 @@ 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.web.model.UserCreateRequest;
|
||||
import eu.ztsh.wymiana.model.UserCreateRequestConfiguredWrapper;
|
||||
import eu.ztsh.wymiana.web.model.UserResponse;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
@ -19,9 +20,13 @@ public class UserMapper {
|
|||
CurrencyMapper.pojoMapToEntities(pojo.currencies(), pojo.pesel()));
|
||||
}
|
||||
|
||||
public static UserEntity requestToEntity(UserCreateRequest request) {
|
||||
public static UserResponse pojoToResponse(User pojo) {
|
||||
return new UserResponse(pojo.name(), pojo.surname(), pojo.pesel(), pojo.currencies().values().stream().toList());
|
||||
}
|
||||
|
||||
public static UserEntity requestToEntity(UserCreateRequestConfiguredWrapper request) {
|
||||
return new UserEntity(request.pesel(), request.name(), request.surname(),
|
||||
List.of(new CurrencyEntity(request.pesel(), "PLN", request.pln())));
|
||||
List.of(new CurrencyEntity(request.pesel(), request.initialSymbol(), request.initial())));
|
||||
}
|
||||
|
||||
private UserMapper() {
|
||||
|
|
|
@ -18,8 +18,8 @@ public class ValidExchangeRequestValidator implements
|
|||
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.toBuy() >= 0)
|
||||
|| (request.toSell() != null && request.toSell() >= 0));
|
||||
&& ((request.toBuy() != null && request.toBuy().signum() >= 0)
|
||||
|| (request.toSell() != null && request.toSell().signum() >= 0));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -4,9 +4,16 @@ import eu.ztsh.wymiana.exception.InsufficientFundsException;
|
|||
import eu.ztsh.wymiana.exception.UserNotFoundException;
|
||||
import eu.ztsh.wymiana.service.CurrencyService;
|
||||
import eu.ztsh.wymiana.web.model.CurrencyExchangeRequest;
|
||||
import eu.ztsh.wymiana.web.model.UserResponse;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
|
@ -22,6 +29,22 @@ public class ExchangeController {
|
|||
|
||||
private final CurrencyService currencyService;
|
||||
|
||||
@Operation(summary = "Perform exchange")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200",
|
||||
description = "Exchange performed successfully",
|
||||
content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
|
||||
schema = @Schema(implementation = UserResponse.class))),
|
||||
@ApiResponse(responseCode = "400",
|
||||
description = "Insufficient funds",
|
||||
content = @Content(mediaType = MediaType.TEXT_PLAIN_VALUE)),
|
||||
@ApiResponse(responseCode = "404",
|
||||
description = "User not found",
|
||||
content = @Content(mediaType = MediaType.TEXT_PLAIN_VALUE)),
|
||||
@ApiResponse(responseCode = "500",
|
||||
description = "Another error has occurred",
|
||||
content = @Content(mediaType = MediaType.TEXT_PLAIN_VALUE))
|
||||
})
|
||||
@PostMapping
|
||||
public ResponseEntity<Object> exchange(@Valid @RequestBody CurrencyExchangeRequest request) {
|
||||
try {
|
||||
|
|
|
@ -2,14 +2,21 @@ package eu.ztsh.wymiana.web.controller;
|
|||
|
||||
import eu.ztsh.wymiana.exception.UserAlreadyExistsException;
|
||||
import eu.ztsh.wymiana.exception.UserNotFoundException;
|
||||
import eu.ztsh.wymiana.model.User;
|
||||
import eu.ztsh.wymiana.service.UserService;
|
||||
import eu.ztsh.wymiana.util.UserMapper;
|
||||
import eu.ztsh.wymiana.validation.ValidationFailedException;
|
||||
import eu.ztsh.wymiana.web.model.UserCreateRequest;
|
||||
import eu.ztsh.wymiana.web.model.UserResponse;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.ValidationException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
@ -23,14 +30,23 @@ import org.springframework.web.bind.annotation.RestController;
|
|||
@Validated
|
||||
@RestController
|
||||
@RequestMapping(path = "/api/user", produces = "application/json")
|
||||
@Tag(name="User management", description = "Create or get user")
|
||||
public class UserController {
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
@Operation(summary = "Get user by PESEL")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "User found"),
|
||||
@ApiResponse(responseCode = "400", description = "Request not valid", content = @Content),
|
||||
@ApiResponse(responseCode = "404", description = "User not found", content = @Content),
|
||||
@ApiResponse(responseCode = "500", description = "Another error has occurred", content = @Content)
|
||||
})
|
||||
@GetMapping("{pesel}")
|
||||
public ResponseEntity<User> get(@PathVariable("pesel") String pesel) {
|
||||
public ResponseEntity<UserResponse> get(@PathVariable("pesel") String pesel) {
|
||||
try {
|
||||
return userService.get(pesel)
|
||||
.map(UserMapper::pojoToResponse)
|
||||
.map(ResponseEntity::ok)
|
||||
.orElseThrow(() -> new UserNotFoundException(pesel));
|
||||
} catch (Exception e) {
|
||||
|
@ -42,6 +58,13 @@ public class UserController {
|
|||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "Create user")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "204", description = "User created", content = @Content),
|
||||
@ApiResponse(responseCode = "400", description = "Request not valid", content = @Content(mediaType = MediaType.TEXT_PLAIN_VALUE)),
|
||||
@ApiResponse(responseCode = "409", description = "User already exists", content = @Content(mediaType = MediaType.TEXT_PLAIN_VALUE)),
|
||||
@ApiResponse(responseCode = "500", description = "Another error has occurred", content = @Content(mediaType = MediaType.TEXT_PLAIN_VALUE))
|
||||
})
|
||||
@PostMapping
|
||||
public ResponseEntity<String> create(@Valid @RequestBody UserCreateRequest request) {
|
||||
try {
|
||||
|
|
|
@ -1,18 +1,22 @@
|
|||
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;
|
||||
import lombok.Builder;
|
||||
import org.hibernate.validator.constraints.pl.PESEL;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Builder
|
||||
@ValidExchangeRequest
|
||||
public record CurrencyExchangeRequest(
|
||||
@PESEL String pesel,
|
||||
@NotNull String from,
|
||||
@NotNull String to,
|
||||
Double toBuy,
|
||||
Double toSell
|
||||
@NotNull @PESEL String pesel,
|
||||
@NotNull Symbol from,
|
||||
@NotNull Symbol to,
|
||||
@Min(0) BigDecimal toBuy,
|
||||
@Min(0) BigDecimal toSell
|
||||
) {
|
||||
|
||||
}
|
||||
|
|
|
@ -6,11 +6,13 @@ import jakarta.validation.constraints.NotNull;
|
|||
import lombok.Builder;
|
||||
import org.hibernate.validator.constraints.pl.PESEL;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Builder
|
||||
public record UserCreateRequest(
|
||||
@NotNull String name,
|
||||
@NotNull String surname,
|
||||
@PESEL @Adult String pesel,
|
||||
@Min(0) double pln) {
|
||||
@PESEL @Adult @NotNull String pesel,
|
||||
@NotNull @Min(0) BigDecimal initial) {
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
package eu.ztsh.wymiana.web.model;
|
||||
|
||||
import eu.ztsh.wymiana.model.Currency;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record UserResponse(String name, String surname, String pesel, List<Currency> currencies) {
|
||||
|
||||
}
|
|
@ -4,6 +4,8 @@ hsqldb:
|
|||
|
||||
nbp:
|
||||
baseurl: "http://api.nbp.pl"
|
||||
currency:
|
||||
initial: PLN
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
|
@ -14,6 +16,9 @@ spring:
|
|||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: create
|
||||
jackson:
|
||||
mapper:
|
||||
ACCEPT_CASE_INSENSITIVE_ENUMS: true
|
||||
|
||||
management:
|
||||
endpoints:
|
||||
|
|
|
@ -5,10 +5,13 @@ 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;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
@ -24,13 +27,11 @@ public class EntityCreator {
|
|||
public static String ANOTHER_PESEL = "08280959342";
|
||||
public static String NAME = "Janina";
|
||||
public static String SURNAME = "Kowalska";
|
||||
public static double PLN = 20.10;
|
||||
public static double USD_SELL = 5.18;
|
||||
public static double USD_BUY = 5.08;
|
||||
public static String PLN_SYMBOL = "PLN";
|
||||
public static String USD_SYMBOL = "USD";
|
||||
public static double BUY_RATE = 3.8804;
|
||||
public static double SELL_RATE = 3.9572;
|
||||
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 BigDecimal BUY_RATE = createScaled(3.8804, 4);
|
||||
public static BigDecimal SELL_RATE = createScaled(3.9572, 4);
|
||||
|
||||
}
|
||||
|
||||
|
@ -39,25 +40,29 @@ public class EntityCreator {
|
|||
}
|
||||
|
||||
public static User user() {
|
||||
return user(Constants.PLN, 0);
|
||||
return user(Constants.PLN, BigDecimal.ZERO);
|
||||
}
|
||||
|
||||
public static User user(double pln, double usd) {
|
||||
Map<String, Currency> currencies = new HashMap<>();
|
||||
if (pln > 0) {
|
||||
currencies.put("PLN", new Currency("PLN", pln));
|
||||
public static User user(BigDecimal pln, BigDecimal usd) {
|
||||
Map<Symbol, Currency> currencies = new HashMap<>();
|
||||
if (pln.signum() > 0) {
|
||||
currencies.put(Symbol.PLN, new Currency(Symbol.PLN, pln));
|
||||
}
|
||||
if (usd > 0) {
|
||||
currencies.put("USD", new Currency("USD", usd));
|
||||
if (usd.signum() > 0) {
|
||||
currencies.put(Symbol.USD, new Currency(Symbol.USD, usd));
|
||||
}
|
||||
return new User(Constants.NAME, Constants.SURNAME, Constants.PESEL, currencies);
|
||||
}
|
||||
|
||||
public static UserCreateRequest.UserCreateRequestBuilder userRequest() {
|
||||
return userRequest(null);
|
||||
}
|
||||
|
||||
public static UserCreateRequest.UserCreateRequestBuilder userRequest(Double initial) {
|
||||
return UserCreateRequest.builder().name(Constants.NAME)
|
||||
.surname(Constants.SURNAME)
|
||||
.pesel(Constants.PESEL)
|
||||
.pln(Constants.PLN);
|
||||
.initial(initial != null ? createScaled(initial, 2) : Constants.PLN);
|
||||
}
|
||||
|
||||
public static CurrencyExchangeRequest.CurrencyExchangeRequestBuilder exchangeRequest() {
|
||||
|
@ -68,7 +73,7 @@ public class EntityCreator {
|
|||
var rates = new Rates();
|
||||
rates.setTable("C");
|
||||
rates.setCurrency("dolar amerykański");
|
||||
rates.setCode("USD");
|
||||
rates.setCode(Symbol.USD.toString());
|
||||
var rate = new Rate();
|
||||
rate.setNo("096/C/NBP/2024");
|
||||
rate.setEffectiveDate(date);
|
||||
|
@ -83,8 +88,8 @@ public class EntityCreator {
|
|||
String name;
|
||||
String surname;
|
||||
String pesel;
|
||||
double pln = -1;
|
||||
double usd = -1;
|
||||
BigDecimal pln = BigDecimal.valueOf(-1);
|
||||
BigDecimal usd = BigDecimal.valueOf(-1);
|
||||
|
||||
public UserEntityBuilder name(String name) {
|
||||
this.name = name;
|
||||
|
@ -102,26 +107,34 @@ public class EntityCreator {
|
|||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
public UserEntity build() {
|
||||
var nonnulPesel = Optional.ofNullable(pesel).orElse(Constants.PESEL);
|
||||
List<CurrencyEntity> currencies = new ArrayList<>();
|
||||
if (pln > -1) {
|
||||
currencies.add(new CurrencyEntity(nonnulPesel, "PLN", pln));
|
||||
if (pln.signum() > -1) {
|
||||
currencies.add(new CurrencyEntity(nonnulPesel, Symbol.PLN, pln));
|
||||
}
|
||||
if (usd > -1) {
|
||||
currencies.add(new CurrencyEntity(nonnulPesel, "USD", usd));
|
||||
if (usd.signum() > -1) {
|
||||
currencies.add(new CurrencyEntity(nonnulPesel, Symbol.USD, usd));
|
||||
}
|
||||
if (currencies.isEmpty()) {
|
||||
currencies.add(new CurrencyEntity(nonnulPesel, "PLN", Constants.PLN));
|
||||
currencies.add(new CurrencyEntity(nonnulPesel, Symbol.PLN, Constants.PLN));
|
||||
}
|
||||
return new UserEntity(
|
||||
nonnulPesel,
|
||||
|
@ -133,4 +146,8 @@ public class EntityCreator {
|
|||
|
||||
}
|
||||
|
||||
private static BigDecimal createScaled(double input, int scale) {
|
||||
return BigDecimal.valueOf(input).setScale(scale, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -29,6 +29,7 @@ public abstract class RepositoryBasedTest {
|
|||
.isNotEmpty()
|
||||
.get()
|
||||
.usingRecursiveComparison()
|
||||
.ignoringCollectionOrder()
|
||||
.isEqualTo(entity);
|
||||
}
|
||||
|
||||
|
|
|
@ -2,10 +2,11 @@ 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;
|
||||
|
@ -16,6 +17,8 @@ import org.junit.jupiter.params.provider.MethodSource;
|
|||
import org.mockito.Mockito;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static eu.ztsh.wymiana.EntityCreator.Constants.*;
|
||||
|
@ -27,12 +30,14 @@ class CurrencyServiceTest extends RepositoryBasedTest {
|
|||
private final CurrencyService currencyService;
|
||||
|
||||
@Autowired
|
||||
public CurrencyServiceTest(UserRepository userRepository, InstanceValidator instanceValidator) {
|
||||
public CurrencyServiceTest(UserRepository userRepository, InstanceValidator instanceValidator,
|
||||
CurrencyProperties currencyProperties) {
|
||||
super(userRepository);
|
||||
var nbp = Mockito.mock(NbpService.class);
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
|
@ -41,12 +46,12 @@ class CurrencyServiceTest extends RepositoryBasedTest {
|
|||
var entity = EntityCreator.userEntity().build();
|
||||
userRepository.save(entity);
|
||||
var result = currencyService.exchange(EntityCreator.exchangeRequest()
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.toSell(PLN)
|
||||
.build());
|
||||
assertThat(result.currencies())
|
||||
.matches(map -> map.get(PLN_SYMBOL).amount() == 0 && map.get(USD_SYMBOL).amount() == USD_BUY);
|
||||
.matches(map -> map.get(Symbol.PLN).amount().signum() == 0 && Objects.equals(map.get(Symbol.USD).amount(), USD_BUY), "USD 5.08");
|
||||
var expected = EntityCreator.userEntity().pln(0).usd(USD_BUY).build();
|
||||
expect(expected);
|
||||
}
|
||||
|
@ -57,12 +62,12 @@ class CurrencyServiceTest extends RepositoryBasedTest {
|
|||
var entity = EntityCreator.userEntity().build();
|
||||
userRepository.save(entity);
|
||||
var result = currencyService.exchange(EntityCreator.exchangeRequest()
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.toBuy(USD_BUY)
|
||||
.build());
|
||||
assertThat(result.currencies())
|
||||
.matches(map -> map.get(PLN_SYMBOL).amount() == 0 && map.get(USD_SYMBOL).amount() == USD_BUY);
|
||||
.matches(map -> map.get(Symbol.PLN).amount().signum() == 0 && Objects.equals(map.get(Symbol.USD).amount(), USD_BUY));
|
||||
var expected = EntityCreator.userEntity().pln(0).usd(USD_BUY).build();
|
||||
expect(expected);
|
||||
}
|
||||
|
@ -73,12 +78,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(USD_SYMBOL)
|
||||
.to(PLN_SYMBOL)
|
||||
.from(Symbol.USD)
|
||||
.to(Symbol.PLN)
|
||||
.toSell(USD_SELL)
|
||||
.build());
|
||||
assertThat(result.currencies())
|
||||
.matches(map -> map.get(PLN_SYMBOL).amount() == PLN && map.get(USD_SYMBOL).amount() == 0);
|
||||
.matches(map -> Objects.equals(map.get(Symbol.PLN).amount(), PLN) && map.get(Symbol.USD).amount().signum() == 0, "PLN 20.10");
|
||||
var expected = EntityCreator.userEntity().pln(PLN).usd(0).build();
|
||||
expect(expected);
|
||||
}
|
||||
|
@ -89,12 +94,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(USD_SYMBOL)
|
||||
.to(PLN_SYMBOL)
|
||||
.from(Symbol.USD)
|
||||
.to(Symbol.PLN)
|
||||
.toBuy(PLN)
|
||||
.build());
|
||||
assertThat(result.currencies())
|
||||
.matches(map -> map.get(PLN_SYMBOL).amount() == PLN && map.get(USD_SYMBOL).amount() == 0);
|
||||
.matches(map -> Objects.equals(map.get(Symbol.PLN).amount(), PLN) && map.get(Symbol.USD).amount().signum() == 0, "PLN 20.10");
|
||||
var expected = EntityCreator.userEntity().pln(PLN).usd(0).build();
|
||||
expect(expected);
|
||||
}
|
||||
|
@ -105,8 +110,8 @@ class CurrencyServiceTest extends RepositoryBasedTest {
|
|||
var entity = EntityCreator.userEntity().build();
|
||||
userRepository.save(entity);
|
||||
var request = EntityCreator.exchangeRequest()
|
||||
.from(USD_SYMBOL)
|
||||
.to(PLN_SYMBOL)
|
||||
.from(Symbol.USD)
|
||||
.to(Symbol.PLN)
|
||||
.toBuy(PLN)
|
||||
.build();
|
||||
assertThatThrownBy(() -> currencyService.exchange(request))
|
||||
|
@ -116,17 +121,17 @@ class CurrencyServiceTest extends RepositoryBasedTest {
|
|||
@Transactional
|
||||
@Test
|
||||
void doubleExchangeTest() {
|
||||
var initialValue = 100;
|
||||
var initialValue = BigDecimal.valueOf(100);
|
||||
var entity = EntityCreator.userEntity().pln(initialValue).build();
|
||||
userRepository.save(entity);
|
||||
var result1 = currencyService.exchange(EntityCreator.exchangeRequest()
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
currencyService.exchange(EntityCreator.exchangeRequest()
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.toBuy(USD_BUY)
|
||||
.build());
|
||||
var result2 = currencyService.exchange(EntityCreator.exchangeRequest()
|
||||
.from(USD_SYMBOL)
|
||||
.to(PLN_SYMBOL)
|
||||
currencyService.exchange(EntityCreator.exchangeRequest()
|
||||
.from(Symbol.USD)
|
||||
.to(Symbol.PLN)
|
||||
.toSell(USD_BUY)
|
||||
.build());
|
||||
var resultOptional = userRepository.findById(entity.getPesel());
|
||||
|
@ -135,8 +140,8 @@ class CurrencyServiceTest extends RepositoryBasedTest {
|
|||
var resultEntity = resultOptional.get();
|
||||
assertThat(resultEntity.getCurrencies()
|
||||
.stream()
|
||||
.filter(c -> c.getSymbol().equalsIgnoreCase("PLN"))
|
||||
.findFirst()).isNotEmpty().get().matches(currencyEntity -> currencyEntity.getAmount() < initialValue);
|
||||
.filter(c -> c.getSymbol().equals(Symbol.PLN))
|
||||
.findFirst()).isNotEmpty().get().matches(currencyEntity -> currencyEntity.getAmount().compareTo(initialValue) < 0);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
|
@ -145,8 +150,8 @@ class CurrencyServiceTest extends RepositoryBasedTest {
|
|||
var entity = EntityCreator.userEntity().build();
|
||||
userRepository.save(entity);
|
||||
var request = EntityCreator.exchangeRequest()
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.toBuy(PLN)
|
||||
.build();
|
||||
assertThatThrownBy(() -> currencyService.exchange(request))
|
||||
|
@ -159,8 +164,8 @@ class CurrencyServiceTest extends RepositoryBasedTest {
|
|||
void invalidPeselTest(String pesel) {
|
||||
var entity = EntityCreator.exchangeRequest()
|
||||
.pesel(pesel)
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.toSell(USD_SELL)
|
||||
.build();
|
||||
assertThatThrownBy(() -> currencyService.exchange(entity))
|
||||
|
@ -171,8 +176,8 @@ class CurrencyServiceTest extends RepositoryBasedTest {
|
|||
@Test
|
||||
void notExistingUserTest() {
|
||||
var entity = EntityCreator.exchangeRequest()
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.toSell(USD_SELL)
|
||||
.build();
|
||||
assertThatThrownBy(() -> currencyService.exchange(entity))
|
||||
|
@ -183,7 +188,7 @@ class CurrencyServiceTest extends RepositoryBasedTest {
|
|||
@DisplayName("Empty 'from' value")
|
||||
void emptyFromTest() {
|
||||
var entity = EntityCreator.exchangeRequest()
|
||||
.to(USD_SYMBOL)
|
||||
.to(Symbol.USD)
|
||||
.toSell(USD_SELL)
|
||||
.build();
|
||||
assertThatThrownBy(() -> currencyService.exchange(entity))
|
||||
|
@ -195,7 +200,7 @@ class CurrencyServiceTest extends RepositoryBasedTest {
|
|||
@DisplayName("Empty 'to' value")
|
||||
void emptyToTest() {
|
||||
var entity = EntityCreator.exchangeRequest()
|
||||
.from(PLN_SYMBOL)
|
||||
.from(Symbol.PLN)
|
||||
.toSell(USD_SELL)
|
||||
.build();
|
||||
assertThatThrownBy(() -> currencyService.exchange(entity))
|
||||
|
|
|
@ -5,6 +5,7 @@ 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;
|
||||
|
@ -79,7 +80,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(EntityCreator.Constants.USD_SYMBOL)).isEqualTo(EntityCreator.Constants.SELL_RATE);
|
||||
assertThat(nbpService.getSellRate(Symbol.USD)).isEqualTo(EntityCreator.Constants.SELL_RATE);
|
||||
} finally {
|
||||
WireMockExtension.verifyGet(1, url);
|
||||
}
|
||||
|
@ -92,9 +93,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(EntityCreator.Constants.USD_SYMBOL)).isEqualTo(EntityCreator.Constants.SELL_RATE);
|
||||
assertThat(nbpService.getSellRate(Symbol.USD)).isEqualTo(EntityCreator.Constants.SELL_RATE);
|
||||
// get from cache
|
||||
assertThat(nbpService.getBuyRate(EntityCreator.Constants.USD_SYMBOL)).isEqualTo(EntityCreator.Constants.BUY_RATE);
|
||||
assertThat(nbpService.getBuyRate(Symbol.USD)).isEqualTo(EntityCreator.Constants.BUY_RATE);
|
||||
WireMockExtension.verifyGet(1, url);
|
||||
}
|
||||
|
||||
|
@ -102,9 +103,9 @@ class NbpServiceTest {
|
|||
@Test
|
||||
void getInvalidCurrencyTest() {
|
||||
var date = dtf.format(updateClock(DayOfWeek.FRIDAY));
|
||||
var url = "/api/exchangerates/rates/c/usb/%s/".formatted(date);
|
||||
var url = "/api/exchangerates/rates/c/usd/%s/".formatted(date);
|
||||
WireMockExtension.response(url, 404, "404 NotFound - Not Found - Brak danych");
|
||||
assertThatThrownBy(() -> nbpService.getSellRate("usb")).isInstanceOf(NoDataException.class);
|
||||
assertThatThrownBy(() -> nbpService.getSellRate(Symbol.USD)).isInstanceOf(NoDataException.class);
|
||||
WireMockExtension.verifyGet(1, url);
|
||||
}
|
||||
|
||||
|
|
|
@ -2,6 +2,7 @@ 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;
|
||||
|
@ -21,9 +22,10 @@ class UserServiceTest extends RepositoryBasedTest {
|
|||
private final UserService userService;
|
||||
|
||||
@Autowired
|
||||
public UserServiceTest(UserRepository userRepository, InstanceValidator instanceValidator) {
|
||||
public UserServiceTest(UserRepository userRepository, InstanceValidator instanceValidator,
|
||||
CurrencyProperties currencyProperties) {
|
||||
super(userRepository);
|
||||
userService = new UserService(userRepository, instanceValidator);
|
||||
userService = new UserService(userRepository, instanceValidator, currencyProperties);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -50,10 +52,9 @@ class UserServiceTest extends RepositoryBasedTest {
|
|||
@DisplayName("Try to create another user with same PESEL")
|
||||
void createDuplicatedPeselTest() {
|
||||
var first = EntityCreator.userRequest().build();
|
||||
var second = EntityCreator.userRequest()
|
||||
var second = EntityCreator.userRequest(30.30)
|
||||
.name("Jan")
|
||||
.surname("Kowalski")
|
||||
.pln(30.30)
|
||||
.build();
|
||||
userService.create(first);
|
||||
assertThatThrownBy(() -> userService.create(second))
|
||||
|
|
|
@ -1,12 +1,10 @@
|
|||
package eu.ztsh.wymiana.util;
|
||||
|
||||
import eu.ztsh.wymiana.EntityCreator;
|
||||
import eu.ztsh.wymiana.model.Currency;
|
||||
import eu.ztsh.wymiana.model.User;
|
||||
import eu.ztsh.wymiana.model.Symbol;
|
||||
import eu.ztsh.wymiana.model.UserCreateRequestConfiguredWrapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class UserMapperTest {
|
||||
|
@ -31,7 +29,9 @@ class UserMapperTest {
|
|||
|
||||
@Test
|
||||
void requestToEntityTest() {
|
||||
var request = EntityCreator.userRequest().build();
|
||||
var request = UserCreateRequestConfiguredWrapper.wrap(EntityCreator.userRequest().build())
|
||||
.withInitial(Symbol.PLN)
|
||||
.build() ;
|
||||
var expected = EntityCreator.userEntity().build();
|
||||
assertThat(UserMapper.requestToEntity(request))
|
||||
.usingRecursiveComparison()
|
||||
|
|
|
@ -1,14 +1,15 @@
|
|||
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 static eu.ztsh.wymiana.EntityCreator.Constants.PLN_SYMBOL;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
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> {
|
||||
|
||||
|
@ -20,8 +21,8 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
|
|||
@DisplayName("Valid request with buy value specified")
|
||||
void validRequestWithBuyTest() {
|
||||
assertThatValidation(EntityCreator.exchangeRequest()
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.toBuy(USD_BUY)
|
||||
.build()).isTrue();
|
||||
}
|
||||
|
@ -30,8 +31,8 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
|
|||
@DisplayName("Valid request with sell value specified")
|
||||
void validRequestWithSellTest() {
|
||||
assertThatValidation(EntityCreator.exchangeRequest()
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.toSell(USD_SELL)
|
||||
.build()).isTrue();
|
||||
}
|
||||
|
@ -40,8 +41,8 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
|
|||
@DisplayName("From and To have same value")
|
||||
void sameFromToTest() {
|
||||
assertThatValidation(EntityCreator.exchangeRequest()
|
||||
.from(USD_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.from(Symbol.USD)
|
||||
.to(Symbol.USD)
|
||||
.toSell(USD_SELL)
|
||||
.build()).isFalse();
|
||||
}
|
||||
|
@ -50,8 +51,8 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
|
|||
@DisplayName("Empty amounts")
|
||||
void emptyBuySellTest() {
|
||||
assertThatValidation(EntityCreator.exchangeRequest()
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.build()).isFalse();
|
||||
}
|
||||
|
||||
|
@ -59,8 +60,8 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
|
|||
@DisplayName("Both Buy and Sell params filled in")
|
||||
void bothFilledBuySellTest() {
|
||||
assertThatValidation(EntityCreator.exchangeRequest()
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.toBuy(USD_BUY)
|
||||
.toSell(USD_SELL)
|
||||
.build()).isFalse();
|
||||
|
@ -70,9 +71,9 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
|
|||
@DisplayName("Negative buy amount value")
|
||||
void negativeBuyAmountTest() {
|
||||
assertThatValidation(EntityCreator.exchangeRequest()
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.toBuy(-1.0)
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.toBuy(BigDecimal.valueOf(-1.0))
|
||||
.build()).isFalse();
|
||||
}
|
||||
|
||||
|
@ -80,9 +81,9 @@ class ValidExchangeRequestValidatorTest extends ValidatorTest<ValidExchangeReque
|
|||
@DisplayName("Negative sell amount value")
|
||||
void negativeSellAmountTest() {
|
||||
assertThatValidation(EntityCreator.exchangeRequest()
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.toSell(-1.0)
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.toSell(BigDecimal.valueOf(-1.0))
|
||||
.build()).isFalse();
|
||||
}
|
||||
|
||||
|
|
|
@ -4,6 +4,7 @@ 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;
|
||||
|
@ -18,6 +19,7 @@ import org.springframework.boot.test.context.SpringBootTest;
|
|||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.web.reactive.server.WebTestClient;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
@ -80,7 +82,7 @@ class ApplicationIntegrationTests {
|
|||
void createUserTest() {
|
||||
webTestClient.post()
|
||||
.uri(endpoint)
|
||||
.bodyValue(EntityCreator.userRequest().pln(100).build())
|
||||
.bodyValue(EntityCreator.userRequest(100D).build())
|
||||
.exchange()
|
||||
.expectStatus().isNoContent();
|
||||
}
|
||||
|
@ -114,7 +116,7 @@ class ApplicationIntegrationTests {
|
|||
.uri(endpoint.concat("/").concat(PESEL))
|
||||
.exchange()
|
||||
.expectStatus().isOk()
|
||||
.expectBody().json(asJson(UserMapper.entityToPojo(EntityCreator.userEntity().pln(100).build())));
|
||||
.expectBody().json(asJson(UserMapper.pojoToResponse(UserMapper.entityToPojo(EntityCreator.userEntity().pln(100).build()))));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -152,8 +154,8 @@ class ApplicationIntegrationTests {
|
|||
webTestClient.post()
|
||||
.uri(endpoint)
|
||||
.bodyValue(EntityCreator.exchangeRequest()
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.toSell(PLN)
|
||||
.build())
|
||||
.exchange()
|
||||
|
@ -169,12 +171,12 @@ class ApplicationIntegrationTests {
|
|||
200,
|
||||
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()
|
||||
.uri(endpoint)
|
||||
.bodyValue(EntityCreator.exchangeRequest()
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.toSell(PLN)
|
||||
.build())
|
||||
.exchange()
|
||||
|
@ -190,8 +192,8 @@ class ApplicationIntegrationTests {
|
|||
.uri(endpoint)
|
||||
.bodyValue(EntityCreator.exchangeRequest()
|
||||
.pesel(ANOTHER_PESEL)
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.toSell(PLN)
|
||||
.build())
|
||||
.exchange()
|
||||
|
@ -206,8 +208,8 @@ class ApplicationIntegrationTests {
|
|||
.uri(endpoint)
|
||||
.bodyValue(EntityCreator.exchangeRequest()
|
||||
.pesel(INVALID_PESEL)
|
||||
.from(PLN_SYMBOL)
|
||||
.to(USD_SYMBOL)
|
||||
.from(Symbol.PLN)
|
||||
.to(Symbol.USD)
|
||||
.toSell(PLN)
|
||||
.build())
|
||||
.exchange()
|
||||
|
@ -220,14 +222,34 @@ class ApplicationIntegrationTests {
|
|||
webTestClient.post()
|
||||
.uri(endpoint)
|
||||
.bodyValue(EntityCreator.exchangeRequest()
|
||||
.from(USD_SYMBOL)
|
||||
.to(PLN_SYMBOL)
|
||||
.from(Symbol.USD)
|
||||
.to(Symbol.PLN)
|
||||
.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
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue