feat: 멀티테넌트 1단계 — 사용자별 KIS 계좌·포트폴리오·수동매매 (MULTI_TENANT_ENABLED 기본 OFF)
설계: docs/multi_tenant_design.md / 검수: docs/multi_tenant_phase1_review.md (High 0, MT=False 배포 가능)
데이터·인프라
- user_kis_credentials(Fernet 암호화, PBKDF2 키 파생, key_version), stock_bans_v2 신설,
portfolio/trade_history/active_trades/trade_journals/trading_sessions 등 user_id nullable 추가
- alembic 0009~0011(idempotent, legacy owner 백필). main.py 기동 시 portfolio.user_id 스키마 검사(H1)
- Jenkinsfile: DB Migration 을 Deploy 앞으로, alembic 이력 없으면 stamp 0008 후 upgrade(N1)
- bootstrap: users 비어 있으면 BOOTSTRAP_ADMIN_* 로 관리자 시드 + .env KIS 자격증명 이관 + 백필(SAVEPOINT)
백엔드
- core/crypto.py, core/tenant_auth.py(get_current_user — 비활성 사용자 401, API 키→legacy owner,
deny_non_owner_session_when_mt), core/dt_utils.py
- services/tenant: context, kis_pool, registry(UserContextRegistry, 락 최소화·복호화 to_thread), risk_factory
- KoreaInvestmentAPI.for_user(사용자별 인스턴스, 토큰캐시 users/{id}/, 시세는 공용 위임)
- trade_executor.safe_place_order_v2(사용자별 락/세마포어, legacy ctx 는 기존 키)
- mdd_manager/loss_tracker _v2 + ban_until tz-aware/naive 경계 정규화(레거시 경로 버그 포함 수정)
- db_worker: payload user_id 옵션 필터, upsert_stock_ban_v2, legacy ActiveTrade 조회 LIMIT 1
- API: /account/credentials(등록·마스킹조회·삭제·연결테스트·자동매매), /auth/admin/tenant/*,
/portfolio/v2(조회·요약·sync·buy·sell), /trades/v2(+pending). PortfolioResponse Optional 수정
프론트
- /account 내 계좌 설정, useTenantMode(세션=v2 / API키=legacy, 미확정 시 쿼리·버튼 비활성),
계좌 미등록 인라인 안내, v2 매수/매도/거래이력 분기
테스트: tests/integration(격리 Postgres, KIS 전면 mock) 20 passed / 1 xfailed(0012 이전 제약)
2단계(스케줄러 사용자화·legacy 라우터 격리) 전까지 MULTI_TENANT_ENABLED=True 전환 금지
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -25,13 +25,17 @@ import api from '../lib/api'
|
||||
import { useWebSocket } from '../hooks/useWebSocket'
|
||||
import { usePortfolioData } from '../hooks/usePortfolioData'
|
||||
import { useMarketData } from '../hooks/useMarketData'
|
||||
import { useTradeActions } from '../hooks/useTradeActions'
|
||||
import { useTradeActions, TradeActionError } from '../hooks/useTradeActions'
|
||||
import { useAccountSetupStatus } from '../hooks/useAccountSetupStatus'
|
||||
import { useTenantMode } from '../lib/tenant'
|
||||
import { getTradesV2 } from '../lib/api'
|
||||
import { PortfolioSummary } from '../components/PortfolioSummary'
|
||||
import PortfolioPanel from '../components/PortfolioPanel'
|
||||
import ChartPanel, { AiAnalysisPanel } from '../components/ChartPanel'
|
||||
import OrderbookPanel from '../components/OrderbookPanel'
|
||||
import RecommendationPanel from '../components/RecommendationPanel'
|
||||
import JournalPanel from '../components/JournalPanel'
|
||||
import AccountSetupNotice from '../components/AccountSetupNotice'
|
||||
import { CandleData, Position, TradeHistory } from '../types/trading'
|
||||
import { isUsStock } from '../utils/stockUtils'
|
||||
import './Dashboard.css'
|
||||
@@ -123,8 +127,16 @@ const Dashboard = () => {
|
||||
portfolioSummary,
|
||||
portfolioSummaryError,
|
||||
invalidatePortfolio,
|
||||
accountSetupRequired,
|
||||
accountSetupMessage,
|
||||
} = usePortfolioData()
|
||||
|
||||
// v2(로그인 세션) 사용자의 KIS 계좌 등록/검증 상태 — 매수/매도 시도 전 선제 안내용
|
||||
const accountStatus = useAccountSetupStatus()
|
||||
const { mode: tenantMode } = useTenantMode()
|
||||
// 매수/매도 액션 중 계좌 미등록/미검증(400/423)을 받으면 배너로 노출 (alert 대체)
|
||||
const [tradeAccountNotice, setTradeAccountNotice] = useState<string | null>(null)
|
||||
|
||||
// Market data hook (with throttled live prices and market update handler)
|
||||
const {
|
||||
livePrices,
|
||||
@@ -210,7 +222,42 @@ const Dashboard = () => {
|
||||
}, [processChartData])
|
||||
|
||||
// Trade actions hook
|
||||
const { handleSell, handleBuy, resetPendingTrades } = useTradeActions()
|
||||
// isReady=false(useTenantMode 확정 전)면 매수/매도/미체결정리 버튼을 모두 disabled 처리
|
||||
const { handleSell, handleBuy, resetPendingTrades, isReady: tradeActionsReady } = useTradeActions()
|
||||
|
||||
// 계좌 미등록/미검증(400/423)은 상단 배너로 흡수하고, 그 외 에러는 그대로 전파해
|
||||
// 각 패널의 기존 alert 처리(다른 실패 사유)가 계속 동작하도록 한다.
|
||||
const handleBuyGuarded = useCallback(
|
||||
async (stockCode: string, stockName: string) => {
|
||||
try {
|
||||
await handleBuy(stockCode, stockName)
|
||||
} catch (error: unknown) {
|
||||
const err = error as TradeActionError
|
||||
if (err.isAccountSetupRequired) {
|
||||
setTradeAccountNotice(err.response?.data?.detail || '자동매매가 비활성화 상태입니다. 내 계좌 설정에서 계좌를 등록·검증하세요.')
|
||||
return
|
||||
}
|
||||
throw error
|
||||
}
|
||||
},
|
||||
[handleBuy]
|
||||
)
|
||||
|
||||
const handleSellGuarded = useCallback(
|
||||
async (stockCode: string, stockName: string, quantity: number) => {
|
||||
try {
|
||||
await handleSell(stockCode, stockName, quantity)
|
||||
} catch (error: unknown) {
|
||||
const err = error as TradeActionError
|
||||
if (err.isAccountSetupRequired) {
|
||||
setTradeAccountNotice(err.response?.data?.detail || '자동매매가 비활성화 상태입니다. 내 계좌 설정에서 계좌를 등록·검증하세요.')
|
||||
return
|
||||
}
|
||||
throw error
|
||||
}
|
||||
},
|
||||
[handleSell]
|
||||
)
|
||||
|
||||
// Subscribe to market data via WebSocket
|
||||
// reconnect 감지: wsConnected가 false→true 전환 시 강제 재구독
|
||||
@@ -352,10 +399,13 @@ const Dashboard = () => {
|
||||
|
||||
// 거래 이력 - 30초 (자동매매 체결 감지용)
|
||||
const { data: tradeHistory } = useQuery({
|
||||
queryKey: ['trade-history'],
|
||||
queryKey: ['trade-history', tenantMode],
|
||||
queryFn: async () => {
|
||||
const data = (await api.get('/trades', { params: { limit: 50 } }))
|
||||
.data as TradeHistory[]
|
||||
const data = (
|
||||
tenantMode === 'v2'
|
||||
? await getTradesV2({ limit: 50 })
|
||||
: await api.get('/trades', { params: { limit: 50 } })
|
||||
).data as TradeHistory[]
|
||||
|
||||
const seen = new Set<number>()
|
||||
return data
|
||||
@@ -366,6 +416,8 @@ const Dashboard = () => {
|
||||
})
|
||||
.slice(0, 20)
|
||||
},
|
||||
// M5: mode 미확정(undefined) 동안은 v2/legacy 어느 쪽으로도 조회하지 않음
|
||||
enabled: tenantMode !== undefined,
|
||||
staleTime: 0,
|
||||
refetchInterval: isMarketOpen ? 30000 : false,
|
||||
refetchOnWindowFocus: true,
|
||||
@@ -719,7 +771,16 @@ const Dashboard = () => {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<PortfolioSummary summary={liveSummary} error={portfolioSummaryError?.message ?? null} todayTradeStats={todayTradeStats} />
|
||||
{tradeAccountNotice && (
|
||||
<AccountSetupNotice message={tradeAccountNotice} className="mb-2" />
|
||||
)}
|
||||
<PortfolioSummary
|
||||
summary={liveSummary}
|
||||
error={portfolioSummaryError?.message ?? null}
|
||||
todayTradeStats={todayTradeStats}
|
||||
accountSetupRequired={accountSetupRequired || accountStatus.required}
|
||||
accountSetupMessage={accountSetupMessage || accountStatus.message}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-12 gap-3 flex-1 min-h-0">
|
||||
@@ -732,7 +793,10 @@ const Dashboard = () => {
|
||||
selectedStock={selectedStock}
|
||||
onSelectStock={handleSelectStock}
|
||||
onRefetchAiAnalysis={stableRefetchAiAnalysis}
|
||||
onSell={handleSell}
|
||||
onSell={handleSellGuarded}
|
||||
sellDisabled={!tradeActionsReady}
|
||||
accountSetupRequired={accountSetupRequired || accountStatus.required}
|
||||
accountSetupMessage={accountSetupMessage || accountStatus.message}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -770,12 +834,14 @@ const Dashboard = () => {
|
||||
heldStockCodes={heldStockCodes}
|
||||
pendingBuyStockCodes={pendingBuyStockCodes}
|
||||
livePrices={livePrices}
|
||||
onBuy={handleBuy}
|
||||
onBuy={handleBuyGuarded}
|
||||
buyDisabled={!tradeActionsReady}
|
||||
/>
|
||||
<JournalPanel
|
||||
journals={journals}
|
||||
tradeHistory={tradeHistory}
|
||||
onResetPending={resetPendingTrades}
|
||||
resetDisabled={!tradeActionsReady}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user