임시커밋
This commit is contained in:
82
features/settings/apis/kis-auth.api.ts
Normal file
82
features/settings/apis/kis-auth.api.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import type { KisRuntimeCredentials } from "@/features/settings/store/use-kis-runtime-store";
|
||||
import type {
|
||||
DashboardKisRevokeResponse,
|
||||
DashboardKisValidateResponse,
|
||||
DashboardKisWsApprovalResponse,
|
||||
} from "@/features/trade/types/trade.types";
|
||||
|
||||
interface KisApiBaseResponse {
|
||||
ok: boolean;
|
||||
message: string;
|
||||
}
|
||||
|
||||
async function postKisAuthApi<T extends KisApiBaseResponse>(
|
||||
endpoint: string,
|
||||
credentials: KisRuntimeCredentials,
|
||||
fallbackErrorMessage: string,
|
||||
): Promise<T> {
|
||||
const response = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(credentials),
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
const payload = (await response.json()) as T;
|
||||
|
||||
if (!response.ok || !payload.ok) {
|
||||
throw new Error(payload.message || fallbackErrorMessage);
|
||||
}
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description KIS API 키를 검증합니다.
|
||||
* @see app/api/kis/validate/route.ts
|
||||
*/
|
||||
export async function validateKisCredentials(
|
||||
credentials: KisRuntimeCredentials,
|
||||
): Promise<DashboardKisValidateResponse> {
|
||||
return postKisAuthApi<DashboardKisValidateResponse>(
|
||||
"/api/kis/validate",
|
||||
credentials,
|
||||
"API 키 검증에 실패했습니다.",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description KIS 액세스 토큰을 폐기합니다.
|
||||
* @see app/api/kis/revoke/route.ts
|
||||
*/
|
||||
export async function revokeKisCredentials(
|
||||
credentials: KisRuntimeCredentials,
|
||||
): Promise<DashboardKisRevokeResponse> {
|
||||
return postKisAuthApi<DashboardKisRevokeResponse>(
|
||||
"/api/kis/revoke",
|
||||
credentials,
|
||||
"API 토큰 폐기에 실패했습니다.",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 웹소켓 승인키와 WS URL을 조회합니다.
|
||||
* @see app/api/kis/ws/approval/route.ts
|
||||
*/
|
||||
export async function fetchKisWebSocketApproval(
|
||||
credentials: KisRuntimeCredentials,
|
||||
): Promise<DashboardKisWsApprovalResponse> {
|
||||
const payload = await postKisAuthApi<DashboardKisWsApprovalResponse>(
|
||||
"/api/kis/ws/approval",
|
||||
credentials,
|
||||
"웹소켓 승인키 발급에 실패했습니다.",
|
||||
);
|
||||
|
||||
if (!payload.approvalKey || !payload.wsUrl) {
|
||||
throw new Error(payload.message || "웹소켓 연결 정보가 누락되었습니다.");
|
||||
}
|
||||
|
||||
return payload;
|
||||
}
|
||||
314
features/settings/components/KisAuthForm.tsx
Normal file
314
features/settings/components/KisAuthForm.tsx
Normal file
@@ -0,0 +1,314 @@
|
||||
import { useState, useTransition } from "react";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useKisRuntimeStore } from "@/features/settings/store/use-kis-runtime-store";
|
||||
import {
|
||||
revokeKisCredentials,
|
||||
validateKisCredentials,
|
||||
} from "@/features/settings/apis/kis-auth.api";
|
||||
import {
|
||||
KeyRound,
|
||||
Shield,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
Lock,
|
||||
Sparkles,
|
||||
Zap,
|
||||
Activity,
|
||||
} from "lucide-react";
|
||||
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
|
||||
*/
|
||||
export function KisAuthForm() {
|
||||
const {
|
||||
kisTradingEnvInput,
|
||||
kisAppKeyInput,
|
||||
kisAppSecretInput,
|
||||
verifiedCredentials,
|
||||
isKisVerified,
|
||||
setKisTradingEnvInput,
|
||||
setKisAppKeyInput,
|
||||
setKisAppSecretInput,
|
||||
setVerifiedKisSession,
|
||||
invalidateKisVerification,
|
||||
clearKisRuntimeSession,
|
||||
} = useKisRuntimeStore(
|
||||
useShallow((state) => ({
|
||||
kisTradingEnvInput: state.kisTradingEnvInput,
|
||||
kisAppKeyInput: state.kisAppKeyInput,
|
||||
kisAppSecretInput: state.kisAppSecretInput,
|
||||
verifiedCredentials: state.verifiedCredentials,
|
||||
isKisVerified: state.isKisVerified,
|
||||
setKisTradingEnvInput: state.setKisTradingEnvInput,
|
||||
setKisAppKeyInput: state.setKisAppKeyInput,
|
||||
setKisAppSecretInput: state.setKisAppSecretInput,
|
||||
setVerifiedKisSession: state.setVerifiedKisSession,
|
||||
invalidateKisVerification: state.invalidateKisVerification,
|
||||
clearKisRuntimeSession: state.clearKisRuntimeSession,
|
||||
})),
|
||||
);
|
||||
|
||||
const [statusMessage, setStatusMessage] = useState<string | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [isValidating, startValidateTransition] = useTransition();
|
||||
const [isRevoking, startRevokeTransition] = useTransition();
|
||||
|
||||
// 입력 필드 Focus 상태 관리를 위한 State
|
||||
const [focusedField, setFocusedField] = useState<
|
||||
"appKey" | "appSecret" | null
|
||||
>(null);
|
||||
|
||||
function handleValidate() {
|
||||
startValidateTransition(async () => {
|
||||
try {
|
||||
setErrorMessage(null);
|
||||
setStatusMessage(null);
|
||||
|
||||
const appKey = kisAppKeyInput.trim();
|
||||
const appSecret = kisAppSecretInput.trim();
|
||||
|
||||
if (!appKey || !appSecret) {
|
||||
throw new Error("App Key와 App Secret을 모두 입력해 주세요.");
|
||||
}
|
||||
|
||||
const credentials = {
|
||||
appKey,
|
||||
appSecret,
|
||||
tradingEnv: kisTradingEnvInput,
|
||||
accountNo: verifiedCredentials?.accountNo ?? "",
|
||||
};
|
||||
|
||||
const result = await validateKisCredentials(credentials);
|
||||
setVerifiedKisSession(credentials, result.tradingEnv);
|
||||
setStatusMessage(
|
||||
`${result.message} (${result.tradingEnv === "real" ? "실전" : "모의"})`,
|
||||
);
|
||||
} catch (err) {
|
||||
invalidateKisVerification();
|
||||
setErrorMessage(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "API 키 검증 중 오류가 발생했습니다.",
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function handleRevoke() {
|
||||
if (!verifiedCredentials) return;
|
||||
|
||||
startRevokeTransition(async () => {
|
||||
try {
|
||||
setErrorMessage(null);
|
||||
setStatusMessage(null);
|
||||
const result = await revokeKisCredentials(verifiedCredentials);
|
||||
clearKisRuntimeSession(result.tradingEnv);
|
||||
setStatusMessage(
|
||||
`${result.message} (${result.tradingEnv === "real" ? "실전" : "모의"})`,
|
||||
);
|
||||
} catch (err) {
|
||||
setErrorMessage(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "연결 해제 중 오류가 발생했습니다.",
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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">
|
||||
{/* Inner Content Container - Compact spacing */}
|
||||
<div className="flex flex-col gap-4">
|
||||
{/* Header Section */}
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-brand-50 text-brand-600 ring-1 ring-brand-100 dark:bg-brand-900/20 dark:text-brand-400 dark:ring-brand-800/50">
|
||||
<KeyRound className="h-4.5 w-4.5" />
|
||||
</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 키를 입력해 주세요.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Trading Mode Switch (Segmented Control - Compact) */}
|
||||
<div className="flex shrink-0 items-center rounded-md bg-zinc-100 p-0.5 ring-1 ring-zinc-200 dark:bg-zinc-800 dark:ring-zinc-700">
|
||||
<button
|
||||
onClick={() => setKisTradingEnvInput("real")}
|
||||
className={cn(
|
||||
"relative flex items-center gap-1.5 rounded-[5px] px-2.5 py-1 text-[11px] font-semibold transition-all duration-200",
|
||||
kisTradingEnvInput === "real"
|
||||
? "bg-white text-brand-600 shadow-sm ring-1 ring-black/5 dark:bg-brand-500 dark:text-white dark:ring-brand-400"
|
||||
: "text-zinc-500 hover:text-zinc-700 hover:bg-black/5 dark:text-zinc-400 dark:hover:text-zinc-200 dark:hover:bg-white/5",
|
||||
)}
|
||||
>
|
||||
<Zap
|
||||
className={cn(
|
||||
"h-3 w-3",
|
||||
kisTradingEnvInput === "real"
|
||||
? "text-brand-500 dark:text-white"
|
||||
: "text-zinc-400",
|
||||
)}
|
||||
/>
|
||||
실전 투자
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setKisTradingEnvInput("mock")}
|
||||
className={cn(
|
||||
"relative flex items-center gap-1.5 rounded-[5px] px-2.5 py-1 text-[11px] font-semibold transition-all duration-200",
|
||||
kisTradingEnvInput === "mock"
|
||||
? "bg-white text-zinc-800 shadow-sm ring-1 ring-black/5 dark:bg-zinc-600 dark:text-white dark:ring-zinc-500"
|
||||
: "text-zinc-500 hover:text-zinc-700 hover:bg-black/5 dark:text-zinc-400 dark:hover:text-zinc-200 dark:hover:bg-white/5",
|
||||
)}
|
||||
>
|
||||
<Activity
|
||||
className={cn(
|
||||
"h-3 w-3",
|
||||
kisTradingEnvInput === "mock"
|
||||
? "text-zinc-800 dark:text-zinc-200"
|
||||
: "text-zinc-400",
|
||||
)}
|
||||
/>
|
||||
모의 투자
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Input Fields Section (Compact Stacked Layout) */}
|
||||
<div className="flex flex-col gap-2">
|
||||
{/* 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",
|
||||
focusedField === "appKey"
|
||||
? "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">
|
||||
<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"
|
||||
value={kisAppKeyInput}
|
||||
onChange={(e) => setKisAppKeyInput(e.target.value)}
|
||||
onFocus={() => setFocusedField("appKey")}
|
||||
onBlur={() => setFocusedField(null)}
|
||||
placeholder="App Key 입력"
|
||||
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 */}
|
||||
<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 === "appSecret"
|
||||
? "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">
|
||||
<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"
|
||||
value={kisAppSecretInput}
|
||||
onChange={(e) => setKisAppSecretInput(e.target.value)}
|
||||
onFocus={() => setFocusedField("appSecret")}
|
||||
onBlur={() => setFocusedField(null)}
|
||||
placeholder="App Secret 입력"
|
||||
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>
|
||||
</div>
|
||||
|
||||
{/* Action & Status Section */}
|
||||
<div className="flex items-center justify-between border-t border-zinc-100 pt-4 dark:border-zinc-800/50">
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handleValidate}
|
||||
disabled={
|
||||
isValidating ||
|
||||
!kisAppKeyInput.trim() ||
|
||||
!kisAppSecretInput.trim()
|
||||
}
|
||||
className="h-9 rounded-lg bg-brand-600 px-4 text-xs font-semibold text-white shadow-sm transition-all hover:bg-brand-700 hover:shadow disabled:opacity-50 disabled:shadow-none dark:bg-brand-600 dark:hover:bg-brand-500"
|
||||
>
|
||||
{isValidating ? (
|
||||
<span className="flex items-center gap-1.5">
|
||||
<InlineSpinner className="text-white h-3 w-3" />
|
||||
검증 중
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-1.5">
|
||||
<Sparkles className="h-3 w-3 fill-brand-200 text-brand-200" />
|
||||
API 키 연결
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{isKisVerified && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleRevoke}
|
||||
disabled={isRevoking}
|
||||
className="h-9 rounded-lg border-zinc-200 bg-white text-xs text-zinc-600 hover:bg-zinc-50 hover:text-zinc-900 dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-400 dark:hover:text-zinc-200"
|
||||
>
|
||||
{isRevoking ? "해제 중" : "연결 해제"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Status Messages - Compact */}
|
||||
<div className="flex-1 text-right">
|
||||
{errorMessage && (
|
||||
<p className="animate-in fade-in slide-in-from-right-4 flex justify-end gap-1.5 text-[11px] font-semibold text-red-500">
|
||||
<XCircle className="h-3.5 w-3.5" />
|
||||
{errorMessage}
|
||||
</p>
|
||||
)}
|
||||
{statusMessage && (
|
||||
<p className="animate-in fade-in slide-in-from-right-4 flex justify-end gap-1.5 text-[11px] font-semibold text-brand-600 dark:text-brand-400">
|
||||
<CheckCircle2 className="h-3.5 w-3.5" />
|
||||
{statusMessage}
|
||||
</p>
|
||||
)}
|
||||
{!errorMessage && !statusMessage && !isKisVerified && (
|
||||
<p className="flex justify-end gap-1.5 text-[11px] text-zinc-400 dark:text-zinc-600">
|
||||
<span className="h-1.5 w-1.5 translate-y-1.5 rounded-full bg-zinc-300 dark:bg-zinc-700" />
|
||||
미연결
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
51
features/settings/components/SettingsContainer.tsx
Normal file
51
features/settings/components/SettingsContainer.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { KisAuthForm } from "@/features/settings/components/KisAuthForm";
|
||||
import { useKisRuntimeStore } from "@/features/settings/store/use-kis-runtime-store";
|
||||
|
||||
/**
|
||||
* @description 설정 페이지 컨테이너입니다. KIS 연결 상태와 인증 폼을 카드 UI로 제공합니다.
|
||||
* @see app/(main)/settings/page.tsx 로그인 확인 후 이 컴포넌트를 렌더링합니다.
|
||||
* @see features/settings/components/KisAuthForm.tsx 실제 인증 입력/검증/해제를 담당합니다.
|
||||
*/
|
||||
export function SettingsContainer() {
|
||||
// 상태 정의: 연결 상태 표시용 전역 인증 상태를 구독합니다.
|
||||
const { verifiedCredentials, isKisVerified } = useKisRuntimeStore(
|
||||
useShallow((state) => ({
|
||||
verifiedCredentials: state.verifiedCredentials,
|
||||
isKisVerified: state.isKisVerified,
|
||||
})),
|
||||
);
|
||||
|
||||
return (
|
||||
<section className="mx-auto flex w-full max-w-5xl flex-col gap-5 p-4 md:p-6">
|
||||
{/* ========== 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>
|
||||
{isKisVerified ? (
|
||||
<span className="inline-flex items-center rounded-full bg-brand-100 px-2.5 py-1 text-xs font-semibold text-brand-700 dark:bg-brand-900/45 dark:text-brand-200">
|
||||
<span className="mr-1.5 h-2 w-2 rounded-full bg-brand-500" />
|
||||
연결됨 ({verifiedCredentials?.tradingEnv === "real" ? "실전" : "모의"})
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center rounded-full bg-brand-50 px-2.5 py-1 text-xs font-semibold text-brand-700 dark:bg-brand-900/30 dark:text-brand-200">
|
||||
<span className="mr-1.5 h-2 w-2 rounded-full bg-brand-300 dark:bg-brand-500/70" />
|
||||
미연결
|
||||
</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 />
|
||||
</article>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
192
features/settings/store/use-kis-runtime-store.ts
Normal file
192
features/settings/store/use-kis-runtime-store.ts
Normal file
@@ -0,0 +1,192 @@
|
||||
"use client";
|
||||
|
||||
import { fetchKisWebSocketApproval } from "@/features/settings/apis/kis-auth.api";
|
||||
import type { KisTradingEnv } from "@/features/trade/types/trade.types";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
import { create } from "zustand";
|
||||
|
||||
/**
|
||||
* @file features/settings/store/use-kis-runtime-store.ts
|
||||
* @description Stores KIS input, verification, and websocket connection state.
|
||||
* @see features/trade/hooks/useKisTradeWebSocket.ts
|
||||
*/
|
||||
export interface KisRuntimeCredentials {
|
||||
appKey: string;
|
||||
appSecret: string;
|
||||
tradingEnv: KisTradingEnv;
|
||||
accountNo: string;
|
||||
}
|
||||
|
||||
interface KisWsConnection {
|
||||
approvalKey: string;
|
||||
wsUrl: string;
|
||||
}
|
||||
|
||||
interface KisRuntimeStoreState {
|
||||
kisTradingEnvInput: KisTradingEnv;
|
||||
kisAppKeyInput: string;
|
||||
kisAppSecretInput: string;
|
||||
kisAccountNoInput: string;
|
||||
|
||||
verifiedCredentials: KisRuntimeCredentials | null;
|
||||
isKisVerified: boolean;
|
||||
tradingEnv: KisTradingEnv;
|
||||
|
||||
wsApprovalKey: string | null;
|
||||
wsUrl: string | null;
|
||||
}
|
||||
|
||||
interface KisRuntimeStoreActions {
|
||||
setKisTradingEnvInput: (tradingEnv: KisTradingEnv) => void;
|
||||
setKisAppKeyInput: (appKey: string) => void;
|
||||
setKisAppSecretInput: (appSecret: string) => void;
|
||||
setKisAccountNoInput: (accountNo: string) => void;
|
||||
setVerifiedKisSession: (
|
||||
credentials: KisRuntimeCredentials,
|
||||
tradingEnv: KisTradingEnv,
|
||||
) => void;
|
||||
invalidateKisVerification: () => void;
|
||||
clearKisRuntimeSession: (tradingEnv: KisTradingEnv) => void;
|
||||
getOrFetchWsConnection: () => Promise<KisWsConnection | null>;
|
||||
}
|
||||
|
||||
const INITIAL_STATE: KisRuntimeStoreState = {
|
||||
kisTradingEnvInput: "real",
|
||||
kisAppKeyInput: "",
|
||||
kisAppSecretInput: "",
|
||||
kisAccountNoInput: "",
|
||||
verifiedCredentials: null,
|
||||
isKisVerified: false,
|
||||
tradingEnv: "real",
|
||||
wsApprovalKey: null,
|
||||
wsUrl: null,
|
||||
};
|
||||
|
||||
const RESET_VERIFICATION_STATE = {
|
||||
verifiedCredentials: null,
|
||||
isKisVerified: false,
|
||||
wsApprovalKey: null,
|
||||
wsUrl: null,
|
||||
};
|
||||
|
||||
let wsConnectionPromise: Promise<KisWsConnection | null> | null = null;
|
||||
|
||||
/**
|
||||
* @description Runtime store for KIS session.
|
||||
* @see features/settings/components/KisAuthForm.tsx
|
||||
*/
|
||||
export const useKisRuntimeStore = create<
|
||||
KisRuntimeStoreState & KisRuntimeStoreActions
|
||||
>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
...INITIAL_STATE,
|
||||
|
||||
setKisTradingEnvInput: (tradingEnv) =>
|
||||
set({
|
||||
kisTradingEnvInput: tradingEnv,
|
||||
...RESET_VERIFICATION_STATE,
|
||||
}),
|
||||
|
||||
setKisAppKeyInput: (appKey) =>
|
||||
set({
|
||||
kisAppKeyInput: appKey,
|
||||
...RESET_VERIFICATION_STATE,
|
||||
}),
|
||||
|
||||
setKisAppSecretInput: (appSecret) =>
|
||||
set({
|
||||
kisAppSecretInput: appSecret,
|
||||
...RESET_VERIFICATION_STATE,
|
||||
}),
|
||||
|
||||
setKisAccountNoInput: (accountNo) =>
|
||||
set({
|
||||
kisAccountNoInput: accountNo,
|
||||
...RESET_VERIFICATION_STATE,
|
||||
}),
|
||||
|
||||
setVerifiedKisSession: (credentials, tradingEnv) =>
|
||||
set({
|
||||
verifiedCredentials: credentials,
|
||||
isKisVerified: true,
|
||||
tradingEnv,
|
||||
wsApprovalKey: null,
|
||||
wsUrl: null,
|
||||
}),
|
||||
|
||||
invalidateKisVerification: () =>
|
||||
set({
|
||||
...RESET_VERIFICATION_STATE,
|
||||
}),
|
||||
|
||||
clearKisRuntimeSession: (tradingEnv) =>
|
||||
set({
|
||||
kisTradingEnvInput: tradingEnv,
|
||||
kisAppKeyInput: "",
|
||||
kisAppSecretInput: "",
|
||||
kisAccountNoInput: "",
|
||||
...RESET_VERIFICATION_STATE,
|
||||
tradingEnv,
|
||||
}),
|
||||
|
||||
getOrFetchWsConnection: async () => {
|
||||
const { wsApprovalKey, wsUrl, verifiedCredentials } = get();
|
||||
|
||||
if (wsApprovalKey && wsUrl) {
|
||||
return { approvalKey: wsApprovalKey, wsUrl };
|
||||
}
|
||||
|
||||
if (!verifiedCredentials) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (wsConnectionPromise) {
|
||||
return wsConnectionPromise;
|
||||
}
|
||||
|
||||
wsConnectionPromise = (async () => {
|
||||
try {
|
||||
const data = await fetchKisWebSocketApproval(verifiedCredentials);
|
||||
if (!data.approvalKey || !data.wsUrl) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const nextConnection = {
|
||||
approvalKey: data.approvalKey,
|
||||
wsUrl: data.wsUrl,
|
||||
} satisfies KisWsConnection;
|
||||
|
||||
set({
|
||||
wsApprovalKey: nextConnection.approvalKey,
|
||||
wsUrl: nextConnection.wsUrl,
|
||||
});
|
||||
|
||||
return nextConnection;
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return null;
|
||||
} finally {
|
||||
wsConnectionPromise = null;
|
||||
}
|
||||
})();
|
||||
|
||||
return wsConnectionPromise;
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: "autotrade-kis-runtime-store",
|
||||
storage: createJSONStorage(() => localStorage),
|
||||
partialize: (state) => ({
|
||||
kisTradingEnvInput: state.kisTradingEnvInput,
|
||||
kisAppKeyInput: state.kisAppKeyInput,
|
||||
kisAppSecretInput: state.kisAppSecretInput,
|
||||
kisAccountNoInput: state.kisAccountNoInput,
|
||||
verifiedCredentials: state.verifiedCredentials,
|
||||
isKisVerified: state.isKisVerified,
|
||||
tradingEnv: state.tradingEnv,
|
||||
// wsApprovalKey/wsUrl are kept in memory only (expiration-sensitive).
|
||||
}),
|
||||
},
|
||||
),
|
||||
);
|
||||
Reference in New Issue
Block a user