Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[4주차] BE alpha 자동배포 #142

Merged
merged 112 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
112 commits
Select commit Hold shift + click to select a range
edb326f
✨ feat: 실시간 체결가 웹소켓 연결 코드 작성#56
uuuo3o Nov 14, 2024
b266468
🔧 fix: status pending 조건 추가 #53
sieunie Nov 15, 2024
57d1174
🔧 fix: 매도/매수 체결 시 쿼리문 수정 #53
sieunie Nov 15, 2024
139bc4a
➕ add: 사용자 보유 주식 테이블 유니크 조건 추가 #53
sieunie Nov 15, 2024
b2fb455
🔧 fix: user id 로직 수정 #53
sieunie Nov 15, 2024
e81574e
➕ add: 에러 로그 추가 #53
sieunie Nov 15, 2024
e0c8c27
➕ add: 매수시 가용 자산 체크 로직 추가 #53
sieunie Nov 15, 2024
2371d93
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
sieunie Nov 15, 2024
3b7999d
🔧 fix: 매수시 가용 자산 체크 로직 수정 #53
sieunie Nov 15, 2024
8ae299c
🔧 fix: 매수시 보유 주식 평균가 업데이트 쿼리 수정 #53
sieunie Nov 15, 2024
e454dc2
🔧 fix: 보유 주식 평균가 타입 수정 #53
sieunie Nov 15, 2024
1e6a838
Merge branch 'dev' of https://github.com/boostcampwm-2024/web16-JuGa …
uuuo3o Nov 15, 2024
d68955b
✨ feat: 실시간 체결가 웹소켓 연결 코드 작성 및 test.html 생성#56
uuuo3o Nov 15, 2024
d1b6eef
Merge pull request #122 from boostcampwm-2024/feature/api/execute-#53
sieunie Nov 15, 2024
b34356d
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
uuuo3o Nov 18, 2024
43f5c1e
🔧 fix : alpha 서버 CD/CD 워크플로우 수정
jinddings Nov 18, 2024
f8b6560
🚚 rename :alpha 서버 워크플로우 rename
jinddings Nov 18, 2024
22fe6b8
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
jinddings Nov 18, 2024
0ed0871
✨ feat: 실시간 체결가 웹소켓 연결 코드 작성 및 test.html 생성#127
uuuo3o Nov 18, 2024
5feaf13
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
uuuo3o Nov 18, 2024
e15169b
🔥 remove: 불필요한 html 파일 삭제#127
uuuo3o Nov 18, 2024
279bd4b
📝 docs: swagger에 응답 타입 수정 및 불필요한 코드 삭제
uuuo3o Nov 18, 2024
03ac949
✨ feat: 모의 도메인용 함수 추가#127
uuuo3o Nov 18, 2024
5212038
✨ feat: SSE로 실시간 데이터 전송 로직 작성#127
uuuo3o Nov 18, 2024
e6cf90a
🔧 fix: cors 연결 설정에 불필요한 주소가 포함되어있던 부분 수정#127
uuuo3o Nov 18, 2024
9a4eaf2
🔧 fix: 소켓 연결 종료 시 1분 간격으로 재연결 로직 추가 #126
sieunie Nov 18, 2024
cfe7b06
Merge branch 'dev' of https://github.com/boostcampwm-2024/web16-JuGa …
jinddings Nov 18, 2024
0f3e141
🔧 fix : alpha, production ENV 분리
jinddings Nov 18, 2024
bd58ed3
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
uuuo3o Nov 18, 2024
4df492a
♻️ refactor: requestApi 메소드 모든 서비스에서 사용하도록 변경
sieunie Nov 18, 2024
b6ec95c
♻️ refactor: 다른 서비스에서 사용되는 서비스를 domain-service로 변경
sieunie Nov 18, 2024
52152b9
♻️ refactor: stock index controller 로직 줄이고 service로 위임
sieunie Nov 18, 2024
3e85e3d
✨ feat: 주식 종목코드도 함께 반환할 수 있도록 구현
uuuo3o Nov 18, 2024
c825569
Merge pull request #129 from boostcampwm-2024/feature/socket/stockTra…
uuuo3o Nov 19, 2024
693df66
Merge pull request #131 from boostcampwm-2024/fix/socket
uuuo3o Nov 19, 2024
df57558
Merge pull request #139 from boostcampwm-2024/refactor/api/topfive
uuuo3o Nov 19, 2024
14242bc
Merge branch 'back/main' into refactor-J188
sieunie Nov 19, 2024
dab1f7b
🔧 fix: websocket 경로 수정
sieunie Nov 19, 2024
f7b9673
🔧 fix: 불필요한 try-catch문 및 logger 삭제
sieunie Nov 19, 2024
c07c5bc
♻️ refactor: 불필요한 logger 삭제
sieunie Nov 19, 2024
405e2d3
Merge pull request #134 from boostcampwm-2024/refactor-J188
sieunie Nov 19, 2024
8d60390
🔧 fix: 매도/매수 시 종목 코드 isNotEmpty 확인 추가
sieunie Nov 19, 2024
c0d2270
Merge pull request #143 from boostcampwm-2024/fix/order
sieunie Nov 19, 2024
4243005
➕ add : 랭킹 API를 위한 모듈, 컨트롤러, 서비스 클래스 파일 추가(#124)
jinddings Nov 19, 2024
49edc8f
✨ feat: 주식 주문에 사용할 상한가, 하한가 추가#144
uuuo3o Nov 19, 2024
a02a4fa
Merge pull request #147 from boostcampwm-2024/feature/api/stockDetail…
uuuo3o Nov 19, 2024
b40079d
✨ feat : rankings 테이블을 위한 Entity 작성(#124)
jinddings Nov 19, 2024
cc6665b
✨ feat: 매도 가능한 주식 개수 반환 API 구현
sieunie Nov 19, 2024
b168dfe
♻️ refactor: user-stock을 asset과 함께 관리하도록 디렉토리 구조 변경
sieunie Nov 19, 2024
597a5c5
✨ feat: 매수 가능 금액 조회 API 구현
sieunie Nov 19, 2024
c5ff175
🔧 fix: asset 보유 자산 조회 수정
sieunie Nov 19, 2024
22dd87d
🔧 fix : cookie를 이용한 accessToken validate(#4)
jinddings Nov 19, 2024
d4d977b
♻️ refactor : lint 오류 수정
jinddings Nov 19, 2024
328b163
🔧 fix : docker timezone 변경
jinddings Nov 19, 2024
650fdf2
🔧 fix : 명령어에서 sudo 제거
jinddings Nov 19, 2024
9a56a18
✨ feat: 마이페이지 조회 API 구현 #150
sieunie Nov 19, 2024
c7aa9ab
🔧 fix : credential 설정 추가
jinddings Nov 19, 2024
52dad51
✨ feat : ranking 테이블을 이용한 랭킹 요청 API 구현(#124)
jinddings Nov 19, 2024
5b0200c
🔧 fix :
jinddings Nov 19, 2024
59d0866
✨ feat : 장 마감 시간마다 ranking table 업데이트 기능
jinddings Nov 19, 2024
a290cdc
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
jinddings Nov 19, 2024
df10b0e
🔧 fix : CORS 서버 주소 변경
uuuo3o Nov 19, 2024
501b266
✨ feat :로그인 된 유저에게 자신의 순위까지 보내는 기능 추가(#124)
jinddings Nov 19, 2024
b338c10
📝 docs : api swagger 설명 추가(#124)
jinddings Nov 19, 2024
83a6faa
✨ feat : 전달된 쿼리에 따라 정렬 기준 변경
jinddings Nov 19, 2024
fb1bde2
🔧 fix: cookie domain 설정 추가
uuuo3o Nov 19, 2024
f287733
🔧 fix: cookie domain 설정 제거
uuuo3o Nov 19, 2024
8b1de0c
✨ feat: 주식 평가 가격 및 총 자산 1분마다 업데이트 로직 구현 #150
sieunie Nov 19, 2024
dbac707
🔧 fix: last_updated 추가 #150
sieunie Nov 19, 2024
ea1ef50
Merge pull request #149 from boostcampwm-2024/fix/order
sieunie Nov 20, 2024
830cbd9
🔧 fix: 마이페이지 조회 시에도 자산 업데이트하도록 수정 #150
sieunie Nov 20, 2024
48a8abf
♻️ refactor: 변수명을 확실하게 변경#160
uuuo3o Nov 20, 2024
e4d8a2b
✨ feat: socket.io로도 전송할 수 있도록 구현#160
uuuo3o Nov 20, 2024
3bebc30
✨ feat: 프로필 조회 API 추가 #150
sieunie Nov 20, 2024
bf64014
✨ feat: 페이지를 벗어날 때 구독을 취소하는 api 구현#160
uuuo3o Nov 20, 2024
0ef3369
🔧 fix: 자산 업데이트 주기 10분으로 수정 #150
sieunie Nov 20, 2024
20facee
✨ feat: 현재 주식가 정보를 전달해주는 실시간 소켓 구현#97
uuuo3o Nov 20, 2024
c95c8ad
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
sieunie Nov 20, 2024
b2f8683
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
jinddings Nov 20, 2024
8eec6d5
♻️ refactor : redisDomainservice 두번 의존성 주입 하는 것 수정(#124)
jinddings Nov 20, 2024
5b2ec0f
🔧 fix : redis에 데이터가 존재하는 경우 redis 데이터를 사용하도록
jinddings Nov 20, 2024
da35e67
🔧 fix : cron 시행 시간 수정(#124)
jinddings Nov 20, 2024
f725a17
✨ feat: 미체결된 주문 리스트 조회 API 구현 #150
sieunie Nov 20, 2024
bebf2bb
Merge pull request #159 from boostcampwm-2024/feature/api/profile-#150
sieunie Nov 20, 2024
1b2590f
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
jinddings Nov 20, 2024
a792b8d
🔧 fix : asset 테이블에 어제 자 total_asset 저장하게 수정(#124)
jinddings Nov 20, 2024
47e10dd
🔧 fix : prev_total_asset 컬럼 default 값 추가
jinddings Nov 20, 2024
a68044c
✨ feat : profitRate 일간 수익률 로 계산 하게 변경 및 ranking nickname 기반 표시(#124)
jinddings Nov 20, 2024
c743ad6
🔧 fix : mysql 사용 부분 redis로 대체(#124)
jinddings Nov 20, 2024
69efe27
♻️ refactor : lint 오류 수정
jinddings Nov 20, 2024
434c881
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
uuuo3o Nov 21, 2024
18678d7
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
uuuo3o Nov 21, 2024
69c9629
Merge pull request #157 from boostcampwm-2024/feature/api/ranking-#124
uuuo3o Nov 21, 2024
27a4548
Merge pull request #161 from boostcampwm-2024/feature/socket/stockTra…
uuuo3o Nov 21, 2024
4011437
Merge branch 'back/main' of https://github.com/boostcampwm-2024/web16…
uuuo3o Nov 21, 2024
451a741
Merge pull request #163 from boostcampwm-2024/feature/socket/stockDet…
uuuo3o Nov 21, 2024
d82280f
🔧 fix: 미체결 주문 리스트 반환값에 id 추가
sieunie Nov 21, 2024
60cde13
🔧 fix: 수익금 수익률 계산 수정 및 flag 반환하도록 수정
sieunie Nov 21, 2024
d0860e1
➕ add: 매일 6시에 미체결 주문 삭제하는 로직 추가
sieunie Nov 21, 2024
13bf33c
🔧 fix: 주식 매수/매도 API 엔드포인트 변경
sieunie Nov 21, 2024
9890a4c
🔧 fix: 미체결 주문 초기화 시간 수정
sieunie Nov 21, 2024
d3cfc84
🔧 fix : query 별로 응답이 아닌 한번의 요청에 두개의 랭킹 모두 응답하게 변경(#124)
jinddings Nov 21, 2024
ff380a6
🔥 remove : 불필요한 interface 삭제 (#124)
jinddings Nov 21, 2024
9935d66
Merge pull request #168 from boostcampwm-2024/fix/api/profile
sieunie Nov 21, 2024
a15a636
🔧 fix : userRanking 이 제대로 응답 안되는 현상 수정(#124)
jinddings Nov 21, 2024
3741990
📝 docs : swagger 불필요해진 query 요청 수정(#124)
jinddings Nov 21, 2024
e143b03
Merge pull request #169 from boostcampwm-2024/feature/api/ranking-#124
jinddings Nov 21, 2024
ccc4e4b
✨ feat : 로그인 상태 확인 API 추가(#7)
jinddings Nov 21, 2024
8850d2a
Merge pull request #170 from boostcampwm-2024/feature/api/login-#7
jinddings Nov 21, 2024
7e7188b
♻️ refactor: api 명세 추가
sieunie Nov 21, 2024
0ff18f9
♻️ refactor: api 명세 나머지 추가
sieunie Nov 21, 2024
bb1c047
Merge pull request #172 from boostcampwm-2024/refactor/api/docs
sieunie Nov 21, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@ jobs:
max-parallel: 1
matrix:
app:
[
{ name: 'be', dir: 'BE', port: 3000, container: 'juga-docker-be' },
{ name: 'fe', dir: 'FE', port: 5173, container: 'juga-docker-fe' },
]
[{ name: 'be', dir: 'BE', port: 3000, container: 'juga-docker-be' }]

steps:
- uses: actions/checkout@v4
Expand All @@ -35,11 +32,7 @@ jobs:
- name: Create .env file
run: |
touch ./${{ matrix.app.dir }}/.env
if [ "${{ matrix.app.name }}" = "be" ]; then
echo "${{ secrets.ENV }}" > ./${{matrix.app.dir}}/.env
else
echo "${{ secrets.ENV_FE }}" > ./${{matrix.app.dir}}/.env
fi
echo "${{ secrets.ENV_ALPHA }}" > ./${{matrix.app.dir}}/.env

- name: Install dependencies
working-directory: ./${{matrix.app.dir}}
Expand Down Expand Up @@ -108,12 +101,7 @@ jobs:
port: 22
script: |
docker system prune -af
if [ "${{ matrix.app.name }}" = "be" ]; then
echo "${{ secrets.ENV }}" > .env
else
echo "${{ secrets.ENV_FE }}" > .env
fi

echo "${{ secrets.ENV_ALPHA }}" > .env

docker network create juga-network || true

Expand Down
1 change: 1 addition & 0 deletions BE/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ WORKDIR /var/app
COPY package*.json ./
RUN npm install --only=production
COPY --from=builder /app/dist ./dist
RUN ln -snf /usr/share/zoneinfo/Asia/Seoul /etc/localtime

EXPOSE 3000
CMD ["node", "dist/main.js"]
6 changes: 4 additions & 2 deletions BE/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,16 @@ import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
import { StockIndexModule } from './stock/index/stock-index.module';
import { StockTopfiveModule } from './stock/topfive/stock-topfive.module';
import { KoreaInvestmentModule } from './koreaInvestment/korea-investment.module';
import { SocketModule } from './websocket/socket.module';
import { KoreaInvestmentModule } from './common/koreaInvestment/korea-investment.module';
import { SocketModule } from './common/websocket/socket.module';
import { StockOrderModule } from './stock/order/stock-order.module';
import { StockDetailModule } from './stock/detail/stock-detail.module';
import { typeOrmConfig } from './configs/typeorm.config';
import { StockListModule } from './stock/list/stock-list.module';
import { StockTradeHistoryModule } from './stock/trade/history/stock-trade-history.module';
import { RedisModule } from './common/redis/redis.module';
import { HTTPExceptionFilter } from './common/filters/http-exception.filter';
import { RankingModule } from './ranking/ranking.module';

@Module({
imports: [
Expand All @@ -33,6 +34,7 @@ import { HTTPExceptionFilter } from './common/filters/http-exception.filter';
StockListModule,
StockTradeHistoryModule,
RedisModule,
RankingModule,
],
controllers: [AppController],
providers: [
Expand Down
80 changes: 76 additions & 4 deletions BE/src/asset/asset.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,78 @@
import { Controller } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from '@nestjs/swagger';
import { Request } from 'express';
import { Cron } from '@nestjs/schedule';
import { JwtAuthGuard } from '../auth/jwt-auth-guard';
import { AssetService } from './asset.service';
import { MypageResponseDto } from './dto/mypage-response.dto';

@Controller('/api/assets')
@ApiTags('자산 API')
export class AssetController {}
@ApiTags('사용자 자산 및 보유 주식 API')
export class AssetController {
constructor(private readonly assetService: AssetService) {}

@Get('/stocks/:stockCode')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@ApiOperation({
summary: '매도 가능 주식 개수 조회 API',
description: '특정 주식 매도 시에 필요한 매도 가능한 주식 개수를 조회한다.',
})
@ApiResponse({
status: 200,
description: '매도 가능 주식 개수 조회 성공',
example: { quantity: 0 },
})
async getUserStockByCode(
@Req() request: Request,
@Param('stockCode') stockCode: string,
) {
return this.assetService.getUserStockByCode(
parseInt(request.user.userId, 10),
stockCode,
);
}

@Get('/cash')
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@ApiOperation({
summary: '매수 가능 금액 조회 API',
description:
'특정 주식 매수 시에 필요한 매수 가능한 금액(현재 가용자산)을 조회한다.',
})
@ApiResponse({
status: 200,
description: '매수 가능 금액 조회 성공',
example: { cash_balance: 0 },
})
async getCashBalance(@Req() request: Request) {
return this.assetService.getCashBalance(parseInt(request.user.userId, 10));
}

@Get()
@ApiBearerAuth()
@UseGuards(JwtAuthGuard)
@ApiOperation({
summary: '마이페이지 보유 자산 현황 조회 API',
description: '마이페이지 조회 시 필요한 보유 자산 현황을 조회한다.',
})
@ApiResponse({
status: 200,
description: '매수 가능 금액 조회 성공',
type: MypageResponseDto,
})
async getMyPage(@Req() request: Request) {
return this.assetService.getMyPage(parseInt(request.user.userId, 10));
}

@Cron('*/10 9-16 * * 1-5')
async updateAllAssets() {
await this.assetService.updateAllAssets();
}
}
3 changes: 3 additions & 0 deletions BE/src/asset/asset.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,7 @@ export class Asset {

@Column({ nullable: true })
last_updated?: Date;

@Column({ default: INIT_ASSET })
prev_total_asset?: number;
}
9 changes: 6 additions & 3 deletions BE/src/asset/asset.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@ import { AssetController } from './asset.controller';
import { AssetService } from './asset.service';
import { AssetRepository } from './asset.repository';
import { Asset } from './asset.entity';
import { UserStock } from './user-stock.entity';
import { UserStockRepository } from './user-stock.repository';
import { StockDetailModule } from '../stock/detail/stock-detail.module';

@Module({
imports: [TypeOrmModule.forFeature([Asset])],
imports: [TypeOrmModule.forFeature([Asset, UserStock]), StockDetailModule],
controllers: [AssetController],
providers: [AssetService, AssetRepository],
exports: [AssetRepository],
providers: [AssetService, AssetRepository, UserStockRepository],
exports: [AssetRepository, UserStockRepository],
})
export class AssetModule {}
7 changes: 7 additions & 0 deletions BE/src/asset/asset.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,11 @@ export class AssetRepository extends Repository<Asset> {
constructor(@InjectDataSource() dataSource: DataSource) {
super(Asset, dataSource.createEntityManager());
}

async getAssets() {
return this.createQueryBuilder('asset')
.leftJoin('user', 'user', 'asset.user_id = user.id')
.select(['asset.* ', 'user.nickname as nickname'])
.getRawMany();
}
}
115 changes: 114 additions & 1 deletion BE/src/asset/asset.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,117 @@
import { Injectable } from '@nestjs/common';
import { UserStockRepository } from './user-stock.repository';
import { AssetRepository } from './asset.repository';
import { MypageResponseDto } from './dto/mypage-response.dto';
import { StockElementResponseDto } from './dto/stock-element-response.dto';
import { AssetResponseDto } from './dto/asset-response.dto';
import { StockDetailService } from '../stock/detail/stock-detail.service';
import { UserStock } from './user-stock.entity';
import { Asset } from './asset.entity';

@Injectable()
export class AssetService {}
export class AssetService {
constructor(
private readonly userStockRepository: UserStockRepository,
private readonly assetRepository: AssetRepository,
private readonly stockDetailService: StockDetailService,
) {}

async getUserStockByCode(userId: number, stockCode: string) {
const userStock = await this.userStockRepository.findOneBy({
user_id: userId,
stock_code: stockCode,
});

return { quantity: userStock ? userStock.quantity : 0 };
}

async getCashBalance(userId: number) {
const asset = await this.assetRepository.findOneBy({ user_id: userId });

return { cash_balance: asset.cash_balance };
}

async getMyPage(userId: number) {
const userStocks =
await this.userStockRepository.findUserStockWithNameByUserId(userId);
const asset = await this.assetRepository.findOneBy({ user_id: userId });
const newAsset = await this.updateMyAsset(
asset,
await this.getCurrPrices(),
);

const myStocks = userStocks.map((userStock) => {
return new StockElementResponseDto(
userStock.stocks_name,
userStock.stocks_code,
userStock.user_stocks_quantity,
userStock.user_stocks_avg_price,
);
});

const myAsset = new AssetResponseDto(
newAsset.cash_balance,
newAsset.stock_balance,
newAsset.total_asset,
newAsset.total_profit,
newAsset.total_profit_rate,
newAsset.total_profit_rate >= 0,
);

const response = new MypageResponseDto();
response.asset = myAsset;
response.stocks = myStocks;

return response;
}

async updateAllAssets() {
const currPrices = await this.getCurrPrices();
const assets = await this.assetRepository.find();

await Promise.allSettled(
assets.map((asset) => this.updateMyAsset(asset, currPrices)),
);
}

private async updateMyAsset(asset: Asset, currPrices) {
const userId = asset.user_id;
const userStocks = await this.userStockRepository.find({
where: { user_id: userId },
});

const totalPrice = userStocks.reduce(
(sum, userStock) =>
sum + userStock.quantity * currPrices[userStock.stock_code],
0,
);

const updatedAsset = {
...asset,
stock_balance: totalPrice,
total_asset: asset.cash_balance + totalPrice,
total_profit: asset.cash_balance + totalPrice - 10000000,
total_profit_rate: (asset.cash_balance + totalPrice - 10000000) / 100000,
last_updated: new Date(),
prev_total_asset: asset.total_asset,
};
return this.assetRepository.save(updatedAsset);
}

private async getCurrPrices() {
const userStocks: UserStock[] =
await this.userStockRepository.findAllDistinctCode();
const currPrices = {};

await Promise.allSettled(
userStocks.map(async (userStock) => {
const inquirePrice = await this.stockDetailService.getInquirePrice(
userStock.stock_code,
);
currPrices[userStock.stock_code] = Number(inquirePrice.stck_prpr);
}),
);

return currPrices;
}
}
37 changes: 37 additions & 0 deletions BE/src/asset/dto/asset-response.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { ApiProperty } from '@nestjs/swagger';

export class AssetResponseDto {
constructor(
cash_balance,
stock_balance,
total_asset,
total_profit,
total_profit_rate,
is_positive,
) {
this.cash_balance = cash_balance;
this.stock_balance = stock_balance;
this.total_asset = total_asset;
this.total_profit = total_profit;
this.total_profit_rate = total_profit_rate;
this.is_positive = is_positive;
}

@ApiProperty({ description: '보유 현금' })
cash_balance: number;

@ApiProperty({ description: '주식 평가 금액' })
stock_balance: number;

@ApiProperty({ description: '총 자산' })
total_asset: number;

@ApiProperty({ description: '총 수익금' })
total_profit: number;

@ApiProperty({ description: '총 수익률' })
total_profit_rate: number;

@ApiProperty({ description: '수익률 부호' })
is_positive: boolean;
}
17 changes: 17 additions & 0 deletions BE/src/asset/dto/mypage-response.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { ApiProperty } from '@nestjs/swagger';
import { StockElementResponseDto } from './stock-element-response.dto';
import { AssetResponseDto } from './asset-response.dto';

export class MypageResponseDto {
@ApiProperty({
description: '보유 자산',
type: AssetResponseDto,
})
asset: AssetResponseDto;

@ApiProperty({
description: '보유 주식 리스트',
type: [StockElementResponseDto],
})
stocks: StockElementResponseDto[];
}
22 changes: 22 additions & 0 deletions BE/src/asset/dto/stock-element-response.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ApiProperty } from '@nestjs/swagger';

export class StockElementResponseDto {
constructor(name, code, quantity, avg_price) {
this.name = name;
this.code = code;
this.quantity = quantity;
this.avg_price = avg_price;
}

@ApiProperty({ description: '종목 이름' })
name: string;

@ApiProperty({ description: '종목 코드' })
code: string;

@ApiProperty({ description: '보유량' })
quantity: number;

@ApiProperty({ description: '평균 매수가' })
avg_price: number;
}
Loading
Loading