Skip to content

Conversation

@cindycho0423
Copy link
Collaborator

@cindycho0423 cindycho0423 commented Dec 9, 2024

#️⃣ 이슈

📝 작업 내용

이번 PR에서 작업한 내용을 간략히 설명해주세요.

  • 체결내역 불러오기

📸 스크린샷

✅ 체크 리스트

  • 적절한 Title 작성
  • 적절한 Label 지정
  • Assignee 및 Reviewer 지정
  • 로컬 작동 확인
  • Merge 되는 브랜치 확인

👩‍💻 공유 포인트 및 논의 사항

Summary by CodeRabbit

  • New Features

    • 거래 내역을 조회하는 기능 추가.
    • 거래 테이블에 매수 및 매도 주문을 구분하는 기능 추가.
    • 거래 내역이 없을 경우 사용자에게 피드백 제공.
  • Bug Fixes

    • 거래 함수에서 null 토큰 체크 추가로 오류 처리 개선.
  • Style

    • 컴포넌트 레이아웃 및 높이 조정.

@cindycho0423 cindycho0423 added the ✨ FEAT This doesn't seem right label Dec 9, 2024
@cindycho0423 cindycho0423 requested a review from Han-wo December 9, 2024 09:34
@cindycho0423 cindycho0423 linked an issue Dec 9, 2024 that may be closed by this pull request
1 task
@coderabbitai
Copy link

coderabbitai bot commented Dec 9, 2024

Walkthrough

이 변경 사항은 새로운 함수 getTradeHistory를 추가하여 주어진 토큰과 주식 이름에 따라 거래 내역을 검색하는 기능을 구현합니다. 이 함수는 토큰이 null인지 확인하고, null일 경우 오류를 발생시킵니다. 또한, 기존의 getTrade 함수에 대한 수정이 포함되어 있으며, 이 함수도 토큰의 null 체크를 추가하여 오류 처리를 강화했습니다. 추가적으로, 여러 컴포넌트에서 사용자 피드백을 개선하기 위한 레이아웃 조정 및 조건부 렌더링이 이루어졌습니다.

Changes

파일 경로 변경 요약
src/api/transaction/index.ts - 새로운 함수 getTradeHistory 추가 (토큰 및 주식 이름 기반 거래 내역 검색)
- getTrade 함수 수정 (토큰 null 체크 추가)
src/app/search/[id]/_components/transaction-form/edit-cancel/index.tsx - Image 컴포넌트 추가
- div 높이 변경 (h-430 -> h-400)
- limitOrderData 조건부 렌더링 개선
src/app/search/[id]/_components/transaction-form/history.tsx - useQuery 및 API 함수 getTradeHistory 추가
- 거래 내역 데이터 기반 렌더링 로직 수정
- div 높이 변경 (h-500 -> h-470)
src/app/search/[id]/_components/transaction-form/trade/index.tsx - submittedData 객체에 buyOrder 속성 추가 (거래 유형에 따라 "매수" 또는 "매도" 설정)
src/app/search/[id]/_components/transaction-form/transaction-table.tsx - TransactionTableProps 인터페이스에 buyOrder 속성 추가
- 테이블 헤더에 buyOrder 포함하여 수정

Assessment against linked issues

Objective Addressed Explanation
체결내역 불러오기 (#56)

Possibly related PRs

Suggested labels

우선순위: MEDIUM

Suggested reviewers

  • Han-wo

🐰 새로운 기능이 생겼어요,
거래 내역을 쉽게 찾아요!
오류도 잘 잡아내고,
사용자 피드백도 더 좋아졌어요!
모두 함께 거래를 즐겨요! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions
Copy link

github-actions bot commented Dec 9, 2024

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (3)
src/app/search/[id]/_components/transaction-form/edit-cancel/index.tsx (1)

137-149: 빈 상태 처리가 잘 구현되었습니다만, 이미지 경로 처리를 개선해야 합니다.

빈 상태 UI가 사용자 친화적으로 구현되었습니다. 하지만 이미지 경로가 하드코딩되어 있어 유지보수성이 떨어질 수 있습니다.

상수나 환경 변수로 이미지 경로를 관리하는 것을 고려해보세요:

-src="/images/green-wallet.png"
+src={IMAGE_PATHS.GREEN_WALLET}
src/app/search/[id]/_components/transaction-form/history.tsx (1)

20-38: 조건부 렌더링 개선 및 로딩/에러 상태 처리 필요

현재 구현은 기본적인 조건부 렌더링만 수행하고 있습니다. 로딩 상태와 에러 상태를 포함한 더 완성도 높은 사용자 경험을 제공할 수 있습니다.

 return (
   <div className="flex h-470 flex-col gap-20 overflow-auto">
+    {isLoading && <div>거래 내역을 불러오는 중입니다...</div>}
+    {error && <div>거래 내역을 불러오는데 실패했습니다. 다시 시도해 주세요.</div>}
     {tradeHistoryData && tradeHistoryData?.length > 0 ? (
       tradeHistoryData.map((history) => (
         <TransactionTable
-          key={history.OrderId}
+          key={`${history.OrderId}-${history.stockName}`}
           color="green"
           isSubmit={false}
           submittedData={{
src/api/transaction/index.ts (1)

Line range hint 1-284: API 응답 처리의 일관성 개선 필요

파일 전체적으로 API 응답 처리 방식이 일관적이지 않습니다. 일부는 text()를 사용하고 일부는 json()을 사용합니다. 또한 에러 처리 방식도 통일이 필요합니다.

다음 사항들을 고려해주세요:

  1. 응답 형식의 일관성 유지 (JSON 권장)
  2. 에러 처리 패턴 통일
  3. HTTP 상태 코드에 따른 구체적인 에러 메시지 제공
  4. 타입 안전성 강화를 위한 응답 데이터 검증 로직 추가
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c17bf70 and 8baafde.

⛔ Files ignored due to path filters (1)
  • public/images/green-wallet.png is excluded by !**/*.png
📒 Files selected for processing (5)
  • src/api/transaction/index.ts (2 hunks)
  • src/app/search/[id]/_components/transaction-form/edit-cancel/index.tsx (3 hunks)
  • src/app/search/[id]/_components/transaction-form/history.tsx (1 hunks)
  • src/app/search/[id]/_components/transaction-form/trade/index.tsx (1 hunks)
  • src/app/search/[id]/_components/transaction-form/transaction-table.tsx (3 hunks)
🔇 Additional comments (5)
src/app/search/[id]/_components/transaction-form/transaction-table.tsx (2)

13-13: 인터페이스 타입 정의가 명확합니다!

옵셔널 프로퍼티로 정의하여 하위 호환성을 잘 유지하고 있습니다.


58-58: 동적 테이블 헤더 구현이 개선되었습니다.

매수/매도 구분을 동적으로 표시하여 사용자 경험이 향상되었습니다.

Also applies to: 71-71

src/app/search/[id]/_components/transaction-form/edit-cancel/index.tsx (2)

107-107: 거래 타입 정보가 올바르게 전달됩니다.

order.type을 통해 매수/매도 구분을 명확하게 전달하고 있습니다.


124-124: 높이 변경이 레이아웃에 영향을 줄 수 있습니다.

h-430에서 h-400으로의 변경이 다른 컴포넌트나 반응형 레이아웃에 영향을 줄 수 있습니다.

✅ Verification successful

높이 변경이 제한적인 영향만을 미칩니다.

검색 결과를 보면 높이 클래스(h-4XX)는 두 곳에서만 사용되고 있습니다:

  • history.tsx에서 h-470 클래스 사용
  • edit-cancel/index.tsx에서 h-400 클래스 사용

두 컴포넌트는 서로 독립적으로 렌더링되며, 하나의 높이 변경이 다른 컴포넌트에 직접적인 영향을 주지 않습니다. 또한 overflow-scrolloverflow-auto 속성이 각각 적용되어 있어 내용이 넘칠 경우 스크롤이 생성됩니다.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: 변경된 높이가 다른 컴포넌트에 영향을 주는지 확인

# 높이 관련 스타일이 사용된 파일 검색
rg "h-4[0-9]0" --type tsx

Length of output: 55


Script:

#!/bin/bash
# Description: 높이 관련 스타일이 사용된 파일 검색 (확장자 수정)

# 모든 TypeScript/React 파일에서 높이 관련 클래스 검색
rg "h-4[0-9]0" --type ts --type tsx

# 파일 확장자로 직접 검색
rg "h-4[0-9]0" -g "*.tsx" -g "*.ts"

# 특정 파일의 전체 내용 확인
cat "src/app/search/[id]/_components/transaction-form/edit-cancel/index.tsx"

Length of output: 5256

src/app/search/[id]/_components/transaction-form/trade/index.tsx (1)

187-187: 거래 유형에 따른 조건부 처리가 명확합니다.

type 프로퍼티를 기반으로 매수/매도를 구분하는 로직이 간단하고 이해하기 쉽게 구현되었습니다.

Comment on lines +13 to +17
const { data: tradeHistoryData } = useQuery({
queryKey: ["tradeHistory"],
queryFn: () => getTradeHistory(token, stockName),
enabled: !!isAuthenticated && !!token,
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

useQuery 구현에 에러 처리와 로딩 상태 추가 필요

데이터 페칭 중 발생할 수 있는 에러 상태와 로딩 상태를 처리하지 않고 있습니다. 사용자 경험 향상을 위해 이러한 상태들을 처리하는 것이 좋습니다.

- const { data: tradeHistoryData } = useQuery({
+ const { data: tradeHistoryData, isLoading, error } = useQuery({
   queryKey: ["tradeHistory"],
   queryFn: () => getTradeHistory(token, stockName),
   enabled: !!isAuthenticated && !!token,
 });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const { data: tradeHistoryData } = useQuery({
queryKey: ["tradeHistory"],
queryFn: () => getTradeHistory(token, stockName),
enabled: !!isAuthenticated && !!token,
});
const { data: tradeHistoryData, isLoading, error } = useQuery({
queryKey: ["tradeHistory"],
queryFn: () => getTradeHistory(token, stockName),
enabled: !!isAuthenticated && !!token,
});

Comment on lines +175 to +177
if (token === null) {
throw new Error();
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

에러 메시지 구체화 필요

현재 구현된 에러 처리는 구체적인 에러 메시지를 제공하지 않아 디버깅이 어려울 수 있습니다.

 if (token === null) {
-  throw new Error();
+  throw new Error('인증 토큰이 필요합니다.');
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (token === null) {
throw new Error();
}
if (token === null) {
throw new Error('인증 토큰이 필요합니다.');
}

Comment on lines +261 to +284
// 매수/매도 체결내역
export async function getTradeHistory(
token: string | null,
stockName: string,
): Promise<OrderHistory[]> {
if (token === null) {
throw new Error();
}

const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/api/account/accounts/save/${stockName}`,
{
headers: {
Authorization: `Bearer ${token}`,
},
},
);

if (!response.ok) {
throw new Error("Failed to fetch stocks");
}

return response.json();
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

getTradeHistory 함수의 에러 처리 및 타입 안전성 개선 필요

새로 추가된 getTradeHistory 함수에서 에러 처리가 미흡하며, 타입 안전성을 개선할 수 있습니다.

 export async function getTradeHistory(
   token: string | null,
   stockName: string,
 ): Promise<OrderHistory[]> {
   if (token === null) {
-    throw new Error();
+    throw new Error('거래 내역 조회를 위한 인증 토큰이 필요합니다.');
   }
+  if (!stockName) {
+    throw new Error('종목명이 필요합니다.');
+  }

   const response = await fetch(
     `${process.env.NEXT_PUBLIC_API_URL}/api/account/accounts/save/${stockName}`,
     {
       headers: {
         Authorization: `Bearer ${token}`,
       },
     },
   );

   if (!response.ok) {
-    throw new Error("Failed to fetch stocks");
+    throw new Error(`거래 내역 조회 실패: ${response.status} ${response.statusText}`);
   }

-  return response.json();
+  const data = await response.json();
+  if (!Array.isArray(data)) {
+    throw new Error('잘못된 응답 형식입니다.');
+  }
+  return data;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// 매수/매도 체결내역
export async function getTradeHistory(
token: string | null,
stockName: string,
): Promise<OrderHistory[]> {
if (token === null) {
throw new Error();
}
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/api/account/accounts/save/${stockName}`,
{
headers: {
Authorization: `Bearer ${token}`,
},
},
);
if (!response.ok) {
throw new Error("Failed to fetch stocks");
}
return response.json();
}
// 매수/매도 체결내역
export async function getTradeHistory(
token: string | null,
stockName: string,
): Promise<OrderHistory[]> {
if (token === null) {
throw new Error('거래 내역 조회를 위한 인증 토큰이 필요합니다.');
}
if (!stockName) {
throw new Error('종목명이 필요합니다.');
}
const response = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/api/account/accounts/save/${stockName}`,
{
headers: {
Authorization: `Bearer ${token}`,
},
},
);
if (!response.ok) {
throw new Error(`거래 내역 조회 실패: ${response.status} ${response.statusText}`);
}
const data = await response.json();
if (!Array.isArray(data)) {
throw new Error('잘못된 응답 형식입니다.');
}
return data;
}

@cindycho0423 cindycho0423 merged commit 1cc896e into develop Dec 9, 2024
4 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

✨ FEAT This doesn't seem right

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: 체결내역 불러오기

2 participants