|
|
@@ -0,0 +1,80 @@
|
|
|
+package com.danielbohry.stocks.controller;
|
|
|
+
|
|
|
+import com.danielbohry.stocks.domain.Quote;
|
|
|
+import com.danielbohry.stocks.service.StockService;
|
|
|
+import lombok.AllArgsConstructor;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.http.ResponseEntity;
|
|
|
+import org.springframework.web.bind.annotation.*;
|
|
|
+import org.springframework.web.multipart.MultipartFile;
|
|
|
+
|
|
|
+import java.io.BufferedReader;
|
|
|
+import java.io.InputStreamReader;
|
|
|
+import java.math.BigDecimal;
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Objects;
|
|
|
+
|
|
|
+import static java.time.LocalDateTime.now;
|
|
|
+
|
|
|
+@Slf4j
|
|
|
+@RestController
|
|
|
+@RequestMapping("api/stocks")
|
|
|
+@AllArgsConstructor
|
|
|
+@CrossOrigin
|
|
|
+public class StockController {
|
|
|
+
|
|
|
+ private final StockService service;
|
|
|
+
|
|
|
+ @GetMapping
|
|
|
+ public ResponseEntity<List<Quote>> getAll() {
|
|
|
+ List<Quote> response = service.get();
|
|
|
+ return ResponseEntity.ok(response);
|
|
|
+ }
|
|
|
+
|
|
|
+ @GetMapping("{code}")
|
|
|
+ public ResponseEntity<Quote> getByCode(@PathVariable String code) {
|
|
|
+ Quote response = service.get(code.toUpperCase());
|
|
|
+ return ResponseEntity.ok(response);
|
|
|
+ }
|
|
|
+
|
|
|
+ @PostMapping("/upload-csv")
|
|
|
+ public ResponseEntity<List<Quote>> uploadCsvFile(@RequestParam("file") MultipartFile file) {
|
|
|
+ if (file.isEmpty()) {
|
|
|
+ return ResponseEntity.badRequest().build();
|
|
|
+ }
|
|
|
+
|
|
|
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
|
|
|
+ List<Quote> quotes = reader.lines()
|
|
|
+ .map(this::convert)
|
|
|
+ .filter(Objects::nonNull)
|
|
|
+ .toList();
|
|
|
+
|
|
|
+ List<Quote> response = service.update(quotes);
|
|
|
+
|
|
|
+ return ResponseEntity.ok(response);
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error("Failed to import csv", e);
|
|
|
+ return ResponseEntity.status(400).build();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private Quote convert(String input) {
|
|
|
+ String[] value = input.split(",");
|
|
|
+
|
|
|
+ log.info("Importing [{}]", (Object) value);
|
|
|
+
|
|
|
+ if (value[3] != null && !value[3].equals("#N/A")) {
|
|
|
+ BigDecimal price = new BigDecimal(value[3]);
|
|
|
+ return price.compareTo(BigDecimal.ZERO) > 0
|
|
|
+ ? new Quote(value[0], value[1], price, now())
|
|
|
+ : null;
|
|
|
+ } else if (value[0] != null && Objects.equals(value[3], "#N/A")) {
|
|
|
+ return null;
|
|
|
+ } else {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+}
|