Skip to content

Commit

Permalink
feat: 주식 가격은 몽고디비를 통해 가져오기
Browse files Browse the repository at this point in the history
  • Loading branch information
shinseongsu committed Dec 3, 2023
1 parent ef6cdb8 commit 714aebb
Show file tree
Hide file tree
Showing 16 changed files with 186 additions and 37 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.flab.investing.stock.application;

import com.flab.investing.global.error.exception.NotFoundStockException;
import com.flab.investing.stock.domain.entity.StockIntraday;
import com.flab.investing.stock.repository.StockIntradayRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class StockIntraDayService {

private final StockIntradayRepository stockIntradayRepository;

public StockIntraday findByStockId(final Long stockId) {
return stockIntradayRepository.findTopByStockIdOrderByCreatedAtDesc(stockId)
.orElseThrow(NotFoundStockException::new);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,31 @@

import com.flab.investing.global.error.exception.NotFoundStockException;
import com.flab.investing.stock.domain.entity.Stock;
import com.flab.investing.stock.domain.entity.StockIntraday;
import com.flab.investing.stock.repository.StockIntradayRepository;
import com.flab.investing.stock.repository.StockRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class StockService {

private final StockRepository stockRepository;

@Transactional(readOnly = true)
public List<Stock> findAllPageable(final Pageable pageable) {
return stockRepository.findAll(pageable).getContent();
}

public Stock findByStockId(final Long stockId) {
return stockRepository.findById(stockId)
.orElseThrow(() -> new NotFoundStockException());
.orElseThrow(NotFoundStockException::new);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public void purchaseSend(UserResponse userResponse, StockPurchaseRequest request
UUID.randomUUID().toString(),
tradeId,
request.stockId(),
userResponse.userId(),
userResponse.id(),
request.stockOfAmount(),
request.stockCount(),
TradeCode.BUY
Expand All @@ -38,7 +38,7 @@ public void sellSend(UserResponse userResponse, StockSellRequest request, Long t
UUID.randomUUID().toString(),
tradeId,
request.stockId(),
userResponse.userId(),
userResponse.id(),
request.stockOfAmount(),
request.stockCount(),
TradeCode.SELL
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.flab.investing.stock.application;

import com.flab.investing.stock.dao.UserTokenDao;
import com.flab.investing.stock.infrastructure.UserServiceClient;
import com.flab.investing.stock.infrastructure.request.UserRequest;
import com.flab.investing.stock.infrastructure.response.UserResponse;
import lombok.RequiredArgsConstructor;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package com.flab.investing.stock.controller;

import com.flab.investing.global.error.exception.InvalidJwtException;
import com.flab.investing.stock.application.StockService;
import com.flab.investing.stock.application.TradeMessageService;
import com.flab.investing.stock.application.TradeService;
import com.flab.investing.stock.application.UserService;
import com.flab.investing.stock.application.*;
import com.flab.investing.stock.application.dto.TradeData;
import com.flab.investing.stock.common.DivisionStatus;
import com.flab.investing.stock.controller.request.StockPurchaseRequest;
import com.flab.investing.stock.controller.request.StockSellRequest;
import com.flab.investing.stock.controller.response.*;
import com.flab.investing.stock.controller.response.StockInfoResponse;
import com.flab.investing.stock.controller.response.StockListInfo;
import com.flab.investing.stock.controller.response.StockPurchaseResponse;
import com.flab.investing.stock.controller.response.StocksResponse;
import com.flab.investing.stock.domain.entity.Stock;
import com.flab.investing.stock.domain.entity.StockIntraday;
import com.flab.investing.stock.infrastructure.response.UserResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
Expand All @@ -19,24 +20,30 @@
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.flab.investing.stock.controller.response.ResponseCode.SUCCESS;

@RestController
@RequestMapping("/stocks")
@RequiredArgsConstructor
@RequestMapping("/stocks")
public class StockController {

private final StockService stockService;
private final UserService userService;
private final TradeService tradeService;
private final StockIntraDayService stockIntraDayService;
private final TradeMessageService tradeMessageService;

@GetMapping
public ResponseEntity<StockListInfo> stockList(@PageableDefault(size = 7) Pageable pageable) {
List<StocksResponse> stocksResponses = stockService.findAllPageable(pageable).stream()
.map(stock -> new StocksResponse(stock.getId(), stock.getCode(), stock.getName(), stock.getPrice()))
.map(stock -> new StocksResponse(
stock.getId(),
stock.getCode(),
stock.getName(),
Integer.parseInt(stockIntraDayService.findByStockId(stock.getId()).getAmount())))
.collect(Collectors.toList());

return ResponseEntity.ok(new StockListInfo(
Expand All @@ -49,6 +56,7 @@ public ResponseEntity<StockListInfo> stockList(@PageableDefault(size = 7) Pageab
@GetMapping("/{stockId}")
public ResponseEntity<StockInfoResponse> stockInfo(@PathVariable Long stockId) {
Stock stock = stockService.findByStockId(stockId);
StockIntraday stockIntraday = stockIntraDayService.findByStockId(stockId);

return ResponseEntity.ok(new StockInfoResponse(
SUCCESS.getCode(),
Expand All @@ -57,25 +65,25 @@ public ResponseEntity<StockInfoResponse> stockInfo(@PathVariable Long stockId) {
stock.getName(),
stock.getCorporationCode(),
stock.getStatus(),
stock.getPrice(),
stock.getStockHigh(),
stock.getStockLower(),
stock.getHighLimit(),
stock.getLowerLimit()
Integer.parseInt(stockIntraday.getAmount()),
Integer.parseInt(Objects.toString(stock.getStockHigh(), stockIntraday.getAmount())),
Integer.parseInt(Objects.toString(stock.getStockLower(), stockIntraday.getAmount())),
Integer.parseInt(stockIntraday.getHighLimit()),
Integer.parseInt(stockIntraday.getLowerLimit())
));
}

@PostMapping("/purchases")
public ResponseEntity<StockPurchaseResponse> purchase(@RequestHeader String accessToken,
@RequestBody StockPurchaseRequest request) {
final UserResponse userResponse = userService.tokenSend(accessToken);
if(!SUCCESS.getCode().equals(userResponse.code())) {
if (!SUCCESS.getCode().equals(userResponse.code())) {
throw new InvalidJwtException(userResponse.message());
}

Long tradeId = tradeService.saveAndGetId(new TradeData(
request.stockId(),
userResponse.userId(),
userResponse.id(),
request.stockCount(),
request.stockOfAmount(),
DivisionStatus.BUY
Expand All @@ -91,14 +99,14 @@ public ResponseEntity<StockPurchaseResponse> purchase(@RequestHeader String acce
@PostMapping("/selles")
public ResponseEntity<StockPurchaseResponse> selles(@RequestHeader String accessToken,
@RequestBody StockSellRequest request) {
final UserResponse userResponse = userService.tokenSend(accessToken);
if(!SUCCESS.getCode().equals(userResponse.code())) {
final UserResponse userResponse = userService.tokenSend(accessToken);
if (!SUCCESS.getCode().equals(userResponse.code())) {
throw new InvalidJwtException(userResponse.message());
}

Long tradeId = tradeService.saveAndGetId(new TradeData(
request.stockId(),
userResponse.userId(),
userResponse.id(),
request.stockCount(),
request.stockOfAmount(),
DivisionStatus.SELL
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
Expand All @@ -18,6 +19,7 @@

@RestController
@RequiredArgsConstructor
@RequestMapping("/stocks")
public class StockStatisticController {

private final DailyStockService dailyStockService;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class UserTokenDao {

public UserResponse tokenSend(final UserRequest request) {
log.info("user token 확인을 위한 ===> {}", request);
UserResponse userResponse = userServiceClient.tokenValidate(request);
UserResponse userResponse = userServiceClient.tokenValidate(request.accessToken());
log.info("user token 결과 =====> {} ", userResponse);
return userResponse;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.flab.investing.stock.domain.entity;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.mongodb.core.mapping.Document;

import java.time.LocalDateTime;

@Getter
@Document(collection = "stockIntraday")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class StockIntraday {

@Id
private String id;

private Long stockId;
private String date;
private String code;
private String amount;
private String status;
private String sign;
private String highLimit;
private String lowerLimit;
@CreatedDate
private LocalDateTime createdAt;
@LastModifiedDate
private LocalDateTime updatedAt;

public StockIntraday(final String id,
final Long stockId,
final String date,
final String code,
final String amount,
final String status,
final String sign,
final String highLimit,
final String lowerLimit,
final LocalDateTime createdAt,
final LocalDateTime updatedAt) {
this.id = id;
this.stockId = stockId;
this.date = date;
this.code = code;
this.amount = amount;
this.status = status;
this.sign = sign;
this.highLimit = highLimit;
this.lowerLimit = lowerLimit;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
}
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
package com.flab.investing.stock.infrastructure;

import com.flab.investing.stock.infrastructure.request.UserRequest;
import com.flab.investing.stock.infrastructure.response.UserResponse;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;

@Component
@FeignClient(name = "userService", url="${userService.url}")
@FeignClient(name = "userService", url = "${userService.url}")
public interface UserServiceClient {

@GetMapping("/users")
UserResponse tokenValidate(@RequestBody UserRequest request);
@GetMapping(value = "/users")
UserResponse tokenValidate(@RequestHeader String accessToken);

}

Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@

public record UserResponse(
String code,
Long userId,
String message,
String name
Long id,
String userEmail
) {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.flab.investing.stock.repository;

import com.flab.investing.stock.domain.entity.StockIntraday;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.Optional;

public interface StockIntradayRepository extends MongoRepository<StockIntraday, String> {

Optional<StockIntraday> findTopByStockIdOrderByCreatedAtDesc(Long stockId);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.flab.investing.stock.acceptance;

import com.flab.investing.stock.repository.StockIntradayRepository;
import com.flab.investing.util.DataCleanUp;
import io.restassured.RestAssured;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -16,8 +17,12 @@ public class AcceptanceTest {
@Autowired
private DataCleanUp dataCleanUp;

@Autowired
private StockIntradayRepository stockIntradayRepository;

public void setUp() {
RestAssured.port = port;
dataCleanUp.execute();
stockIntradayRepository.deleteAll();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import com.flab.investing.stock.acceptance.step.StockControllerStep;
import com.flab.investing.stock.domain.entity.Stock;
import com.flab.investing.stock.fixture.StockFixture;
import com.flab.investing.stock.fixture.StockIntradayFixture;
import com.flab.investing.stock.repository.StockIntradayRepository;
import com.flab.investing.stock.repository.StockRepository;
import io.restassured.response.ResponseBodyExtractionOptions;
import org.junit.jupiter.api.BeforeEach;
Expand All @@ -18,13 +20,17 @@ public class StockInfoAcceptanceTest extends AcceptanceTest{
@Autowired
private StockRepository stockRepository;

@Autowired
private StockIntradayRepository stockIntradayRepository;

private Stock samsung;

@BeforeEach
void setup() {
super.setUp();

this.samsung = stockRepository.save(StockFixture.create("삼성전자", 1000));
this.stockIntradayRepository.save(StockIntradayFixture.create(samsung.getId(), samsung.getPrice()));
}

@DisplayName("주식 정보를 조회 한다.")
Expand Down
Loading

0 comments on commit 714aebb

Please sign in to comment.