|
|
@@ -1,19 +1,68 @@
|
|
|
package com.danielbohry.stocks.service;
|
|
|
|
|
|
import com.danielbohry.stocks.client.StockClient;
|
|
|
+import com.danielbohry.stocks.domain.Quote;
|
|
|
+import com.danielbohry.stocks.repository.QuoteRepository;
|
|
|
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
|
|
+import com.fasterxml.jackson.annotation.JsonProperty;
|
|
|
import lombok.AllArgsConstructor;
|
|
|
-import org.springframework.cache.annotation.Cacheable;
|
|
|
+import lombok.Data;
|
|
|
+import lombok.NoArgsConstructor;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.beans.factory.annotation.Value;
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
|
+import java.math.BigDecimal;
|
|
|
+
|
|
|
+import static java.time.LocalDateTime.now;
|
|
|
+
|
|
|
@Service
|
|
|
-@AllArgsConstructor
|
|
|
+@Slf4j
|
|
|
public class StockService {
|
|
|
|
|
|
+ private final QuoteRepository repository;
|
|
|
private final StockClient client;
|
|
|
+ private final String key;
|
|
|
+
|
|
|
+ public StockService(QuoteRepository repository,
|
|
|
+ StockClient client,
|
|
|
+ @Value("${clients.stock.key}") String key) {
|
|
|
+ this.repository = repository;
|
|
|
+ this.client = client;
|
|
|
+ this.key = key;
|
|
|
+ }
|
|
|
+
|
|
|
+ public Quote getStockQuote(String code) {
|
|
|
+ Quote quote = repository.findByCode(code).orElse(new Quote(code, null, null));
|
|
|
+ quote.setPrice(getLastPrice(quote));
|
|
|
+ quote.setUpdatedAt(now());
|
|
|
+
|
|
|
+ repository.save(quote);
|
|
|
+
|
|
|
+ return quote;
|
|
|
+ }
|
|
|
+
|
|
|
+ private BigDecimal getLastPrice(Quote quote) {
|
|
|
+ if (quote.getPrice() == null) {
|
|
|
+ log.info("Current quote for [{}] is null. Requesting latest quote...", quote);
|
|
|
+ return new BigDecimal(client.getStockInfo(quote.getCode(), key).get(0).getLastPrice());
|
|
|
+ } else if (quote.getUpdatedAt().isBefore(now().minusDays(1))) {
|
|
|
+ log.info("Current quote for [{}] is older than 1 day. Requesting latest quote...", quote);
|
|
|
+ return new BigDecimal(client.getStockInfo(quote.getCode(), key).get(0).getLastPrice());
|
|
|
+ } else {
|
|
|
+ return quote.getPrice();
|
|
|
+ }
|
|
|
+ }
|
|
|
|
|
|
- @Cacheable("stockInfo#60")
|
|
|
- public StockClient.StockResponse getStockInfo(String code) {
|
|
|
- return client.getStockInfo("OVERVIEW", code, "GL9332G0A2RNBZBR");
|
|
|
+ @Data
|
|
|
+ @AllArgsConstructor
|
|
|
+ @NoArgsConstructor
|
|
|
+ @JsonIgnoreProperties(ignoreUnknown = true)
|
|
|
+ public static class StockResponse {
|
|
|
+ @JsonProperty("adjClose")
|
|
|
+ private String lastPrice;
|
|
|
+ @JsonProperty("adjOpen")
|
|
|
+ private String openPrice;
|
|
|
}
|
|
|
|
|
|
}
|