Browse Source

add currency as param and fix convertion bug

Daniel Bohry 8 months ago
parent
commit
734a5d01b9

+ 5 - 4
src/main/java/com/danielbohry/stocks/api/portfolio/PortfolioController.java

@@ -22,14 +22,15 @@ public class PortfolioController {
     private final PortfolioService service;
 
     @GetMapping
-    public ResponseEntity<?> current() {
-        List<Portfolio> response = service.getByUser(UserContextHolder.get().getUsername());
+    public ResponseEntity<?> current(@RequestParam(required = false, defaultValue = "usd") String currency) {
+        List<Portfolio> response = service.getByUser(UserContextHolder.get().getUsername(), currency.toUpperCase());
         return ResponseEntity.ok(response);
     }
 
     @GetMapping("{id}")
-    public ResponseEntity<Portfolio> get(@PathVariable String id) {
-        Portfolio response = service.get(id);
+    public ResponseEntity<Portfolio> get(@PathVariable String id,
+                                         @RequestParam(required = false, defaultValue = "usd") String currency) {
+        Portfolio response = service.get(id, currency.toUpperCase());
         return ResponseEntity.ok(response);
     }
 

+ 17 - 23
src/main/java/com/danielbohry/stocks/service/PortfolioService.java

@@ -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);

+ 1 - 1
src/test/java/service/PortfolioServiceTest.java

@@ -66,7 +66,7 @@ public class PortfolioServiceTest {
         Portfolio portfolio = portfolioService.create();
 
         //when
-        Portfolio result = portfolioService.get(portfolio.getId());
+        Portfolio result = portfolioService.get(portfolio.getId(), "USD");
 
         //then
         assertNotNull(result.getId());