|
|
@@ -14,10 +14,8 @@ import lombok.extern.slf4j.Slf4j;
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
|
import java.math.BigDecimal;
|
|
|
-import java.util.List;
|
|
|
-import java.util.Objects;
|
|
|
-import java.util.Optional;
|
|
|
-import java.util.UUID;
|
|
|
+import java.math.RoundingMode;
|
|
|
+import java.util.*;
|
|
|
import java.util.stream.Collectors;
|
|
|
|
|
|
import static java.math.RoundingMode.HALF_UP;
|
|
|
@@ -37,15 +35,15 @@ public class PortfolioService {
|
|
|
return repository.findAll();
|
|
|
}
|
|
|
|
|
|
- public List<Portfolio> getByUser(String username) {
|
|
|
+ public List<Portfolio> getByUser(String username, String currency) {
|
|
|
List<Portfolio> portfolios = repository.findAllByUsername(username);
|
|
|
|
|
|
return portfolios.stream()
|
|
|
- .map(portfolio -> get(portfolio.getId()))
|
|
|
+ .map(portfolio -> get(portfolio.getId(), currency))
|
|
|
.toList();
|
|
|
}
|
|
|
|
|
|
- public Portfolio get(String id) {
|
|
|
+ public Portfolio get(String id, String currency) {
|
|
|
Portfolio portfolio = repository.findById(id)
|
|
|
.orElseThrow(() -> new NotFoundException("No portfolio found with id: " + id));
|
|
|
|
|
|
@@ -53,28 +51,24 @@ public class PortfolioService {
|
|
|
throw new UnauthorizedException("You do not have permission to access this portfolio");
|
|
|
}
|
|
|
|
|
|
- ExchangeRateResponse exchangeRate = exchangeService.getCurrentRate("USD");
|
|
|
+ ExchangeRateResponse exchangeRate = exchangeService.getCurrentRate(currency);
|
|
|
+ Map<String, BigDecimal> rates = exchangeRate.getConversionRates();
|
|
|
+ BigDecimal targetRate = rates.getOrDefault(currency, BigDecimal.ONE);
|
|
|
|
|
|
- BigDecimal brlRatio = exchangeRate.getConversionRates().get("BRL");
|
|
|
- BigDecimal eurRatio = exchangeRate.getConversionRates().get("EUR");
|
|
|
-
|
|
|
- log.info("Getting portfolio [{}]", id);
|
|
|
+ log.info("Getting portfolio [{}] and converting to [{}]", id, currency);
|
|
|
List<Stock> updatedStocks = portfolio.getStocks().stream()
|
|
|
.peek(stock -> {
|
|
|
Quote quote = stockService.getStockQuote(stock.getCode());
|
|
|
stock.setName(quote.getName());
|
|
|
|
|
|
- switch (quote.getCurrency()) {
|
|
|
- case "BRL":
|
|
|
- stock.setPrice(quote.getPrice().divide(brlRatio, HALF_UP));
|
|
|
- break;
|
|
|
- case "EUR":
|
|
|
- stock.setPrice(quote.getPrice().divide(eurRatio, HALF_UP));
|
|
|
- default:
|
|
|
- stock.setPrice(quote.getPrice());
|
|
|
- }
|
|
|
-
|
|
|
- stock.setTotal(stock.getPrice().multiply(new BigDecimal(stock.getQuantity())));
|
|
|
+ BigDecimal quoteRate = rates.getOrDefault(quote.getCurrency(), BigDecimal.ONE);
|
|
|
+
|
|
|
+ BigDecimal convertedPrice = quote.getPrice()
|
|
|
+ .divide(quoteRate, 2, RoundingMode.HALF_UP)
|
|
|
+ .multiply(targetRate);
|
|
|
+
|
|
|
+ stock.setPrice(convertedPrice);
|
|
|
+ stock.setTotal(convertedPrice.multiply(new BigDecimal(stock.getQuantity())));
|
|
|
}).toList();
|
|
|
|
|
|
portfolio.setStocks(updatedStocks);
|