대시보드 추가기능 + 계좌인증
This commit is contained in:
69
app/api/kis/domestic/activity/route.ts
Normal file
69
app/api/kis/domestic/activity/route.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import type { DashboardActivityResponse } from "@/features/dashboard/types/dashboard.types";
|
||||
import { hasKisConfig, normalizeTradingEnv } from "@/lib/kis/config";
|
||||
import { getDomesticDashboardActivity } from "@/lib/kis/dashboard";
|
||||
import {
|
||||
readKisAccountParts,
|
||||
readKisCredentialsFromHeaders,
|
||||
} from "@/app/api/kis/domestic/_shared";
|
||||
|
||||
/**
|
||||
* @file app/api/kis/domestic/activity/route.ts
|
||||
* @description 국내주식 주문내역/매매일지 조회 API
|
||||
*/
|
||||
|
||||
/**
|
||||
* 대시보드 하단(주문내역/매매일지) 조회 API
|
||||
* @returns 주문내역 목록 + 매매일지 목록/요약
|
||||
* @remarks UI 흐름: DashboardContainer -> useDashboardData -> /api/kis/domestic/activity -> ActivitySection 렌더링
|
||||
* @see features/dashboard/hooks/use-dashboard-data.ts 대시보드 초기 로드/새로고침에서 호출합니다.
|
||||
* @see features/dashboard/components/ActivitySection.tsx 주문내역/매매일지 섹션 렌더링
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
const credentials = readKisCredentialsFromHeaders(request.headers);
|
||||
|
||||
if (!hasKisConfig(credentials)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "KIS API 키 설정이 필요합니다.",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const account = readKisAccountParts(request.headers);
|
||||
if (!account) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"계좌번호가 필요합니다. 설정에서 계좌번호(예: 12345678-01)를 입력해 주세요.",
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await getDomesticDashboardActivity(account, credentials);
|
||||
const response: DashboardActivityResponse = {
|
||||
source: "kis",
|
||||
tradingEnv: normalizeTradingEnv(credentials.tradingEnv),
|
||||
orders: result.orders,
|
||||
tradeJournal: result.tradeJournal,
|
||||
journalSummary: result.journalSummary,
|
||||
warnings: result.warnings,
|
||||
fetchedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
return NextResponse.json(response, {
|
||||
headers: {
|
||||
"cache-control": "no-store",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "주문내역/매매일지 조회 중 오류가 발생했습니다.";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
235
app/api/kis/validate-profile/route.ts
Normal file
235
app/api/kis/validate-profile/route.ts
Normal file
@@ -0,0 +1,235 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import type { DashboardKisProfileValidateResponse } from "@/features/trade/types/trade.types";
|
||||
import { parseKisAccountParts } from "@/lib/kis/account";
|
||||
import { kisGet } from "@/lib/kis/client";
|
||||
import { normalizeTradingEnv, type KisCredentialInput } from "@/lib/kis/config";
|
||||
import { validateKisCredentialInput } from "@/lib/kis/request";
|
||||
import { getKisAccessToken } from "@/lib/kis/token";
|
||||
|
||||
interface KisProfileValidateRequestBody {
|
||||
appKey?: string;
|
||||
appSecret?: string;
|
||||
tradingEnv?: string;
|
||||
accountNo?: string;
|
||||
}
|
||||
|
||||
interface BalanceValidationPreset {
|
||||
inqrDvsn: "01" | "02";
|
||||
prcsDvsn: "00" | "01";
|
||||
}
|
||||
|
||||
const BALANCE_VALIDATION_PRESETS: BalanceValidationPreset[] = [
|
||||
{
|
||||
// 명세 기본 요청값
|
||||
inqrDvsn: "01",
|
||||
prcsDvsn: "01",
|
||||
},
|
||||
{
|
||||
// 일부 계좌/환경 호환값
|
||||
inqrDvsn: "02",
|
||||
prcsDvsn: "00",
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* @file app/api/kis/validate-profile/route.ts
|
||||
* @description 한국투자증권 계좌번호를 검증합니다.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @description 앱키/앱시크릿키 + 계좌번호 유효성을 검증합니다.
|
||||
* @remarks UI 흐름: /settings -> KisProfileForm 확인 버튼 -> /api/kis/validate-profile -> store 반영 -> 대시보드 상태 확장
|
||||
* @see features/settings/components/KisProfileForm.tsx 계좌 확인 버튼에서 호출합니다.
|
||||
* @see features/settings/apis/kis-auth.api.ts validateKisProfile 클라이언트 API 함수
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
let body: KisProfileValidateRequestBody = {};
|
||||
|
||||
try {
|
||||
body = (await request.json()) as KisProfileValidateRequestBody;
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
tradingEnv: "mock",
|
||||
message: "요청 본문(JSON)을 읽을 수 없습니다.",
|
||||
} satisfies Pick<DashboardKisProfileValidateResponse, "ok" | "tradingEnv" | "message">,
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const credentials: KisCredentialInput = {
|
||||
appKey: body.appKey?.trim(),
|
||||
appSecret: body.appSecret?.trim(),
|
||||
tradingEnv: normalizeTradingEnv(body.tradingEnv),
|
||||
};
|
||||
|
||||
const tradingEnv = normalizeTradingEnv(credentials.tradingEnv);
|
||||
|
||||
const invalidCredentialMessage = validateKisCredentialInput(credentials);
|
||||
if (invalidCredentialMessage) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
tradingEnv,
|
||||
message: invalidCredentialMessage,
|
||||
} satisfies Pick<DashboardKisProfileValidateResponse, "ok" | "tradingEnv" | "message">,
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const accountNoInput = (body.accountNo ?? "").trim();
|
||||
|
||||
if (!accountNoInput) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
tradingEnv,
|
||||
message: "계좌번호를 입력해 주세요.",
|
||||
} satisfies Pick<DashboardKisProfileValidateResponse, "ok" | "tradingEnv" | "message">,
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const accountParts = parseKisAccountParts(accountNoInput);
|
||||
if (!accountParts) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
tradingEnv,
|
||||
message: "계좌번호 형식이 올바르지 않습니다. 8-2 형식(예: 12345678-01)으로 입력해 주세요.",
|
||||
} satisfies Pick<DashboardKisProfileValidateResponse, "ok" | "tradingEnv" | "message">,
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
// 1) 토큰 발급으로 앱키/시크릿 사전 검증
|
||||
try {
|
||||
await getKisAccessToken(credentials);
|
||||
} catch (error) {
|
||||
throw new Error(`앱키 검증 실패: ${toErrorMessage(error)}`);
|
||||
}
|
||||
|
||||
// 2) 계좌 유효성 검증 (실제 계좌 조회 API)
|
||||
try {
|
||||
await validateAccountByBalanceApi(
|
||||
accountParts.accountNo,
|
||||
accountParts.accountProductCode,
|
||||
credentials,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new Error(`계좌 검증 실패: ${toErrorMessage(error)}`);
|
||||
}
|
||||
|
||||
const normalizedAccountNo = `${accountParts.accountNo}-${accountParts.accountProductCode}`;
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
tradingEnv,
|
||||
message: "계좌번호 검증이 완료되었습니다.",
|
||||
account: {
|
||||
normalizedAccountNo,
|
||||
},
|
||||
} satisfies DashboardKisProfileValidateResponse);
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "계좌 검증 중 오류가 발생했습니다.";
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
ok: false,
|
||||
tradingEnv,
|
||||
message,
|
||||
} satisfies Pick<DashboardKisProfileValidateResponse, "ok" | "tradingEnv" | "message">,
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 계좌번호로 잔고 조회 API를 호출해 유효성을 확인합니다.
|
||||
* @param accountNo 계좌번호 앞 8자리
|
||||
* @param accountProductCode 계좌번호 뒤 2자리
|
||||
* @param credentials KIS 인증 정보
|
||||
* @see app/api/kis/validate-profile/route.ts POST
|
||||
*/
|
||||
async function validateAccountByBalanceApi(
|
||||
accountNo: string,
|
||||
accountProductCode: string,
|
||||
credentials: KisCredentialInput,
|
||||
) {
|
||||
const trId = normalizeTradingEnv(credentials.tradingEnv) === "real" ? "TTTC8434R" : "VTTC8434R";
|
||||
const attemptErrors: string[] = [];
|
||||
|
||||
for (const preset of BALANCE_VALIDATION_PRESETS) {
|
||||
try {
|
||||
const response = await kisGet<unknown>(
|
||||
"/uapi/domestic-stock/v1/trading/inquire-balance",
|
||||
trId,
|
||||
{
|
||||
CANO: accountNo,
|
||||
ACNT_PRDT_CD: accountProductCode,
|
||||
AFHR_FLPR_YN: "N",
|
||||
OFL_YN: "",
|
||||
INQR_DVSN: preset.inqrDvsn,
|
||||
UNPR_DVSN: "01",
|
||||
FUND_STTL_ICLD_YN: "N",
|
||||
FNCG_AMT_AUTO_RDPT_YN: "N",
|
||||
PRCS_DVSN: preset.prcsDvsn,
|
||||
CTX_AREA_FK100: "",
|
||||
CTX_AREA_NK100: "",
|
||||
},
|
||||
credentials,
|
||||
);
|
||||
|
||||
validateInquireBalanceResponse(response);
|
||||
return;
|
||||
} catch (error) {
|
||||
attemptErrors.push(
|
||||
`INQR_DVSN=${preset.inqrDvsn}, PRCS_DVSN=${preset.prcsDvsn}: ${toErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`계좌 확인 요청이 모두 실패했습니다. ${attemptErrors.join(" | ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 주식잔고조회 응답 구조를 최소 검증합니다.
|
||||
* @param response KIS 원본 응답
|
||||
* @see app/api/kis/validate-profile/route.ts validateAccountByBalanceApi
|
||||
*/
|
||||
function validateInquireBalanceResponse(
|
||||
response: {
|
||||
output1?: unknown;
|
||||
output2?: unknown;
|
||||
},
|
||||
) {
|
||||
const output1Ok =
|
||||
Array.isArray(response.output1) ||
|
||||
(response.output1 !== null && typeof response.output1 === "object");
|
||||
const output2Ok =
|
||||
Array.isArray(response.output2) ||
|
||||
(response.output2 !== null && typeof response.output2 === "object");
|
||||
|
||||
if (!output1Ok && !output2Ok) {
|
||||
throw new Error("응답에 output1/output2가 없습니다. 요청 파라미터를 확인해 주세요.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Error 객체를 사용자 표시용 문자열로 변환합니다.
|
||||
* @param error unknown 에러
|
||||
* @returns 메시지 문자열
|
||||
* @see app/api/kis/validate-profile/route.ts POST
|
||||
*/
|
||||
function toErrorMessage(error: unknown) {
|
||||
return error instanceof Error
|
||||
? error.message
|
||||
: "알 수 없는 오류가 발생했습니다.";
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { KisRuntimeCredentials } from "@/features/settings/store/use-kis-runtime-store";
|
||||
import type {
|
||||
DashboardActivityResponse,
|
||||
DashboardBalanceResponse,
|
||||
DashboardIndicesResponse,
|
||||
} from "@/features/dashboard/types/dashboard.types";
|
||||
@@ -65,6 +66,34 @@ export async function fetchDashboardIndices(
|
||||
return payload as DashboardIndicesResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문내역/매매일지(활동 데이터)를 조회합니다.
|
||||
* @param credentials KIS 인증 정보
|
||||
* @returns 활동 데이터 응답
|
||||
* @see app/api/kis/domestic/activity/route.ts 서버 라우트
|
||||
*/
|
||||
export async function fetchDashboardActivity(
|
||||
credentials: KisRuntimeCredentials,
|
||||
): Promise<DashboardActivityResponse> {
|
||||
const response = await fetch("/api/kis/domestic/activity", {
|
||||
method: "GET",
|
||||
headers: buildKisRequestHeaders(credentials),
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
const payload = (await response.json()) as
|
||||
| DashboardActivityResponse
|
||||
| { error?: string };
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
"error" in payload ? payload.error : "활동 데이터 조회 중 오류가 발생했습니다.",
|
||||
);
|
||||
}
|
||||
|
||||
return payload as DashboardActivityResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* 대시보드 API 공통 헤더를 구성합니다.
|
||||
* @param credentials KIS 인증 정보
|
||||
|
||||
307
features/dashboard/components/ActivitySection.tsx
Normal file
307
features/dashboard/components/ActivitySection.tsx
Normal file
@@ -0,0 +1,307 @@
|
||||
import { AlertCircle, ClipboardList, FileText } from "lucide-react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import type {
|
||||
DashboardActivityResponse,
|
||||
DashboardTradeSide,
|
||||
} from "@/features/dashboard/types/dashboard.types";
|
||||
import {
|
||||
formatCurrency,
|
||||
formatPercent,
|
||||
getChangeToneClass,
|
||||
} from "@/features/dashboard/utils/dashboard-format";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface ActivitySectionProps {
|
||||
activity: DashboardActivityResponse | null;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 대시보드 하단 주문내역/매매일지 섹션입니다.
|
||||
* @remarks UI 흐름: DashboardContainer -> ActivitySection -> tabs(주문내역/매매일지) -> 리스트 렌더링
|
||||
* @see features/dashboard/components/DashboardContainer.tsx 하단 영역에서 호출합니다.
|
||||
* @see app/api/kis/domestic/activity/route.ts 주문내역/매매일지 데이터 소스
|
||||
*/
|
||||
export function ActivitySection({ activity, isLoading, error }: ActivitySectionProps) {
|
||||
const orders = activity?.orders ?? [];
|
||||
const journalRows = activity?.tradeJournal ?? [];
|
||||
const summary = activity?.journalSummary;
|
||||
const warnings = activity?.warnings ?? [];
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
{/* ========== TITLE ========== */}
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<ClipboardList className="h-4 w-4 text-brand-600 dark:text-brand-400" />
|
||||
주문내역 · 매매일지
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
최근 주문 체결 내역과 실현손익 기록을 확인합니다.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-3">
|
||||
{isLoading && !activity && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
주문내역/매매일지를 불러오는 중입니다.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<p className="flex items-start gap-1.5 text-sm text-red-600 dark:text-red-400">
|
||||
<AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<span>{error}</span>
|
||||
</p>
|
||||
)}
|
||||
|
||||
{warnings.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{warnings.map((warning) => (
|
||||
<Badge
|
||||
key={warning}
|
||||
variant="outline"
|
||||
className="border-amber-300 bg-amber-50 text-amber-700 dark:border-amber-700 dark:bg-amber-950/30 dark:text-amber-300"
|
||||
>
|
||||
<AlertCircle className="h-3 w-3" />
|
||||
{warning}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ========== TABS ========== */}
|
||||
<Tabs defaultValue="orders" className="gap-3">
|
||||
<TabsList className="w-full justify-start">
|
||||
<TabsTrigger value="orders">주문내역 {orders.length}건</TabsTrigger>
|
||||
<TabsTrigger value="journal">매매일지 {journalRows.length}건</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="orders">
|
||||
<div className="overflow-hidden rounded-xl border border-border/70">
|
||||
<div className="grid grid-cols-[100px_1fr_140px_120px_120px_90px] gap-2 bg-muted/40 px-3 py-2 text-xs font-medium text-muted-foreground">
|
||||
<span>일시</span>
|
||||
<span>종목</span>
|
||||
<span>주문</span>
|
||||
<span>체결</span>
|
||||
<span>평균체결가</span>
|
||||
<span>상태</span>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="h-[280px]">
|
||||
{orders.length === 0 ? (
|
||||
<p className="px-3 py-4 text-sm text-muted-foreground">
|
||||
표시할 주문내역이 없습니다.
|
||||
</p>
|
||||
) : (
|
||||
<div className="divide-y divide-border/60">
|
||||
{orders.map((order) => (
|
||||
<div
|
||||
key={`${order.orderNo}-${order.orderDate}-${order.orderTime}`}
|
||||
className="grid grid-cols-[100px_1fr_140px_120px_120px_90px] items-center gap-2 px-3 py-2 text-sm"
|
||||
>
|
||||
{/* ========== ORDER DATETIME ========== */}
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<p>{order.orderDate}</p>
|
||||
<p>{order.orderTime}</p>
|
||||
</div>
|
||||
|
||||
{/* ========== STOCK INFO ========== */}
|
||||
<div>
|
||||
<p className="font-medium text-foreground">{order.name}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{order.symbol} · {getSideLabel(order.side)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* ========== ORDER INFO ========== */}
|
||||
<div className="text-xs">
|
||||
<p>수량 {order.orderQuantity.toLocaleString("ko-KR")}주</p>
|
||||
<p className="text-muted-foreground">
|
||||
{order.orderTypeName} · {formatCurrency(order.orderPrice)}원
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* ========== FILLED INFO ========== */}
|
||||
<div className="text-xs">
|
||||
<p>체결 {order.filledQuantity.toLocaleString("ko-KR")}주</p>
|
||||
<p className="text-muted-foreground">
|
||||
금액 {formatCurrency(order.filledAmount)}원
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* ========== AVG PRICE ========== */}
|
||||
<div className="text-xs font-medium text-foreground">
|
||||
{formatCurrency(order.averageFilledPrice)}원
|
||||
</div>
|
||||
|
||||
{/* ========== STATUS ========== */}
|
||||
<div>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={cn(
|
||||
"text-[11px]",
|
||||
order.isCanceled
|
||||
? "border-slate-300 text-slate-600 dark:border-slate-700 dark:text-slate-300"
|
||||
: order.remainingQuantity > 0
|
||||
? "border-amber-300 text-amber-700 dark:border-amber-700 dark:text-amber-300"
|
||||
: "border-emerald-300 text-emerald-700 dark:border-emerald-700 dark:text-emerald-300",
|
||||
)}
|
||||
>
|
||||
{order.isCanceled
|
||||
? "취소"
|
||||
: order.remainingQuantity > 0
|
||||
? "미체결"
|
||||
: "체결완료"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="journal" className="space-y-3">
|
||||
{/* ========== JOURNAL SUMMARY ========== */}
|
||||
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<SummaryMetric
|
||||
label="총 실현손익"
|
||||
value={summary ? `${formatCurrency(summary.totalRealizedProfit)}원` : "-"}
|
||||
toneClass={summary ? getChangeToneClass(summary.totalRealizedProfit) : undefined}
|
||||
/>
|
||||
<SummaryMetric
|
||||
label="총 수익률"
|
||||
value={summary ? formatPercent(summary.totalRealizedRate) : "-"}
|
||||
toneClass={summary ? getChangeToneClass(summary.totalRealizedProfit) : undefined}
|
||||
/>
|
||||
<SummaryMetric
|
||||
label="총 매수금액"
|
||||
value={summary ? `${formatCurrency(summary.totalBuyAmount)}원` : "-"}
|
||||
/>
|
||||
<SummaryMetric
|
||||
label="총 매도금액"
|
||||
value={summary ? `${formatCurrency(summary.totalSellAmount)}원` : "-"}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="overflow-hidden rounded-xl border border-border/70">
|
||||
<div className="grid grid-cols-[100px_1fr_120px_130px_120px_110px] gap-2 bg-muted/40 px-3 py-2 text-xs font-medium text-muted-foreground">
|
||||
<span>일자</span>
|
||||
<span>종목</span>
|
||||
<span>매매구분</span>
|
||||
<span>매수/매도금액</span>
|
||||
<span>실현손익(률)</span>
|
||||
<span>비용</span>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="h-[280px]">
|
||||
{journalRows.length === 0 ? (
|
||||
<p className="px-3 py-4 text-sm text-muted-foreground">
|
||||
표시할 매매일지가 없습니다.
|
||||
</p>
|
||||
) : (
|
||||
<div className="divide-y divide-border/60">
|
||||
{journalRows.map((row) => {
|
||||
const toneClass = getChangeToneClass(row.realizedProfit);
|
||||
return (
|
||||
<div
|
||||
key={`${row.tradeDate}-${row.symbol}-${row.realizedProfit}-${row.buyAmount}-${row.sellAmount}`}
|
||||
className="grid grid-cols-[100px_1fr_120px_130px_120px_110px] items-center gap-2 px-3 py-2 text-sm"
|
||||
>
|
||||
<p className="text-xs text-muted-foreground">{row.tradeDate}</p>
|
||||
<div>
|
||||
<p className="font-medium text-foreground">{row.name}</p>
|
||||
<p className="text-xs text-muted-foreground">{row.symbol}</p>
|
||||
</div>
|
||||
<p className={cn("text-xs font-medium", getSideToneClass(row.side))}>
|
||||
{getSideLabel(row.side)}
|
||||
</p>
|
||||
<p className="text-xs">
|
||||
매수 {formatCurrency(row.buyAmount)}원 / 매도 {formatCurrency(row.sellAmount)}원
|
||||
</p>
|
||||
<p className={cn("text-xs font-medium", toneClass)}>
|
||||
{formatCurrency(row.realizedProfit)}원 ({formatPercent(row.realizedRate)})
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
수수료 {formatCurrency(row.fee)}원
|
||||
<br />
|
||||
세금 {formatCurrency(row.tax)}원
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
{!isLoading && !error && !activity && (
|
||||
<p className="flex items-center gap-1.5 text-sm text-muted-foreground">
|
||||
<FileText className="h-4 w-4" />
|
||||
활동 데이터가 없습니다.
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
interface SummaryMetricProps {
|
||||
label: string;
|
||||
value: string;
|
||||
toneClass?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 매매일지 요약 지표 카드입니다.
|
||||
* @param label 지표명
|
||||
* @param value 지표값
|
||||
* @param toneClass 값 색상 클래스
|
||||
* @see features/dashboard/components/ActivitySection.tsx 매매일지 상단 요약 표시
|
||||
*/
|
||||
function SummaryMetric({ label, value, toneClass }: SummaryMetricProps) {
|
||||
return (
|
||||
<div className="rounded-xl border border-border/70 bg-background/70 p-3">
|
||||
<p className="text-xs text-muted-foreground">{label}</p>
|
||||
<p className={cn("mt-1 text-sm font-semibold text-foreground", toneClass)}>{value}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 매수/매도 라벨 텍스트를 반환합니다.
|
||||
* @param side 매수/매도 구분값
|
||||
* @returns 라벨 문자열
|
||||
* @see features/dashboard/components/ActivitySection.tsx 주문내역/매매일지 표시
|
||||
*/
|
||||
function getSideLabel(side: DashboardTradeSide) {
|
||||
if (side === "buy") return "매수";
|
||||
if (side === "sell") return "매도";
|
||||
return "기타";
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 매수/매도 라벨 색상 클래스를 반환합니다.
|
||||
* @param side 매수/매도 구분값
|
||||
* @returns Tailwind 텍스트 클래스
|
||||
* @see features/dashboard/components/ActivitySection.tsx 매매구분 표시
|
||||
*/
|
||||
function getSideToneClass(side: DashboardTradeSide) {
|
||||
if (side === "buy") return "text-red-600 dark:text-red-400";
|
||||
if (side === "sell") return "text-blue-600 dark:text-blue-400";
|
||||
return "text-muted-foreground";
|
||||
}
|
||||
@@ -18,11 +18,10 @@ export function DashboardAccessGate({ canAccess }: DashboardAccessGateProps) {
|
||||
<section className="w-full max-w-xl rounded-2xl border border-brand-200 bg-background p-6 shadow-sm dark:border-brand-800/45 dark:bg-brand-900/18">
|
||||
{/* ========== UNVERIFIED NOTICE ========== */}
|
||||
<h2 className="text-lg font-semibold text-foreground">
|
||||
대시보드를 보려면 KIS API 인증이 필요합니다.
|
||||
대시보드를 보려면 한국투자증권 연결이 필요합니다.
|
||||
</h2>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
설정 페이지에서 App Key/App Secret(그리고 계좌번호)을 입력하고 연결을
|
||||
완료해 주세요.
|
||||
설정 페이지에서 앱키, 앱시크릿키, 계좌번호를 입력하고 연결을 완료해 주세요.
|
||||
</p>
|
||||
|
||||
{/* ========== ACTION ========== */}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useMemo } from "react";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { ActivitySection } from "@/features/dashboard/components/ActivitySection";
|
||||
import { DashboardAccessGate } from "@/features/dashboard/components/DashboardAccessGate";
|
||||
import { DashboardSkeleton } from "@/features/dashboard/components/DashboardSkeleton";
|
||||
import { HoldingsList } from "@/features/dashboard/components/HoldingsList";
|
||||
@@ -22,6 +23,8 @@ export function DashboardContainer() {
|
||||
const {
|
||||
verifiedCredentials,
|
||||
isKisVerified,
|
||||
isKisProfileVerified,
|
||||
verifiedAccountNo,
|
||||
_hasHydrated,
|
||||
wsApprovalKey,
|
||||
wsUrl,
|
||||
@@ -29,6 +32,8 @@ export function DashboardContainer() {
|
||||
useShallow((state) => ({
|
||||
verifiedCredentials: state.verifiedCredentials,
|
||||
isKisVerified: state.isKisVerified,
|
||||
isKisProfileVerified: state.isKisProfileVerified,
|
||||
verifiedAccountNo: state.verifiedAccountNo,
|
||||
_hasHydrated: state._hasHydrated,
|
||||
wsApprovalKey: state.wsApprovalKey,
|
||||
wsUrl: state.wsUrl,
|
||||
@@ -38,6 +43,7 @@ export function DashboardContainer() {
|
||||
const canAccess = isKisVerified && Boolean(verifiedCredentials);
|
||||
|
||||
const {
|
||||
activity,
|
||||
balance,
|
||||
indices,
|
||||
selectedHolding,
|
||||
@@ -45,6 +51,7 @@ export function DashboardContainer() {
|
||||
setSelectedSymbol,
|
||||
isLoading,
|
||||
isRefreshing,
|
||||
activityError,
|
||||
balanceError,
|
||||
indicesError,
|
||||
lastUpdatedAt,
|
||||
@@ -80,6 +87,8 @@ export function DashboardContainer() {
|
||||
summary={balance?.summary ?? null}
|
||||
isKisRestConnected={isKisRestConnected}
|
||||
isWebSocketReady={Boolean(wsApprovalKey && wsUrl)}
|
||||
isProfileVerified={isKisProfileVerified}
|
||||
verifiedAccountNo={verifiedAccountNo}
|
||||
isRefreshing={isRefreshing}
|
||||
lastUpdatedAt={lastUpdatedAt}
|
||||
onRefresh={() => {
|
||||
@@ -110,6 +119,13 @@ export function DashboardContainer() {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ========== ACTIVITY SECTION ========== */}
|
||||
<ActivitySection
|
||||
activity={activity}
|
||||
isLoading={isLoading}
|
||||
error={activityError}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -103,12 +103,15 @@ export function HoldingsList({
|
||||
</div>
|
||||
|
||||
{/* ========== ROW BOTTOM ========== */}
|
||||
<div className="mt-2 flex items-center justify-between text-xs">
|
||||
<div className="mt-2 grid grid-cols-3 gap-1 text-xs">
|
||||
<span className="text-muted-foreground">
|
||||
평가금액 {formatCurrency(holding.evaluationAmount)}원
|
||||
평균 매수가 {formatCurrency(holding.averagePrice)}원
|
||||
</span>
|
||||
<span className={cn("font-medium", toneClass)}>
|
||||
손익 {formatCurrency(holding.profitLoss)}원
|
||||
<span className="text-muted-foreground">
|
||||
현재 평가금액 {formatCurrency(holding.evaluationAmount)}원
|
||||
</span>
|
||||
<span className={cn("text-right font-medium", toneClass)}>
|
||||
현재 손익 {formatCurrency(holding.profitLoss)}원
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
@@ -32,10 +32,10 @@ export function MarketSummary({ items, isLoading, error }: MarketSummaryProps) {
|
||||
{/* ========== TITLE ========== */}
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<BarChart3 className="h-4 w-4 text-brand-600 dark:text-brand-400" />
|
||||
시장 요약
|
||||
시장 지수
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
KOSPI/KOSDAQ 주요 지수 변동을 보여줍니다.
|
||||
코스피/코스닥 지수 움직임을 보여줍니다.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ interface StatusHeaderProps {
|
||||
summary: DashboardBalanceSummary | null;
|
||||
isKisRestConnected: boolean;
|
||||
isWebSocketReady: boolean;
|
||||
isProfileVerified: boolean;
|
||||
verifiedAccountNo: string | null;
|
||||
isRefreshing: boolean;
|
||||
lastUpdatedAt: string | null;
|
||||
onRefresh: () => void;
|
||||
@@ -27,6 +29,8 @@ export function StatusHeader({
|
||||
summary,
|
||||
isKisRestConnected,
|
||||
isWebSocketReady,
|
||||
isProfileVerified,
|
||||
verifiedAccountNo,
|
||||
isRefreshing,
|
||||
lastUpdatedAt,
|
||||
onRefresh,
|
||||
@@ -53,22 +57,31 @@ export function StatusHeader({
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
예수금 {summary ? `${formatCurrency(summary.cashBalance)}원` : "-"}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
실제 자산 {summary ? `${formatCurrency(summary.netAssetAmount)}원` : "-"}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* ========== PROFIT/LOSS ========== */}
|
||||
<div className="rounded-xl border border-border/70 bg-background/90 px-4 py-3">
|
||||
<p className="text-xs font-medium text-muted-foreground">실시간 손익</p>
|
||||
<p className="text-xs font-medium text-muted-foreground">현재 손익</p>
|
||||
<p className={cn("mt-1 text-xl font-semibold tracking-tight", toneClass)}>
|
||||
{summary ? `${formatCurrency(summary.totalProfitLoss)}원` : "-"}
|
||||
</p>
|
||||
<p className={cn("mt-1 text-xs font-medium", toneClass)}>
|
||||
{summary ? formatPercent(summary.totalProfitRate) : "-"}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
현재 평가금액 {summary ? `${formatCurrency(summary.evaluationAmount)}원` : "-"}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
총 매수금액 {summary ? `${formatCurrency(summary.purchaseAmount)}원` : "-"}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* ========== CONNECTION STATUS ========== */}
|
||||
<div className="rounded-xl border border-border/70 bg-background/90 px-4 py-3">
|
||||
<p className="text-xs font-medium text-muted-foreground">시스템 상태</p>
|
||||
<p className="text-xs font-medium text-muted-foreground">연결 상태</p>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2 text-xs font-medium">
|
||||
<span
|
||||
className={cn(
|
||||
@@ -79,7 +92,7 @@ export function StatusHeader({
|
||||
)}
|
||||
>
|
||||
<Wifi className="h-3.5 w-3.5" />
|
||||
REST {isKisRestConnected ? "연결됨" : "연결 끊김"}
|
||||
서버 {isKisRestConnected ? "연결됨" : "연결 끊김"}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
@@ -90,11 +103,28 @@ export function StatusHeader({
|
||||
)}
|
||||
>
|
||||
<Activity className="h-3.5 w-3.5" />
|
||||
WS {isWebSocketReady ? "준비됨" : "미연결"}
|
||||
실시간 시세 {isWebSocketReady ? "연결됨" : "미연결"}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
"inline-flex items-center gap-1 rounded-full px-2 py-1",
|
||||
isProfileVerified
|
||||
? "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"
|
||||
: "bg-amber-500/10 text-amber-700 dark:text-amber-400",
|
||||
)}
|
||||
>
|
||||
<Activity className="h-3.5 w-3.5" />
|
||||
계좌 인증 {isProfileVerified ? "완료" : "미완료"}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
마지막 갱신 {updatedLabel}
|
||||
마지막 업데이트 {updatedLabel}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
계좌 {maskAccountNo(verifiedAccountNo)}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
대출금 {summary ? `${formatCurrency(summary.loanAmount)}원` : "-"}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -110,7 +140,7 @@ export function StatusHeader({
|
||||
<RefreshCcw
|
||||
className={cn("h-4 w-4", isRefreshing ? "animate-spin" : "")}
|
||||
/>
|
||||
새로고침
|
||||
지금 다시 불러오기
|
||||
</Button>
|
||||
<Button
|
||||
asChild
|
||||
@@ -118,7 +148,7 @@ export function StatusHeader({
|
||||
>
|
||||
<Link href="/settings">
|
||||
<Settings2 className="h-4 w-4" />
|
||||
자동매매 설정
|
||||
연결 설정
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
@@ -126,3 +156,16 @@ export function StatusHeader({
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 계좌번호를 마스킹해 표시합니다.
|
||||
* @param value 계좌번호(8-2)
|
||||
* @returns 마스킹 문자열
|
||||
* @see features/dashboard/components/StatusHeader.tsx 시스템 상태 영역 계좌 표시
|
||||
*/
|
||||
function maskAccountNo(value: string | null) {
|
||||
if (!value) return "-";
|
||||
const digits = value.replace(/\D/g, "");
|
||||
if (digits.length !== 10) return "********";
|
||||
return "********-**";
|
||||
}
|
||||
|
||||
@@ -33,10 +33,10 @@ export function StockDetailPreview({
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<BarChartBig className="h-4 w-4 text-brand-600 dark:text-brand-400" />
|
||||
종목 상세 미리보기
|
||||
선택 종목 정보
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
보유 종목을 선택하면 상세 요약이 표시됩니다.
|
||||
보유 종목을 선택하면 자세한 정보가 표시됩니다.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
@@ -58,7 +58,7 @@ export function StockDetailPreview({
|
||||
{/* ========== TITLE ========== */}
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<BarChartBig className="h-4 w-4 text-brand-600 dark:text-brand-400" />
|
||||
종목 상세 미리보기
|
||||
선택 종목 정보
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{holding.name} ({holding.symbol}) · {holding.market}
|
||||
@@ -77,7 +77,7 @@ export function StockDetailPreview({
|
||||
valueClassName={profitToneClass}
|
||||
/>
|
||||
<Metric
|
||||
label="평가손익"
|
||||
label="현재 손익"
|
||||
value={`${formatCurrency(holding.profitLoss)}원`}
|
||||
valueClassName={profitToneClass}
|
||||
/>
|
||||
@@ -105,7 +105,7 @@ export function StockDetailPreview({
|
||||
<div className="rounded-xl border border-dashed border-border/80 bg-muted/30 p-3">
|
||||
<p className="flex items-center gap-1.5 text-sm font-medium text-foreground/80">
|
||||
<MousePointerClick className="h-4 w-4 text-brand-500" />
|
||||
간편 주문(준비 중)
|
||||
빠른 주문(준비 중)
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
향후 이 영역에서 선택 종목의 빠른 매수/매도 기능을 제공합니다.
|
||||
|
||||
@@ -3,16 +3,19 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { KisRuntimeCredentials } from "@/features/settings/store/use-kis-runtime-store";
|
||||
import {
|
||||
fetchDashboardActivity,
|
||||
fetchDashboardBalance,
|
||||
fetchDashboardIndices,
|
||||
} from "@/features/dashboard/apis/dashboard.api";
|
||||
import type {
|
||||
DashboardActivityResponse,
|
||||
DashboardBalanceResponse,
|
||||
DashboardHoldingItem,
|
||||
DashboardIndicesResponse,
|
||||
} from "@/features/dashboard/types/dashboard.types";
|
||||
|
||||
interface UseDashboardDataResult {
|
||||
activity: DashboardActivityResponse | null;
|
||||
balance: DashboardBalanceResponse | null;
|
||||
indices: DashboardIndicesResponse["items"];
|
||||
selectedHolding: DashboardHoldingItem | null;
|
||||
@@ -20,6 +23,7 @@ interface UseDashboardDataResult {
|
||||
setSelectedSymbol: (symbol: string) => void;
|
||||
isLoading: boolean;
|
||||
isRefreshing: boolean;
|
||||
activityError: string | null;
|
||||
balanceError: string | null;
|
||||
indicesError: string | null;
|
||||
lastUpdatedAt: string | null;
|
||||
@@ -39,11 +43,13 @@ const POLLING_INTERVAL_MS = 60_000;
|
||||
export function useDashboardData(
|
||||
credentials: KisRuntimeCredentials | null,
|
||||
): UseDashboardDataResult {
|
||||
const [activity, setActivity] = useState<DashboardActivityResponse | null>(null);
|
||||
const [balance, setBalance] = useState<DashboardBalanceResponse | null>(null);
|
||||
const [indices, setIndices] = useState<DashboardIndicesResponse["items"]>([]);
|
||||
const [selectedSymbol, setSelectedSymbolState] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
const [activityError, setActivityError] = useState<string | null>(null);
|
||||
const [balanceError, setBalanceError] = useState<string | null>(null);
|
||||
const [indicesError, setIndicesError] = useState<string | null>(null);
|
||||
const [lastUpdatedAt, setLastUpdatedAt] = useState<string | null>(null);
|
||||
@@ -73,14 +79,18 @@ export function useDashboardData(
|
||||
const tasks: [
|
||||
Promise<DashboardBalanceResponse | null>,
|
||||
Promise<DashboardIndicesResponse>,
|
||||
Promise<DashboardActivityResponse | null>,
|
||||
] = [
|
||||
hasAccountNo
|
||||
? fetchDashboardBalance(credentials)
|
||||
: Promise.resolve(null),
|
||||
fetchDashboardIndices(credentials),
|
||||
hasAccountNo
|
||||
? fetchDashboardActivity(credentials)
|
||||
: Promise.resolve(null),
|
||||
];
|
||||
|
||||
const [balanceResult, indicesResult] = await Promise.allSettled(tasks);
|
||||
const [balanceResult, indicesResult, activityResult] = await Promise.allSettled(tasks);
|
||||
if (requestSeq !== requestSeqRef.current) return;
|
||||
|
||||
let hasAnySuccess = false;
|
||||
@@ -90,6 +100,10 @@ export function useDashboardData(
|
||||
setBalanceError(
|
||||
"계좌번호가 없어 잔고를 조회할 수 없습니다. 설정에서 계좌번호(8-2)를 입력해 주세요.",
|
||||
);
|
||||
setActivity(null);
|
||||
setActivityError(
|
||||
"계좌번호가 없어 주문내역/매매일지를 조회할 수 없습니다. 설정에서 계좌번호(8-2)를 입력해 주세요.",
|
||||
);
|
||||
setSelectedSymbolState(null);
|
||||
} else if (balanceResult.status === "fulfilled") {
|
||||
hasAnySuccess = true;
|
||||
@@ -108,6 +122,14 @@ export function useDashboardData(
|
||||
setBalanceError(balanceResult.reason instanceof Error ? balanceResult.reason.message : "잔고 조회에 실패했습니다.");
|
||||
}
|
||||
|
||||
if (hasAccountNo && activityResult.status === "fulfilled") {
|
||||
hasAnySuccess = true;
|
||||
setActivity(activityResult.value);
|
||||
setActivityError(null);
|
||||
} else if (hasAccountNo && activityResult.status === "rejected") {
|
||||
setActivityError(activityResult.reason instanceof Error ? activityResult.reason.message : "주문내역/매매일지 조회에 실패했습니다.");
|
||||
}
|
||||
|
||||
if (indicesResult.status === "fulfilled") {
|
||||
hasAnySuccess = true;
|
||||
setIndices(indicesResult.value.items);
|
||||
@@ -167,6 +189,7 @@ export function useDashboardData(
|
||||
}, []);
|
||||
|
||||
return {
|
||||
activity,
|
||||
balance,
|
||||
indices,
|
||||
selectedHolding,
|
||||
@@ -174,6 +197,7 @@ export function useDashboardData(
|
||||
setSelectedSymbol,
|
||||
isLoading,
|
||||
isRefreshing,
|
||||
activityError,
|
||||
balanceError,
|
||||
indicesError,
|
||||
lastUpdatedAt,
|
||||
|
||||
@@ -15,6 +15,10 @@ export interface DashboardBalanceSummary {
|
||||
cashBalance: number;
|
||||
totalProfitLoss: number;
|
||||
totalProfitRate: number;
|
||||
netAssetAmount: number;
|
||||
evaluationAmount: number;
|
||||
purchaseAmount: number;
|
||||
loanAmount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -32,6 +36,61 @@ export interface DashboardHoldingItem {
|
||||
profitRate: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문/매매 공통 매수/매도 구분
|
||||
*/
|
||||
export type DashboardTradeSide = "buy" | "sell" | "unknown";
|
||||
|
||||
/**
|
||||
* 대시보드 주문내역 항목
|
||||
*/
|
||||
export interface DashboardOrderHistoryItem {
|
||||
orderDate: string;
|
||||
orderTime: string;
|
||||
orderNo: string;
|
||||
symbol: string;
|
||||
name: string;
|
||||
side: DashboardTradeSide;
|
||||
orderTypeName: string;
|
||||
orderPrice: number;
|
||||
orderQuantity: number;
|
||||
filledQuantity: number;
|
||||
filledAmount: number;
|
||||
averageFilledPrice: number;
|
||||
remainingQuantity: number;
|
||||
isCanceled: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 대시보드 매매일지 항목
|
||||
*/
|
||||
export interface DashboardTradeJournalItem {
|
||||
tradeDate: string;
|
||||
symbol: string;
|
||||
name: string;
|
||||
side: DashboardTradeSide;
|
||||
buyQuantity: number;
|
||||
buyAmount: number;
|
||||
sellQuantity: number;
|
||||
sellAmount: number;
|
||||
realizedProfit: number;
|
||||
realizedRate: number;
|
||||
fee: number;
|
||||
tax: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 대시보드 매매일지 요약
|
||||
*/
|
||||
export interface DashboardTradeJournalSummary {
|
||||
totalRealizedProfit: number;
|
||||
totalRealizedRate: number;
|
||||
totalBuyAmount: number;
|
||||
totalSellAmount: number;
|
||||
totalFee: number;
|
||||
totalTax: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 계좌 잔고 API 응답 모델
|
||||
*/
|
||||
@@ -64,3 +123,16 @@ export interface DashboardIndicesResponse {
|
||||
items: DashboardMarketIndexItem[];
|
||||
fetchedAt: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문내역/매매일지 API 응답 모델
|
||||
*/
|
||||
export interface DashboardActivityResponse {
|
||||
source: "kis";
|
||||
tradingEnv: KisTradingEnv;
|
||||
orders: DashboardOrderHistoryItem[];
|
||||
tradeJournal: DashboardTradeJournalItem[];
|
||||
journalSummary: DashboardTradeJournalSummary;
|
||||
warnings: string[];
|
||||
fetchedAt: string;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { KisRuntimeCredentials } from "@/features/settings/store/use-kis-runtime-store";
|
||||
import type {
|
||||
DashboardKisProfileValidateResponse,
|
||||
DashboardKisRevokeResponse,
|
||||
DashboardKisValidateResponse,
|
||||
DashboardKisWsApprovalResponse,
|
||||
@@ -43,7 +44,7 @@ export async function validateKisCredentials(
|
||||
return postKisAuthApi<DashboardKisValidateResponse>(
|
||||
"/api/kis/validate",
|
||||
credentials,
|
||||
"API 키 검증에 실패했습니다.",
|
||||
"앱키 검증에 실패했습니다.",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -80,3 +81,17 @@ export async function fetchKisWebSocketApproval(
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 계좌번호를 검증합니다.
|
||||
* @see app/api/kis/validate-profile/route.ts
|
||||
*/
|
||||
export async function validateKisProfile(
|
||||
credentials: KisRuntimeCredentials,
|
||||
): Promise<DashboardKisProfileValidateResponse> {
|
||||
return postKisAuthApi<DashboardKisProfileValidateResponse>(
|
||||
"/api/kis/validate-profile",
|
||||
credentials,
|
||||
"계좌 검증에 실패했습니다.",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
Lock,
|
||||
CreditCard,
|
||||
Sparkles,
|
||||
Zap,
|
||||
Activity,
|
||||
@@ -22,23 +21,22 @@ import {
|
||||
import { InlineSpinner } from "@/components/ui/loading-spinner";
|
||||
|
||||
/**
|
||||
* @description KIS 인증 입력 폼 (Minimal Redesign v4)
|
||||
* - User Feedback: "입력창이 너무 길어", "파란색/하늘색 제거해"
|
||||
* - Compact Width: max-w-lg + mx-auto
|
||||
* - Monochrome Mock Mode: Blue -> Zinc/Gray
|
||||
* @description 한국투자증권 앱키/앱시크릿키 인증 폼입니다.
|
||||
* @remarks UI 흐름: /settings -> 앱키/앱시크릿키 입력 -> 연결 확인 버튼 -> /api/kis/validate -> 연결 상태 반영
|
||||
* @see app/api/kis/validate/route.ts 앱키 검증 API
|
||||
* @see features/settings/store/use-kis-runtime-store.ts 인증 상태 저장소
|
||||
*/
|
||||
export function KisAuthForm() {
|
||||
const {
|
||||
kisTradingEnvInput,
|
||||
kisAppKeyInput,
|
||||
kisAppSecretInput,
|
||||
kisAccountNoInput,
|
||||
verifiedAccountNo,
|
||||
verifiedCredentials,
|
||||
isKisVerified,
|
||||
setKisTradingEnvInput,
|
||||
setKisAppKeyInput,
|
||||
setKisAppSecretInput,
|
||||
setKisAccountNoInput,
|
||||
setVerifiedKisSession,
|
||||
invalidateKisVerification,
|
||||
clearKisRuntimeSession,
|
||||
@@ -47,13 +45,12 @@ export function KisAuthForm() {
|
||||
kisTradingEnvInput: state.kisTradingEnvInput,
|
||||
kisAppKeyInput: state.kisAppKeyInput,
|
||||
kisAppSecretInput: state.kisAppSecretInput,
|
||||
kisAccountNoInput: state.kisAccountNoInput,
|
||||
verifiedAccountNo: state.verifiedAccountNo,
|
||||
verifiedCredentials: state.verifiedCredentials,
|
||||
isKisVerified: state.isKisVerified,
|
||||
setKisTradingEnvInput: state.setKisTradingEnvInput,
|
||||
setKisAppKeyInput: state.setKisAppKeyInput,
|
||||
setKisAppSecretInput: state.setKisAppSecretInput,
|
||||
setKisAccountNoInput: state.setKisAccountNoInput,
|
||||
setVerifiedKisSession: state.setVerifiedKisSession,
|
||||
invalidateKisVerification: state.invalidateKisVerification,
|
||||
clearKisRuntimeSession: state.clearKisRuntimeSession,
|
||||
@@ -66,9 +63,7 @@ export function KisAuthForm() {
|
||||
const [isRevoking, startRevokeTransition] = useTransition();
|
||||
|
||||
// 입력 필드 Focus 상태 관리를 위한 State
|
||||
const [focusedField, setFocusedField] = useState<
|
||||
"appKey" | "appSecret" | "accountNo" | null
|
||||
>(null);
|
||||
const [focusedField, setFocusedField] = useState<"appKey" | "appSecret" | null>(null);
|
||||
|
||||
function handleValidate() {
|
||||
startValidateTransition(async () => {
|
||||
@@ -78,23 +73,15 @@ export function KisAuthForm() {
|
||||
|
||||
const appKey = kisAppKeyInput.trim();
|
||||
const appSecret = kisAppSecretInput.trim();
|
||||
const accountNo = kisAccountNoInput.trim();
|
||||
|
||||
if (!appKey || !appSecret) {
|
||||
throw new Error("App Key와 App Secret을 모두 입력해 주세요.");
|
||||
}
|
||||
|
||||
if (accountNo && !isValidAccountNo(accountNo)) {
|
||||
throw new Error(
|
||||
"계좌번호 형식이 올바르지 않습니다. 8-2 형식(예: 12345678-01)으로 입력해 주세요.",
|
||||
);
|
||||
throw new Error("앱키와 앱시크릿키를 모두 입력해 주세요.");
|
||||
}
|
||||
|
||||
const credentials = {
|
||||
appKey,
|
||||
appSecret,
|
||||
tradingEnv: kisTradingEnvInput,
|
||||
accountNo,
|
||||
accountNo: verifiedAccountNo ?? "",
|
||||
};
|
||||
|
||||
const result = await validateKisCredentials(credentials);
|
||||
@@ -107,7 +94,7 @@ export function KisAuthForm() {
|
||||
setErrorMessage(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "API 키 검증 중 오류가 발생했습니다.",
|
||||
: "앱키 확인 중 오류가 발생했습니다.",
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -136,7 +123,7 @@ export function KisAuthForm() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="group relative mx-auto w-full max-w-lg overflow-hidden rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm transition-all hover:border-brand-200 hover:shadow-md dark:border-zinc-800 dark:bg-zinc-900/50 dark:hover:border-brand-800 dark:hover:shadow-brand-900/10">
|
||||
<div className="group relative w-full overflow-hidden rounded-2xl border border-zinc-200 bg-white p-4 shadow-sm transition-all hover:border-brand-200 hover:shadow-md dark:border-zinc-800 dark:bg-zinc-900/50 dark:hover:border-brand-800 dark:hover:shadow-brand-900/10">
|
||||
{/* Inner Content Container - Compact spacing */}
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Header Section */}
|
||||
@@ -147,16 +134,16 @@ export function KisAuthForm() {
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="flex items-center gap-2 text-base font-bold tracking-tight text-zinc-800 dark:text-zinc-100">
|
||||
KIS API Key Connection
|
||||
한국투자증권 앱키 연결
|
||||
{isKisVerified && (
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-green-50 px-1.5 py-0.5 text-[10px] font-medium text-green-600 ring-1 ring-green-600/10 dark:bg-green-500/10 dark:text-green-400 dark:ring-green-500/30">
|
||||
<CheckCircle2 className="h-3 w-3" />
|
||||
Connected
|
||||
연결됨
|
||||
</span>
|
||||
)}
|
||||
</h2>
|
||||
<p className="text-[11px] font-medium text-zinc-500 dark:text-zinc-400">
|
||||
한국투자증권에서 발급받은 API 키를 입력해 주세요.
|
||||
한국투자증권 Open API에서 발급받은 앱키/앱시크릿키를 입력해 주세요.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -206,7 +193,7 @@ export function KisAuthForm() {
|
||||
|
||||
{/* Input Fields Section (Compact Stacked Layout) */}
|
||||
<div className="flex flex-col gap-2">
|
||||
{/* App Key Input */}
|
||||
{/* ========== APP KEY INPUT ========== */}
|
||||
<div
|
||||
className={cn(
|
||||
"group/input relative flex items-center overflow-hidden rounded-lg border bg-white transition-all duration-200 dark:bg-zinc-900/30",
|
||||
@@ -219,7 +206,7 @@ export function KisAuthForm() {
|
||||
<Shield className="h-3.5 w-3.5" />
|
||||
</div>
|
||||
<div className="flex h-9 min-w-[70px] items-center justify-center bg-zinc-50 px-2 text-[11px] font-semibold text-zinc-500 border-r border-zinc-100 sm:hidden dark:bg-zinc-800/50 dark:text-zinc-500 dark:border-zinc-800">
|
||||
App Key
|
||||
앱키
|
||||
</div>
|
||||
<Input
|
||||
type="password"
|
||||
@@ -227,40 +214,13 @@ export function KisAuthForm() {
|
||||
onChange={(e) => setKisAppKeyInput(e.target.value)}
|
||||
onFocus={() => setFocusedField("appKey")}
|
||||
onBlur={() => setFocusedField(null)}
|
||||
placeholder="App Key 입력"
|
||||
placeholder="한국투자증권 앱키 입력"
|
||||
className="h-9 flex-1 border-none bg-transparent px-3 text-xs text-zinc-900 placeholder:text-zinc-400 focus-visible:ring-0 dark:text-zinc-100 dark:placeholder:text-zinc-600"
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Account No Input */}
|
||||
<div
|
||||
className={cn(
|
||||
"group/input relative flex items-center overflow-hidden rounded-lg border bg-white transition-all duration-200 dark:bg-zinc-900/30",
|
||||
focusedField === "accountNo"
|
||||
? "border-brand-500 ring-1 ring-brand-500"
|
||||
: "border-zinc-200 hover:border-zinc-300 dark:border-zinc-700 dark:hover:border-zinc-600",
|
||||
)}
|
||||
>
|
||||
<div className="hidden h-9 w-9 items-center justify-center border-r border-zinc-100 bg-zinc-50 text-zinc-400 transition-colors group-focus-within/input:text-brand-500 dark:border-zinc-800 dark:bg-zinc-800/50 dark:text-zinc-500 dark:group-focus-within/input:text-brand-400 sm:flex">
|
||||
<CreditCard className="h-3.5 w-3.5" />
|
||||
</div>
|
||||
<div className="flex h-9 min-w-[70px] items-center justify-center border-r border-zinc-100 bg-zinc-50 px-2 text-[11px] font-semibold text-zinc-500 sm:hidden dark:border-zinc-800 dark:bg-zinc-800/50 dark:text-zinc-500">
|
||||
계좌번호
|
||||
</div>
|
||||
<Input
|
||||
type="text"
|
||||
value={kisAccountNoInput}
|
||||
onChange={(e) => setKisAccountNoInput(e.target.value)}
|
||||
onFocus={() => setFocusedField("accountNo")}
|
||||
onBlur={() => setFocusedField(null)}
|
||||
placeholder="12345678-01"
|
||||
className="h-9 flex-1 border-none bg-transparent px-3 text-xs text-zinc-900 placeholder:text-zinc-400 focus-visible:ring-0 dark:text-zinc-100 dark:placeholder:text-zinc-600"
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* App Secret Input */}
|
||||
{/* ========== APP SECRET INPUT ========== */}
|
||||
<div
|
||||
className={cn(
|
||||
"group/input relative flex items-center overflow-hidden rounded-lg border bg-white transition-all duration-200 dark:bg-zinc-900/30",
|
||||
@@ -273,7 +233,7 @@ export function KisAuthForm() {
|
||||
<Lock className="h-3.5 w-3.5" />
|
||||
</div>
|
||||
<div className="flex h-9 min-w-[70px] items-center justify-center bg-zinc-50 px-2 text-[11px] font-semibold text-zinc-500 border-r border-zinc-100 sm:hidden dark:bg-zinc-800/50 dark:text-zinc-500 dark:border-zinc-800">
|
||||
Secret
|
||||
시크릿키
|
||||
</div>
|
||||
<Input
|
||||
type="password"
|
||||
@@ -281,7 +241,7 @@ export function KisAuthForm() {
|
||||
onChange={(e) => setKisAppSecretInput(e.target.value)}
|
||||
onFocus={() => setFocusedField("appSecret")}
|
||||
onBlur={() => setFocusedField(null)}
|
||||
placeholder="App Secret 입력"
|
||||
placeholder="한국투자증권 앱시크릿키 입력"
|
||||
className="h-9 flex-1 border-none bg-transparent px-3 text-xs text-zinc-900 placeholder:text-zinc-400 focus-visible:ring-0 dark:text-zinc-100 dark:placeholder:text-zinc-600"
|
||||
autoComplete="off"
|
||||
/>
|
||||
@@ -308,7 +268,7 @@ export function KisAuthForm() {
|
||||
) : (
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Sparkles className="h-3 w-3 fill-brand-200 text-brand-200" />
|
||||
API 키 연결
|
||||
앱키 연결 확인
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
@@ -351,14 +311,3 @@ export function KisAuthForm() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description KIS 계좌번호(8-2) 입력 포맷을 검증합니다.
|
||||
* @param value 사용자 입력 계좌번호
|
||||
* @returns 형식 유효 여부
|
||||
* @see features/settings/components/KisAuthForm.tsx handleValidate 인증 전 계좌번호 검사
|
||||
*/
|
||||
function isValidAccountNo(value: string) {
|
||||
const digits = value.replace(/\D/g, "");
|
||||
return digits.length === 10;
|
||||
}
|
||||
|
||||
218
features/settings/components/KisProfileForm.tsx
Normal file
218
features/settings/components/KisProfileForm.tsx
Normal file
@@ -0,0 +1,218 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { CreditCard, CheckCircle2, SearchCheck, ShieldOff, XCircle } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { InlineSpinner } from "@/components/ui/loading-spinner";
|
||||
import { validateKisProfile } from "@/features/settings/apis/kis-auth.api";
|
||||
import { useKisRuntimeStore } from "@/features/settings/store/use-kis-runtime-store";
|
||||
|
||||
/**
|
||||
* @description 한국투자증권 계좌번호 검증 폼입니다.
|
||||
* @remarks UI 흐름: /settings -> 계좌번호 입력 -> 계좌 확인 버튼 -> validate-profile API -> store 반영 -> 대시보드 반영
|
||||
* @see app/api/kis/validate-profile/route.ts 계좌번호 검증 서버 라우트
|
||||
* @see features/settings/store/use-kis-runtime-store.ts 검증 성공값을 전역 상태에 저장합니다.
|
||||
*/
|
||||
export function KisProfileForm() {
|
||||
const {
|
||||
kisAccountNoInput,
|
||||
verifiedCredentials,
|
||||
isKisVerified,
|
||||
isKisProfileVerified,
|
||||
verifiedAccountNo,
|
||||
setKisAccountNoInput,
|
||||
setVerifiedKisProfile,
|
||||
invalidateKisProfileVerification,
|
||||
} = useKisRuntimeStore(
|
||||
useShallow((state) => ({
|
||||
kisAccountNoInput: state.kisAccountNoInput,
|
||||
verifiedCredentials: state.verifiedCredentials,
|
||||
isKisVerified: state.isKisVerified,
|
||||
isKisProfileVerified: state.isKisProfileVerified,
|
||||
verifiedAccountNo: state.verifiedAccountNo,
|
||||
setKisAccountNoInput: state.setKisAccountNoInput,
|
||||
setVerifiedKisProfile: state.setVerifiedKisProfile,
|
||||
invalidateKisProfileVerification: state.invalidateKisProfileVerification,
|
||||
})),
|
||||
);
|
||||
|
||||
const [statusMessage, setStatusMessage] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [isValidating, startValidateTransition] = useTransition();
|
||||
|
||||
/**
|
||||
* @description 계좌번호 인증을 해제하고 입력값을 비웁니다.
|
||||
* @see features/settings/store/use-kis-runtime-store.ts setKisAccountNoInput
|
||||
* @see features/settings/store/use-kis-runtime-store.ts invalidateKisProfileVerification
|
||||
*/
|
||||
function handleDisconnectAccount() {
|
||||
setStatusMessage("계좌 인증을 해제했습니다.");
|
||||
setErrorMessage(null);
|
||||
setKisAccountNoInput("");
|
||||
invalidateKisProfileVerification();
|
||||
}
|
||||
|
||||
function handleValidateProfile() {
|
||||
startValidateTransition(async () => {
|
||||
try {
|
||||
setStatusMessage(null);
|
||||
setErrorMessage(null);
|
||||
|
||||
if (!verifiedCredentials || !isKisVerified) {
|
||||
throw new Error("먼저 앱키 연결을 완료해 주세요.");
|
||||
}
|
||||
|
||||
const accountNo = kisAccountNoInput.trim();
|
||||
|
||||
if (!accountNo) {
|
||||
throw new Error("계좌번호를 입력해 주세요.");
|
||||
}
|
||||
|
||||
if (!isValidAccountNo(accountNo)) {
|
||||
throw new Error(
|
||||
"계좌번호 형식이 올바르지 않습니다. 8-2 형식(예: 12345678-01)으로 입력해 주세요.",
|
||||
);
|
||||
}
|
||||
|
||||
const result = await validateKisProfile({
|
||||
...verifiedCredentials,
|
||||
accountNo,
|
||||
});
|
||||
|
||||
setVerifiedKisProfile({
|
||||
accountNo: result.account.normalizedAccountNo,
|
||||
});
|
||||
|
||||
setStatusMessage(result.message);
|
||||
} catch (error) {
|
||||
invalidateKisProfileVerification();
|
||||
setErrorMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "계좌 확인 중 오류가 발생했습니다.",
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-brand-200 bg-background p-4 shadow-sm dark:border-brand-800/45 dark:bg-brand-900/14">
|
||||
{/* ========== HEADER ========== */}
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold tracking-tight text-foreground">
|
||||
한국투자증권 계좌 인증
|
||||
</h2>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
앱키 연결 완료 후 계좌번호를 확인합니다.
|
||||
</p>
|
||||
</div>
|
||||
<span className="inline-flex items-center rounded-full bg-muted px-2.5 py-1 text-[11px] font-medium text-muted-foreground">
|
||||
{isKisProfileVerified ? "인증 완료" : "미인증"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* ========== INPUTS ========== */}
|
||||
<div className="mt-4">
|
||||
<div className="relative">
|
||||
<CreditCard className="pointer-events-none absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Input
|
||||
type="password"
|
||||
value={kisAccountNoInput}
|
||||
onChange={(event) => setKisAccountNoInput(event.target.value)}
|
||||
placeholder="계좌번호 (예: 12345678-01)"
|
||||
className="h-9 pl-8 text-xs"
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ========== ACTION ========== */}
|
||||
<div className="mt-4 flex items-center justify-between gap-3 border-t border-border/70 pt-4">
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleValidateProfile}
|
||||
disabled={
|
||||
!isKisVerified ||
|
||||
isValidating ||
|
||||
!kisAccountNoInput.trim()
|
||||
}
|
||||
className="h-9 rounded-lg bg-brand-600 px-4 text-xs font-semibold text-white hover:bg-brand-700"
|
||||
>
|
||||
{isValidating ? (
|
||||
<span className="flex items-center gap-1.5">
|
||||
<InlineSpinner className="h-3 w-3 text-white" />
|
||||
확인 중
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-1.5">
|
||||
<SearchCheck className="h-3.5 w-3.5" />
|
||||
계좌 인증하기
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={handleDisconnectAccount}
|
||||
disabled={!isKisProfileVerified && !kisAccountNoInput.trim()}
|
||||
className="h-9 rounded-lg text-xs"
|
||||
>
|
||||
<ShieldOff className="h-3.5 w-3.5" />
|
||||
계좌 인증 해제
|
||||
</Button>
|
||||
|
||||
<div className="flex-1 text-right">
|
||||
{errorMessage && (
|
||||
<p className="flex justify-end gap-1.5 text-[11px] font-medium text-red-500">
|
||||
<XCircle className="h-3.5 w-3.5" />
|
||||
{errorMessage}
|
||||
</p>
|
||||
)}
|
||||
{statusMessage && (
|
||||
<p className="flex justify-end gap-1.5 text-[11px] font-medium text-emerald-600 dark:text-emerald-400">
|
||||
<CheckCircle2 className="h-3.5 w-3.5" />
|
||||
{statusMessage}
|
||||
</p>
|
||||
)}
|
||||
{!statusMessage && !errorMessage && !isKisVerified && (
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
먼저 앱키 연결을 완료해 주세요.
|
||||
</p>
|
||||
)}
|
||||
{!statusMessage && !errorMessage && isKisProfileVerified && (
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
확인된 계좌: {maskAccountNo(verifiedAccountNo)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description KIS 계좌번호(8-2) 입력 포맷을 검증합니다.
|
||||
* @param value 사용자 입력 계좌번호
|
||||
* @returns 형식 유효 여부
|
||||
* @see features/settings/components/KisProfileForm.tsx handleValidateProfile
|
||||
*/
|
||||
function isValidAccountNo(value: string) {
|
||||
const digits = value.replace(/\D/g, "");
|
||||
return digits.length === 10;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 표시용 계좌번호를 마스킹 처리합니다.
|
||||
* @param value 계좌번호(8-2)
|
||||
* @returns 마스킹 계좌번호
|
||||
* @see features/settings/components/KisProfileForm.tsx 확인된 값 표시
|
||||
*/
|
||||
function maskAccountNo(value: string | null) {
|
||||
if (!value) return "-";
|
||||
const digits = value.replace(/\D/g, "");
|
||||
if (digits.length !== 10) return "********";
|
||||
return "********-**";
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { Info } from "lucide-react";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { KisAuthForm } from "@/features/settings/components/KisAuthForm";
|
||||
import { KisProfileForm } from "@/features/settings/components/KisProfileForm";
|
||||
import { useKisRuntimeStore } from "@/features/settings/store/use-kis-runtime-store";
|
||||
|
||||
/**
|
||||
@@ -11,10 +13,17 @@ import { useKisRuntimeStore } from "@/features/settings/store/use-kis-runtime-st
|
||||
*/
|
||||
export function SettingsContainer() {
|
||||
// 상태 정의: 연결 상태 표시용 전역 인증 상태를 구독합니다.
|
||||
const { verifiedCredentials, isKisVerified } = useKisRuntimeStore(
|
||||
const {
|
||||
verifiedCredentials,
|
||||
isKisVerified,
|
||||
isKisProfileVerified,
|
||||
verifiedAccountNo,
|
||||
} = useKisRuntimeStore(
|
||||
useShallow((state) => ({
|
||||
verifiedCredentials: state.verifiedCredentials,
|
||||
isKisVerified: state.isKisVerified,
|
||||
isKisProfileVerified: state.isKisProfileVerified,
|
||||
verifiedAccountNo: state.verifiedAccountNo,
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -23,7 +32,7 @@ export function SettingsContainer() {
|
||||
{/* ========== STATUS CARD ========== */}
|
||||
<article className="rounded-2xl border border-brand-200 bg-muted/35 p-4 dark:border-brand-800/45 dark:bg-brand-900/20">
|
||||
<h1 className="text-xl font-semibold tracking-tight text-foreground">
|
||||
KIS API 설정
|
||||
한국투자증권 연결 설정
|
||||
</h1>
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="font-medium text-foreground">연결 상태:</span>
|
||||
@@ -39,13 +48,51 @@ export function SettingsContainer() {
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="font-medium text-foreground">계좌 인증 상태:</span>
|
||||
{isKisProfileVerified ? (
|
||||
<span className="inline-flex items-center rounded-full bg-emerald-100 px-2.5 py-1 text-xs font-semibold text-emerald-700 dark:bg-emerald-900/35 dark:text-emerald-200">
|
||||
확인됨 ({maskAccountNo(verifiedAccountNo)})
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center rounded-full bg-zinc-100 px-2.5 py-1 text-xs font-semibold text-zinc-700 dark:bg-zinc-800 dark:text-zinc-300">
|
||||
미확인
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
|
||||
{/* ========== AUTH FORM CARD ========== */}
|
||||
<article className="rounded-2xl border border-brand-200 bg-background p-4 shadow-sm dark:border-brand-800/45 dark:bg-brand-900/14">
|
||||
<KisAuthForm />
|
||||
{/* ========== PRIVACY NOTICE ========== */}
|
||||
<article className="rounded-2xl border border-amber-300 bg-amber-50/70 p-4 text-sm text-amber-900 dark:border-amber-700/60 dark:bg-amber-950/30 dark:text-amber-200">
|
||||
<p className="flex items-start gap-2 font-medium">
|
||||
<Info className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
입력 정보 보관 안내
|
||||
</p>
|
||||
<p className="mt-2 text-xs leading-relaxed text-amber-800/90 dark:text-amber-200/90">
|
||||
이 화면에서 입력한 한국투자증권 앱키, 앱시크릿키, 계좌번호는 서버 DB에 저장하지 않습니다.
|
||||
현재 사용 중인 브라우저(클라이언트)에서만 관리되며, 연결 해제 시 즉시 지울 수 있습니다.
|
||||
</p>
|
||||
</article>
|
||||
|
||||
{/* ========== FORM GRID ========== */}
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
<KisAuthForm />
|
||||
<KisProfileForm />
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 계좌번호 마스킹 문자열을 반환합니다.
|
||||
* @param value 계좌번호(8-2)
|
||||
* @returns 마스킹 계좌번호
|
||||
* @see features/settings/components/SettingsContainer.tsx 프로필 상태 라벨 표시
|
||||
*/
|
||||
function maskAccountNo(value: string | null) {
|
||||
if (!value) return "-";
|
||||
const digits = value.replace(/\D/g, "");
|
||||
if (digits.length !== 10) return "********";
|
||||
return "********-**";
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,8 @@ interface KisRuntimeStoreState {
|
||||
|
||||
verifiedCredentials: KisRuntimeCredentials | null;
|
||||
isKisVerified: boolean;
|
||||
isKisProfileVerified: boolean;
|
||||
verifiedAccountNo: string | null;
|
||||
tradingEnv: KisTradingEnv;
|
||||
|
||||
wsApprovalKey: string | null;
|
||||
@@ -47,6 +49,10 @@ interface KisRuntimeStoreActions {
|
||||
credentials: KisRuntimeCredentials,
|
||||
tradingEnv: KisTradingEnv,
|
||||
) => void;
|
||||
setVerifiedKisProfile: (profile: {
|
||||
accountNo: string;
|
||||
}) => void;
|
||||
invalidateKisProfileVerification: () => void;
|
||||
invalidateKisVerification: () => void;
|
||||
clearKisRuntimeSession: (tradingEnv: KisTradingEnv) => void;
|
||||
getOrFetchWsConnection: () => Promise<KisWsConnection | null>;
|
||||
@@ -60,15 +66,23 @@ const INITIAL_STATE: KisRuntimeStoreState = {
|
||||
kisAccountNoInput: "",
|
||||
verifiedCredentials: null,
|
||||
isKisVerified: false,
|
||||
isKisProfileVerified: false,
|
||||
verifiedAccountNo: null,
|
||||
tradingEnv: "real",
|
||||
wsApprovalKey: null,
|
||||
wsUrl: null,
|
||||
_hasHydrated: false,
|
||||
};
|
||||
|
||||
const RESET_PROFILE_STATE = {
|
||||
isKisProfileVerified: false,
|
||||
verifiedAccountNo: null,
|
||||
} as const;
|
||||
|
||||
const RESET_VERIFICATION_STATE = {
|
||||
verifiedCredentials: null,
|
||||
isKisVerified: false,
|
||||
...RESET_PROFILE_STATE,
|
||||
wsApprovalKey: null,
|
||||
wsUrl: null,
|
||||
};
|
||||
@@ -105,10 +119,16 @@ export const useKisRuntimeStore = create<
|
||||
}),
|
||||
|
||||
setKisAccountNoInput: (accountNo) =>
|
||||
set({
|
||||
set((state) => ({
|
||||
kisAccountNoInput: accountNo,
|
||||
...RESET_VERIFICATION_STATE,
|
||||
}),
|
||||
...RESET_PROFILE_STATE,
|
||||
verifiedCredentials: state.verifiedCredentials
|
||||
? {
|
||||
...state.verifiedCredentials,
|
||||
accountNo: "",
|
||||
}
|
||||
: null,
|
||||
})),
|
||||
|
||||
setVerifiedKisSession: (credentials, tradingEnv) =>
|
||||
set({
|
||||
@@ -119,6 +139,33 @@ export const useKisRuntimeStore = create<
|
||||
wsUrl: null,
|
||||
}),
|
||||
|
||||
setVerifiedKisProfile: ({ accountNo }) =>
|
||||
set((state) => ({
|
||||
isKisProfileVerified: true,
|
||||
verifiedAccountNo: accountNo,
|
||||
verifiedCredentials: state.verifiedCredentials
|
||||
? {
|
||||
...state.verifiedCredentials,
|
||||
accountNo,
|
||||
}
|
||||
: state.verifiedCredentials,
|
||||
wsApprovalKey: null,
|
||||
wsUrl: null,
|
||||
})),
|
||||
|
||||
invalidateKisProfileVerification: () =>
|
||||
set((state) => ({
|
||||
...RESET_PROFILE_STATE,
|
||||
verifiedCredentials: state.verifiedCredentials
|
||||
? {
|
||||
...state.verifiedCredentials,
|
||||
accountNo: "",
|
||||
}
|
||||
: state.verifiedCredentials,
|
||||
wsApprovalKey: null,
|
||||
wsUrl: null,
|
||||
})),
|
||||
|
||||
invalidateKisVerification: () =>
|
||||
set({
|
||||
...RESET_VERIFICATION_STATE,
|
||||
@@ -196,6 +243,8 @@ export const useKisRuntimeStore = create<
|
||||
kisAccountNoInput: state.kisAccountNoInput,
|
||||
verifiedCredentials: state.verifiedCredentials,
|
||||
isKisVerified: state.isKisVerified,
|
||||
isKisProfileVerified: state.isKisProfileVerified,
|
||||
verifiedAccountNo: state.verifiedAccountNo,
|
||||
tradingEnv: state.tradingEnv,
|
||||
// wsApprovalKey/wsUrl are kept in memory only (expiration-sensitive).
|
||||
}),
|
||||
|
||||
@@ -18,10 +18,10 @@ export function TradeAccessGate({ canTrade }: TradeAccessGateProps) {
|
||||
<section className="w-full max-w-xl rounded-2xl border border-brand-200 bg-background p-6 shadow-sm dark:border-brand-800/45 dark:bg-brand-900/18">
|
||||
{/* ========== UNVERIFIED NOTICE ========== */}
|
||||
<h2 className="text-lg font-semibold text-foreground">
|
||||
트레이딩을 시작하려면 KIS API 인증이 필요합니다.
|
||||
트레이딩을 시작하려면 한국투자증권 연결이 필요합니다.
|
||||
</h2>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
설정 페이지에서 App Key/App Secret을 입력하고 연결 상태를 확인해 주세요.
|
||||
설정 페이지에서 앱키, 앱시크릿키, 계좌번호를 입력하고 연결을 완료해 주세요.
|
||||
</p>
|
||||
|
||||
{/* ========== ACTION ========== */}
|
||||
|
||||
@@ -220,3 +220,15 @@ export interface DashboardKisWsApprovalResponse {
|
||||
approvalKey?: string;
|
||||
wsUrl?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* KIS 계좌 검증 API 응답
|
||||
*/
|
||||
export interface DashboardKisProfileValidateResponse {
|
||||
ok: boolean;
|
||||
tradingEnv: KisTradingEnv;
|
||||
message: string;
|
||||
account: {
|
||||
normalizedAccountNo: string;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -29,6 +29,17 @@ interface KisBalanceOutput2Row {
|
||||
asst_icdc_erng_rt?: string;
|
||||
}
|
||||
|
||||
interface KisAccountBalanceOutput2Row {
|
||||
tot_asst_amt?: string;
|
||||
nass_tot_amt?: string;
|
||||
tot_dncl_amt?: string;
|
||||
dncl_amt?: string;
|
||||
loan_amt_smtl?: string;
|
||||
pchs_amt_smtl?: string;
|
||||
evlu_amt_smtl?: string;
|
||||
evlu_pfls_amt_smtl?: string;
|
||||
}
|
||||
|
||||
interface KisIndexOutputRow {
|
||||
bstp_nmix_prpr?: string;
|
||||
bstp_nmix_prdy_vrss?: string;
|
||||
@@ -36,11 +47,57 @@ interface KisIndexOutputRow {
|
||||
prdy_vrss_sign?: string;
|
||||
}
|
||||
|
||||
interface KisDailyCcldOutput1Row {
|
||||
ord_dt?: string;
|
||||
ord_tmd?: string;
|
||||
odno?: string;
|
||||
ord_dvsn_name?: string;
|
||||
sll_buy_dvsn_cd?: string;
|
||||
sll_buy_dvsn_cd_name?: string;
|
||||
pdno?: string;
|
||||
prdt_name?: string;
|
||||
ord_qty?: string;
|
||||
ord_unpr?: string;
|
||||
tot_ccld_qty?: string;
|
||||
tot_ccld_amt?: string;
|
||||
avg_prvs?: string;
|
||||
rmn_qty?: string;
|
||||
cncl_yn?: string;
|
||||
}
|
||||
|
||||
interface KisPeriodTradeProfitOutput1Row {
|
||||
trad_dt?: string;
|
||||
pdno?: string;
|
||||
prdt_name?: string;
|
||||
trad_dvsn_name?: string;
|
||||
buy_qty?: string;
|
||||
buy_amt?: string;
|
||||
sll_qty?: string;
|
||||
sll_amt?: string;
|
||||
rlzt_pfls?: string;
|
||||
pfls_rt?: string;
|
||||
fee?: string;
|
||||
tl_tax?: string;
|
||||
}
|
||||
|
||||
interface KisPeriodTradeProfitOutput2Row {
|
||||
tot_rlzt_pfls?: string;
|
||||
tot_pftrt?: string;
|
||||
buy_tr_amt_smtl?: string;
|
||||
sll_tr_amt_smtl?: string;
|
||||
tot_fee?: string;
|
||||
tot_tltx?: string;
|
||||
}
|
||||
|
||||
export interface DomesticBalanceSummary {
|
||||
totalAmount: number;
|
||||
cashBalance: number;
|
||||
totalProfitLoss: number;
|
||||
totalProfitRate: number;
|
||||
netAssetAmount: number;
|
||||
evaluationAmount: number;
|
||||
purchaseAmount: number;
|
||||
loanAmount: number;
|
||||
}
|
||||
|
||||
export interface DomesticHoldingItem {
|
||||
@@ -69,6 +126,54 @@ export interface DomesticMarketIndexResult {
|
||||
changeRate: number;
|
||||
}
|
||||
|
||||
export interface DomesticOrderHistoryItem {
|
||||
orderDate: string;
|
||||
orderTime: string;
|
||||
orderNo: string;
|
||||
symbol: string;
|
||||
name: string;
|
||||
side: "buy" | "sell" | "unknown";
|
||||
orderTypeName: string;
|
||||
orderPrice: number;
|
||||
orderQuantity: number;
|
||||
filledQuantity: number;
|
||||
filledAmount: number;
|
||||
averageFilledPrice: number;
|
||||
remainingQuantity: number;
|
||||
isCanceled: boolean;
|
||||
}
|
||||
|
||||
export interface DomesticTradeJournalItem {
|
||||
tradeDate: string;
|
||||
symbol: string;
|
||||
name: string;
|
||||
side: "buy" | "sell" | "unknown";
|
||||
buyQuantity: number;
|
||||
buyAmount: number;
|
||||
sellQuantity: number;
|
||||
sellAmount: number;
|
||||
realizedProfit: number;
|
||||
realizedRate: number;
|
||||
fee: number;
|
||||
tax: number;
|
||||
}
|
||||
|
||||
export interface DomesticTradeJournalSummary {
|
||||
totalRealizedProfit: number;
|
||||
totalRealizedRate: number;
|
||||
totalBuyAmount: number;
|
||||
totalSellAmount: number;
|
||||
totalFee: number;
|
||||
totalTax: number;
|
||||
}
|
||||
|
||||
export interface DomesticDashboardActivityResult {
|
||||
orders: DomesticOrderHistoryItem[];
|
||||
tradeJournal: DomesticTradeJournalItem[];
|
||||
journalSummary: DomesticTradeJournalSummary;
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
const MARKET_BY_SYMBOL = new Map(
|
||||
KOREAN_STOCK_INDEX.map((item) => [item.symbol, item.market] as const),
|
||||
);
|
||||
@@ -82,6 +187,21 @@ const INDEX_TARGETS: Array<{
|
||||
{ market: "KOSDAQ", code: "1001", name: "코스닥" },
|
||||
];
|
||||
|
||||
const DASHBOARD_ORDER_LOOKBACK_DAYS = 30;
|
||||
const DASHBOARD_JOURNAL_LOOKBACK_DAYS = 90;
|
||||
|
||||
interface DashboardBalanceInquirePreset {
|
||||
inqrDvsn: "01" | "02";
|
||||
prcsDvsn: "00" | "01";
|
||||
}
|
||||
|
||||
const DASHBOARD_BALANCE_INQUIRE_PRESETS: DashboardBalanceInquirePreset[] = [
|
||||
// 공식 문서(주식잔고조회[v1_국내주식-006].xlsx) 기본값
|
||||
{ inqrDvsn: "01", prcsDvsn: "01" },
|
||||
// 일부 환경 호환값
|
||||
{ inqrDvsn: "02", prcsDvsn: "00" },
|
||||
];
|
||||
|
||||
/**
|
||||
* KIS 잔고조회 API를 호출해 대시보드 모델로 변환합니다.
|
||||
* @param account KIS 계좌번호(8-2) 파트
|
||||
@@ -93,32 +213,22 @@ export async function getDomesticDashboardBalance(
|
||||
account: KisAccountParts,
|
||||
credentials?: KisCredentialInput,
|
||||
): Promise<DomesticBalanceResult> {
|
||||
const trId =
|
||||
normalizeTradingEnv(credentials?.tradingEnv) === "real"
|
||||
? "TTTC8434R"
|
||||
: "VTTC8434R";
|
||||
const tradingEnv = normalizeTradingEnv(credentials?.tradingEnv);
|
||||
const inquireBalanceTrId = tradingEnv === "real" ? "TTTC8434R" : "VTTC8434R";
|
||||
const inquireAccountBalanceTrId =
|
||||
tradingEnv === "real" ? "CTRP6548R" : "VTRP6548R";
|
||||
|
||||
const response = await kisGet<unknown>(
|
||||
"/uapi/domestic-stock/v1/trading/inquire-balance",
|
||||
trId,
|
||||
{
|
||||
CANO: account.accountNo,
|
||||
ACNT_PRDT_CD: account.accountProductCode,
|
||||
AFHR_FLPR_YN: "N",
|
||||
OFL_YN: "",
|
||||
INQR_DVSN: "02",
|
||||
UNPR_DVSN: "01",
|
||||
FUND_STTL_ICLD_YN: "N",
|
||||
FNCG_AMT_AUTO_RDPT_YN: "N",
|
||||
PRCS_DVSN: "00",
|
||||
CTX_AREA_FK100: "",
|
||||
CTX_AREA_NK100: "",
|
||||
},
|
||||
const [balanceResponse, accountBalanceResponse] = await Promise.all([
|
||||
getDomesticInquireBalanceEnvelope(account, inquireBalanceTrId, credentials),
|
||||
getDomesticAccountBalanceSummaryRow(
|
||||
account,
|
||||
inquireAccountBalanceTrId,
|
||||
credentials,
|
||||
);
|
||||
),
|
||||
]);
|
||||
|
||||
const holdingRows = parseRows<KisBalanceOutput1Row>(response.output1);
|
||||
const summaryRow = parseFirstRow<KisBalanceOutput2Row>(response.output2);
|
||||
const holdingRows = parseRows<KisBalanceOutput1Row>(balanceResponse.output1);
|
||||
const summaryRow = parseFirstRow<KisBalanceOutput2Row>(balanceResponse.output2);
|
||||
|
||||
const holdings = holdingRows
|
||||
.map((row) => {
|
||||
@@ -139,19 +249,36 @@ export async function getDomesticDashboardBalance(
|
||||
})
|
||||
.filter((item): item is DomesticHoldingItem => Boolean(item));
|
||||
|
||||
const cashBalance = toNumber(summaryRow?.dnca_tot_amt);
|
||||
const cashBalance = firstPositiveNumber(
|
||||
toNumber(accountBalanceResponse?.tot_dncl_amt),
|
||||
toNumber(accountBalanceResponse?.dncl_amt),
|
||||
toNumber(summaryRow?.dnca_tot_amt),
|
||||
);
|
||||
const holdingsEvalAmount = sumNumbers(holdings.map((item) => item.evaluationAmount));
|
||||
const stockEvalAmount = firstPositiveNumber(
|
||||
const evaluationAmount = firstPositiveNumber(
|
||||
toNumber(accountBalanceResponse?.evlu_amt_smtl),
|
||||
toNumber(summaryRow?.scts_evlu_amt),
|
||||
toNumber(summaryRow?.evlu_amt_smtl_amt),
|
||||
holdingsEvalAmount,
|
||||
);
|
||||
const purchaseAmount = firstPositiveNumber(
|
||||
toNumber(accountBalanceResponse?.pchs_amt_smtl),
|
||||
Math.max(evaluationAmount - sumNumbers(holdings.map((item) => item.profitLoss)), 0),
|
||||
);
|
||||
const loanAmount = firstPositiveNumber(toNumber(accountBalanceResponse?.loan_amt_smtl));
|
||||
const netAssetAmount = firstPositiveNumber(
|
||||
toNumber(accountBalanceResponse?.nass_tot_amt),
|
||||
evaluationAmount + cashBalance - loanAmount,
|
||||
);
|
||||
const totalAmount = firstPositiveNumber(
|
||||
stockEvalAmount + cashBalance,
|
||||
toNumber(accountBalanceResponse?.tot_asst_amt),
|
||||
netAssetAmount + loanAmount,
|
||||
evaluationAmount + cashBalance,
|
||||
toNumber(summaryRow?.tot_evlu_amt),
|
||||
holdingsEvalAmount + cashBalance,
|
||||
);
|
||||
const totalProfitLoss = firstDefinedNumber(
|
||||
toOptionalNumber(accountBalanceResponse?.evlu_pfls_amt_smtl),
|
||||
toOptionalNumber(summaryRow?.evlu_pfls_smtl_amt),
|
||||
sumNumbers(holdings.map((item) => item.profitLoss)),
|
||||
);
|
||||
@@ -166,11 +293,95 @@ export async function getDomesticDashboardBalance(
|
||||
cashBalance,
|
||||
totalProfitLoss,
|
||||
totalProfitRate,
|
||||
netAssetAmount,
|
||||
evaluationAmount,
|
||||
purchaseAmount,
|
||||
loanAmount,
|
||||
},
|
||||
holdings,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 주식잔고조회(v1_국내주식-006)를 문서 기본값 우선으로 호출합니다.
|
||||
* @param account KIS 계좌번호(8-2) 파트
|
||||
* @param trId 거래 환경별 TR ID
|
||||
* @param credentials 사용자 입력 키(선택)
|
||||
* @returns KIS 잔고 조회 원본 응답
|
||||
* @see lib/kis/dashboard.ts getDomesticDashboardBalance
|
||||
*/
|
||||
async function getDomesticInquireBalanceEnvelope(
|
||||
account: KisAccountParts,
|
||||
trId: string,
|
||||
credentials?: KisCredentialInput,
|
||||
) {
|
||||
const errors: string[] = [];
|
||||
|
||||
for (const preset of DASHBOARD_BALANCE_INQUIRE_PRESETS) {
|
||||
try {
|
||||
return await kisGet<unknown>(
|
||||
"/uapi/domestic-stock/v1/trading/inquire-balance",
|
||||
trId,
|
||||
{
|
||||
CANO: account.accountNo,
|
||||
ACNT_PRDT_CD: account.accountProductCode,
|
||||
AFHR_FLPR_YN: "N",
|
||||
OFL_YN: "",
|
||||
INQR_DVSN: preset.inqrDvsn,
|
||||
UNPR_DVSN: "01",
|
||||
FUND_STTL_ICLD_YN: "N",
|
||||
FNCG_AMT_AUTO_RDPT_YN: "N",
|
||||
PRCS_DVSN: preset.prcsDvsn,
|
||||
CTX_AREA_FK100: "",
|
||||
CTX_AREA_NK100: "",
|
||||
},
|
||||
credentials,
|
||||
);
|
||||
} catch (error) {
|
||||
errors.push(
|
||||
`INQR_DVSN=${preset.inqrDvsn}, PRCS_DVSN=${preset.prcsDvsn}: ${error instanceof Error ? error.message : "호출 실패"}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`주식잔고조회(v1_국내주식-006) 호출 실패: ${errors.join(" | ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 투자계좌자산현황조회(v1_국내주식-048)의 output2를 조회합니다.
|
||||
* @param account KIS 계좌번호(8-2) 파트
|
||||
* @param trId 거래 환경별 TR ID (실전: CTRP6548R, 모의: VTRP6548R)
|
||||
* @param credentials 사용자 입력 키(선택)
|
||||
* @returns 계좌 자산 요약(output2) 또는 null
|
||||
* @see C:/dev/auto-trade/.tmp/open-trading-api/examples_llm/domestic_stock/inquire_account_balance/inquire_account_balance.py
|
||||
*/
|
||||
async function getDomesticAccountBalanceSummaryRow(
|
||||
account: KisAccountParts,
|
||||
trId: string,
|
||||
credentials?: KisCredentialInput,
|
||||
) {
|
||||
try {
|
||||
const response = await kisGet<unknown>(
|
||||
"/uapi/domestic-stock/v1/trading/inquire-account-balance",
|
||||
trId,
|
||||
{
|
||||
CANO: account.accountNo,
|
||||
ACNT_PRDT_CD: account.accountProductCode,
|
||||
INQR_DVSN_1: "",
|
||||
BSPR_BF_DT_APLY_YN: "",
|
||||
},
|
||||
credentials,
|
||||
);
|
||||
|
||||
return parseFirstRow<KisAccountBalanceOutput2Row>(response.output2);
|
||||
} catch {
|
||||
// 일부 계좌/환경에서는 v1_국내주식-048 조회가 제한될 수 있어, 잔고 API 값으로 폴백합니다.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* KOSPI/KOSDAQ 지수를 조회해 대시보드 모델로 변환합니다.
|
||||
* @param credentials 사용자 입력 키(선택)
|
||||
@@ -210,6 +421,399 @@ export async function getDomesticDashboardIndices(
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 대시보드 하단의 주문내역/매매일지 데이터를 조회합니다.
|
||||
* @param account KIS 계좌번호(8-2) 파트
|
||||
* @param credentials 사용자 입력 키(선택)
|
||||
* @returns 주문내역/매매일지/요약/경고 목록
|
||||
* @remarks UI 흐름: 대시보드 하단 진입 -> activity API 호출 -> 주문내역/매매일지 탭 렌더링
|
||||
* @see app/api/kis/domestic/activity/route.ts 대시보드 활동 데이터 API 응답 생성
|
||||
* @see features/dashboard/components/ActivitySection.tsx 주문내역/매매일지 UI 렌더링
|
||||
*/
|
||||
export async function getDomesticDashboardActivity(
|
||||
account: KisAccountParts,
|
||||
credentials?: KisCredentialInput,
|
||||
): Promise<DomesticDashboardActivityResult> {
|
||||
const [orderResult, journalResult] = await Promise.allSettled([
|
||||
getDomesticOrderHistory(account, credentials),
|
||||
getDomesticTradeJournal(account, credentials),
|
||||
]);
|
||||
|
||||
const warnings: string[] = [];
|
||||
|
||||
const orders =
|
||||
orderResult.status === "fulfilled"
|
||||
? orderResult.value
|
||||
: [];
|
||||
|
||||
if (orderResult.status === "rejected") {
|
||||
warnings.push(
|
||||
orderResult.reason instanceof Error
|
||||
? `주문내역 조회 실패: ${orderResult.reason.message}`
|
||||
: "주문내역 조회에 실패했습니다.",
|
||||
);
|
||||
}
|
||||
|
||||
const tradeJournal =
|
||||
journalResult.status === "fulfilled"
|
||||
? journalResult.value.items
|
||||
: [];
|
||||
const journalSummary =
|
||||
journalResult.status === "fulfilled"
|
||||
? journalResult.value.summary
|
||||
: createEmptyJournalSummary();
|
||||
|
||||
if (journalResult.status === "rejected") {
|
||||
const tradingEnv = normalizeTradingEnv(credentials?.tradingEnv);
|
||||
const defaultMessage =
|
||||
tradingEnv === "mock"
|
||||
? "매매일지 API는 모의투자에서 지원되지 않거나 조회 제한이 있을 수 있습니다."
|
||||
: "매매일지 조회에 실패했습니다.";
|
||||
|
||||
warnings.push(
|
||||
journalResult.reason instanceof Error
|
||||
? `매매일지 조회 실패: ${journalResult.reason.message}`
|
||||
: defaultMessage,
|
||||
);
|
||||
}
|
||||
|
||||
if (orderResult.status === "rejected" && journalResult.status === "rejected") {
|
||||
throw new Error("주문내역/매매일지를 모두 조회하지 못했습니다.");
|
||||
}
|
||||
|
||||
return {
|
||||
orders,
|
||||
tradeJournal,
|
||||
journalSummary,
|
||||
warnings,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 주식일별주문체결조회(v1_국내주식-005)로 최근 주문내역을 조회합니다.
|
||||
* @param account KIS 계좌번호(8-2) 파트
|
||||
* @param credentials 사용자 입력 키(선택)
|
||||
* @returns 주문내역 목록(최신순)
|
||||
* @see C:/dev/auto-trade/.tmp/open-trading-api/examples_llm/domestic_stock/inquire_daily_ccld/inquire_daily_ccld.py
|
||||
*/
|
||||
async function getDomesticOrderHistory(
|
||||
account: KisAccountParts,
|
||||
credentials?: KisCredentialInput,
|
||||
) {
|
||||
const tradingEnv = normalizeTradingEnv(credentials?.tradingEnv);
|
||||
const trId = tradingEnv === "real" ? "TTTC0081R" : "VTTC0081R";
|
||||
const range = getLookbackRangeYmd(DASHBOARD_ORDER_LOOKBACK_DAYS);
|
||||
|
||||
const response = await kisGet<unknown>(
|
||||
"/uapi/domestic-stock/v1/trading/inquire-daily-ccld",
|
||||
trId,
|
||||
{
|
||||
CANO: account.accountNo,
|
||||
ACNT_PRDT_CD: account.accountProductCode,
|
||||
INQR_STRT_DT: range.startDate,
|
||||
INQR_END_DT: range.endDate,
|
||||
SLL_BUY_DVSN_CD: "00",
|
||||
PDNO: "",
|
||||
CCLD_DVSN: "00",
|
||||
INQR_DVSN: "00",
|
||||
INQR_DVSN_3: "00",
|
||||
ORD_GNO_BRNO: "",
|
||||
ODNO: "",
|
||||
INQR_DVSN_1: "",
|
||||
CTX_AREA_FK100: "",
|
||||
CTX_AREA_NK100: "",
|
||||
EXCG_ID_DVSN_CD: "ALL",
|
||||
},
|
||||
credentials,
|
||||
);
|
||||
|
||||
const rows = parseRows<KisDailyCcldOutput1Row>(response.output1);
|
||||
const mappedRows = rows.map((row) => {
|
||||
const orderDateRaw = toDigits(row.ord_dt);
|
||||
const orderTimeRaw = normalizeTimeDigits(row.ord_tmd);
|
||||
const symbol = (row.pdno ?? "").trim();
|
||||
const name = (row.prdt_name ?? "").trim();
|
||||
const orderNo = (row.odno ?? "").trim();
|
||||
const side = parseTradeSide(row.sll_buy_dvsn_cd, row.sll_buy_dvsn_cd_name);
|
||||
|
||||
return {
|
||||
orderDate: formatDateLabel(orderDateRaw),
|
||||
orderTime: formatTimeLabel(orderTimeRaw),
|
||||
orderNo,
|
||||
symbol,
|
||||
name: name || symbol || "-",
|
||||
side,
|
||||
orderTypeName: (row.ord_dvsn_name ?? "").trim() || "일반",
|
||||
orderPrice: toNumber(row.ord_unpr),
|
||||
orderQuantity: toNumber(row.ord_qty),
|
||||
filledQuantity: toNumber(row.tot_ccld_qty),
|
||||
filledAmount: toNumber(row.tot_ccld_amt),
|
||||
averageFilledPrice: toNumber(row.avg_prvs),
|
||||
remainingQuantity: toNumber(row.rmn_qty),
|
||||
isCanceled: (row.cncl_yn ?? "").trim().toUpperCase() === "Y",
|
||||
sortKey: `${orderDateRaw}${orderTimeRaw}`,
|
||||
};
|
||||
});
|
||||
|
||||
const normalized = mappedRows
|
||||
.sort((a, b) => b.sortKey.localeCompare(a.sortKey))
|
||||
.slice(0, 100)
|
||||
.map((item) => ({
|
||||
orderDate: item.orderDate,
|
||||
orderTime: item.orderTime,
|
||||
orderNo: item.orderNo,
|
||||
symbol: item.symbol,
|
||||
name: item.name,
|
||||
side: item.side,
|
||||
orderTypeName: item.orderTypeName,
|
||||
orderPrice: item.orderPrice,
|
||||
orderQuantity: item.orderQuantity,
|
||||
filledQuantity: item.filledQuantity,
|
||||
filledAmount: item.filledAmount,
|
||||
averageFilledPrice: item.averageFilledPrice,
|
||||
remainingQuantity: item.remainingQuantity,
|
||||
isCanceled: item.isCanceled,
|
||||
}));
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 기간별매매손익현황조회(v1_국내주식-060)로 매매일지 데이터를 조회합니다.
|
||||
* @param account KIS 계좌번호(8-2) 파트
|
||||
* @param credentials 사용자 입력 키(선택)
|
||||
* @returns 매매일지 목록/요약
|
||||
* @see C:/dev/auto-trade/.tmp/open-trading-api/examples_llm/domestic_stock/inquire_period_trade_profit/inquire_period_trade_profit.py
|
||||
* @see C:/dev/auto-trade/.tmp/open-trading-api/kis_apis.xlsx v1_국내주식-060 모의 TR 미표기
|
||||
*/
|
||||
async function getDomesticTradeJournal(
|
||||
account: KisAccountParts,
|
||||
credentials?: KisCredentialInput,
|
||||
) {
|
||||
const tradingEnv = normalizeTradingEnv(credentials?.tradingEnv);
|
||||
const range = getLookbackRangeYmd(DASHBOARD_JOURNAL_LOOKBACK_DAYS);
|
||||
const trIdCandidates =
|
||||
tradingEnv === "real"
|
||||
? ["TTTC8715R"]
|
||||
: ["VTTC8715R", "TTTC8715R"];
|
||||
|
||||
let response: { output1?: unknown; output2?: unknown } | null = null;
|
||||
let lastError: Error | null = null;
|
||||
|
||||
for (const trId of trIdCandidates) {
|
||||
try {
|
||||
response = await kisGet<unknown>(
|
||||
"/uapi/domestic-stock/v1/trading/inquire-period-trade-profit",
|
||||
trId,
|
||||
{
|
||||
CANO: account.accountNo,
|
||||
ACNT_PRDT_CD: account.accountProductCode,
|
||||
SORT_DVSN: "02",
|
||||
INQR_STRT_DT: range.startDate,
|
||||
INQR_END_DT: range.endDate,
|
||||
CBLC_DVSN: "00",
|
||||
PDNO: "",
|
||||
CTX_AREA_FK100: "",
|
||||
CTX_AREA_NK100: "",
|
||||
},
|
||||
credentials,
|
||||
);
|
||||
break;
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error : new Error("매매일지 조회 실패");
|
||||
}
|
||||
}
|
||||
|
||||
if (!response) {
|
||||
throw lastError ?? new Error("매매일지 조회 실패");
|
||||
}
|
||||
|
||||
const rows = parseRows<KisPeriodTradeProfitOutput1Row>(response.output1);
|
||||
const summaryRow = parseFirstRow<KisPeriodTradeProfitOutput2Row>(response.output2);
|
||||
|
||||
const items = rows
|
||||
.map((row) => {
|
||||
const tradeDateRaw = toDigits(row.trad_dt);
|
||||
const symbol = (row.pdno ?? "").trim();
|
||||
const name = (row.prdt_name ?? "").trim();
|
||||
|
||||
return {
|
||||
tradeDate: formatDateLabel(tradeDateRaw),
|
||||
symbol,
|
||||
name: name || symbol || "-",
|
||||
side: parseTradeSide(undefined, row.trad_dvsn_name),
|
||||
buyQuantity: toNumber(row.buy_qty),
|
||||
buyAmount: toNumber(row.buy_amt),
|
||||
sellQuantity: toNumber(row.sll_qty),
|
||||
sellAmount: toNumber(row.sll_amt),
|
||||
realizedProfit: toNumber(row.rlzt_pfls),
|
||||
realizedRate: toNumber(row.pfls_rt),
|
||||
fee: toNumber(row.fee),
|
||||
tax: toNumber(row.tl_tax),
|
||||
sortKey: tradeDateRaw,
|
||||
} satisfies DomesticTradeJournalItem & { sortKey: string };
|
||||
})
|
||||
.sort((a, b) => b.sortKey.localeCompare(a.sortKey))
|
||||
.slice(0, 100)
|
||||
.map((item) => ({
|
||||
tradeDate: item.tradeDate,
|
||||
symbol: item.symbol,
|
||||
name: item.name,
|
||||
side: item.side,
|
||||
buyQuantity: item.buyQuantity,
|
||||
buyAmount: item.buyAmount,
|
||||
sellQuantity: item.sellQuantity,
|
||||
sellAmount: item.sellAmount,
|
||||
realizedProfit: item.realizedProfit,
|
||||
realizedRate: item.realizedRate,
|
||||
fee: item.fee,
|
||||
tax: item.tax,
|
||||
}));
|
||||
|
||||
const summary = {
|
||||
totalRealizedProfit: firstDefinedNumber(
|
||||
toOptionalNumber(summaryRow?.tot_rlzt_pfls),
|
||||
sumNumbers(items.map((item) => item.realizedProfit)),
|
||||
),
|
||||
totalRealizedRate: firstDefinedNumber(
|
||||
toOptionalNumber(summaryRow?.tot_pftrt),
|
||||
calcProfitRate(
|
||||
sumNumbers(items.map((item) => item.realizedProfit)),
|
||||
sumNumbers(items.map((item) => item.buyAmount)),
|
||||
),
|
||||
),
|
||||
totalBuyAmount: firstDefinedNumber(
|
||||
toOptionalNumber(summaryRow?.buy_tr_amt_smtl),
|
||||
sumNumbers(items.map((item) => item.buyAmount)),
|
||||
),
|
||||
totalSellAmount: firstDefinedNumber(
|
||||
toOptionalNumber(summaryRow?.sll_tr_amt_smtl),
|
||||
sumNumbers(items.map((item) => item.sellAmount)),
|
||||
),
|
||||
totalFee: firstDefinedNumber(
|
||||
toOptionalNumber(summaryRow?.tot_fee),
|
||||
sumNumbers(items.map((item) => item.fee)),
|
||||
),
|
||||
totalTax: firstDefinedNumber(
|
||||
toOptionalNumber(summaryRow?.tot_tltx),
|
||||
sumNumbers(items.map((item) => item.tax)),
|
||||
),
|
||||
} satisfies DomesticTradeJournalSummary;
|
||||
|
||||
return {
|
||||
items,
|
||||
summary,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 기준일 기준 N일 범위의 YYYYMMDD 기간을 반환합니다.
|
||||
* @param lookbackDays 과거 조회 일수
|
||||
* @returns 시작/종료 일자
|
||||
* @see lib/kis/dashboard.ts getDomesticOrderHistory/getDomesticTradeJournal 조회 기간 계산
|
||||
*/
|
||||
function getLookbackRangeYmd(lookbackDays: number) {
|
||||
const end = new Date();
|
||||
const start = new Date(end);
|
||||
start.setDate(end.getDate() - lookbackDays);
|
||||
|
||||
return {
|
||||
startDate: formatYmd(start),
|
||||
endDate: formatYmd(end),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Date를 YYYYMMDD 문자열로 변환합니다.
|
||||
* @param date 기준 일자
|
||||
* @returns YYYYMMDD
|
||||
* @see lib/kis/dashboard.ts getLookbackRangeYmd
|
||||
*/
|
||||
function formatYmd(date: Date) {
|
||||
const year = String(date.getFullYear());
|
||||
const month = String(date.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(date.getDate()).padStart(2, "0");
|
||||
return `${year}${month}${day}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 문자열에서 숫자만 추출합니다.
|
||||
* @param value 원본 문자열
|
||||
* @returns 숫자 문자열
|
||||
* @see lib/kis/dashboard.ts 주문일자/매매일자/시각 정규화
|
||||
*/
|
||||
function toDigits(value?: string) {
|
||||
return (value ?? "").replace(/\D/g, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문 시각을 HHMMSS로 정규화합니다.
|
||||
* @param value 시각 문자열
|
||||
* @returns 6자리 시각 문자열
|
||||
* @see lib/kis/dashboard.ts getDomesticOrderHistory 정렬/표시 시각 생성
|
||||
*/
|
||||
function normalizeTimeDigits(value?: string) {
|
||||
const digits = toDigits(value);
|
||||
if (!digits) return "000000";
|
||||
return digits.padEnd(6, "0").slice(0, 6);
|
||||
}
|
||||
|
||||
/**
|
||||
* YYYYMMDD를 YYYY-MM-DD로 변환합니다.
|
||||
* @param value 날짜 문자열
|
||||
* @returns YYYY-MM-DD 또는 "-"
|
||||
* @see lib/kis/dashboard.ts 주문내역/매매일지 날짜 컬럼 표시
|
||||
*/
|
||||
function formatDateLabel(value: string) {
|
||||
if (value.length !== 8) return "-";
|
||||
return `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* HHMMSS를 HH:MM:SS로 변환합니다.
|
||||
* @param value 시각 문자열
|
||||
* @returns HH:MM:SS 또는 "-"
|
||||
* @see lib/kis/dashboard.ts 주문내역 시각 컬럼 표시
|
||||
*/
|
||||
function formatTimeLabel(value: string) {
|
||||
if (value.length !== 6) return "-";
|
||||
return `${value.slice(0, 2)}:${value.slice(2, 4)}:${value.slice(4, 6)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* KIS 매수/매도 코드를 공통 side 값으로 변환합니다.
|
||||
* @param code 매수매도구분코드
|
||||
* @param name 매수매도구분명 또는 매매구분명
|
||||
* @returns buy/sell/unknown
|
||||
* @see lib/kis/dashboard.ts getDomesticOrderHistory/getDomesticTradeJournal
|
||||
*/
|
||||
function parseTradeSide(code?: string, name?: string): "buy" | "sell" | "unknown" {
|
||||
const normalizedCode = (code ?? "").trim();
|
||||
const normalizedName = (name ?? "").trim();
|
||||
|
||||
if (normalizedCode === "01") return "sell";
|
||||
if (normalizedCode === "02") return "buy";
|
||||
if (normalizedName.includes("매도")) return "sell";
|
||||
if (normalizedName.includes("매수")) return "buy";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* 매매일지 요약 기본값을 반환합니다.
|
||||
* @returns 0으로 채운 요약 객체
|
||||
* @see lib/kis/dashboard.ts getDomesticDashboardActivity 매매일지 실패 폴백
|
||||
*/
|
||||
function createEmptyJournalSummary(): DomesticTradeJournalSummary {
|
||||
return {
|
||||
totalRealizedProfit: 0,
|
||||
totalRealizedRate: 0,
|
||||
totalBuyAmount: 0,
|
||||
totalSellAmount: 0,
|
||||
totalFee: 0,
|
||||
totalTax: 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 문자열 숫자를 number로 변환합니다.
|
||||
* @param value KIS 숫자 문자열
|
||||
|
||||
Reference in New Issue
Block a user