협상 카드 카탈로그 팝업 — 서버 카드 목록 API + 발동 중 하이라이트

- GET /v1/nego/cards: 일반 카드 9종(정본 nego_card.json) + 와일드카드 2종, 테스트 추가(15 통과)
- 엔진 판단 패널 '전체 카드' 버튼 → 모달: ID·이름·스크립트, 현재 발동 카드 하이라이트,
  변수 {…} 안내, 로딩·실패 상태, X/배경/ESC 닫기

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UFZ7JWdwCaQAwNYJErL8pP
This commit is contained in:
민헌andClaude Fable 5 committed 2026-08-31 15:07:57 +09:00
1 parent 9f5bf64b02
commit 7bcd7a0f39
5 files changed
+166 -1

No files matched your search

+108
View File
@@ -0,0 +1,108 @@
import { useRef, useState } from 'react'
import { fetchCards, type CardCatalogResponse, type CardInfo } from '../lib/api'
/**
* 협상 카드 카탈로그 팝업 — 엔진이 보유한 카드 전체를 정본(서버)에서 받아 보여준다.
* 현재 발동 중인 카드는 하이라이트된다.
*/
export function CardCatalog({ activeCardId }: { activeCardId: string | null }) {
const dialogRef = useRef<HTMLDialogElement>(null)
const [data, setData] = useState<CardCatalogResponse | null>(null)
const [failed, setFailed] = useState(false)
const open = async () => {
dialogRef.current?.showModal()
if (data) return
try {
setFailed(false)
setData(await fetchCards())
} catch {
setFailed(true)
}
}
const CardRow = ({ card }: { card: CardInfo }) => {
const active = card.card_id === activeCardId
return (
<li
className={`rounded-field p-3.5 ${
active ? 'bg-primary/6 ring-1 ring-primary/30' : 'bg-base-200/50'
}`}
>
<div className="flex flex-wrap items-center gap-2">
<span className="num rounded-full bg-base-100 px-2 py-px font-mono text-[11px] font-semibold text-base-content/55">
{card.card_id}
</span>
<span className="text-sm font-bold">{card.card_name}</span>
{active && (
<span className="rounded-full bg-primary/10 px-2 py-px text-[11px] font-semibold text-primary">
발동 중
</span>
)}
</div>
<p className="mt-2 text-[13px] leading-relaxed whitespace-pre-line text-base-content/60">
{card.script}
</p>
</li>
)
}
return (
<>
<button type="button" onClick={open} className="btn btn-ghost btn-xs -mr-1 text-base-content/55">
전체 카드
</button>
<dialog ref={dialogRef} className="modal">
<div className="modal-box max-w-xl rounded-box p-0">
<div className="flex items-start justify-between gap-3 border-b border-base-300/60 px-6 py-4">
<div>
<h3 className="text-base font-bold">협상 카드 목록</h3>
<p className="mt-0.5 text-[13px] text-base-content/55">
엔진이 상황에 맞춰 꺼내 쓰는 카드입니다. {'{...}'} 부분은 협상 시점의 실제 값으로 채워집니다.
</p>
</div>
<form method="dialog">
<button className="btn btn-ghost btn-sm btn-circle" aria-label="닫기">
<svg viewBox="0 0 12 12" className="w-3.5" aria-hidden>
<path d="M1 1l10 10M11 1L1 11" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
</svg>
</button>
</form>
</div>
<div className="max-h-[65vh] overflow-y-auto px-6 py-4">
{failed ? (
<p className="py-6 text-center text-[13px] text-base-content/55">
카드 목록을 불러오지 못했어요. 엔진 연결을 확인한 뒤 다시 열어 주세요.
</p>
) : !data ? (
<p className="flex items-center justify-center gap-2 py-6 text-[13px] text-base-content/55">
<span className="loading loading-dots loading-sm" aria-hidden />
카드 목록을 불러오고 있어요
</p>
) : (
<>
<h4 className="text-xs font-semibold text-base-content/45">
일반 협상 카드 {data.cards.length}종
</h4>
<ol className="mt-2 flex flex-col gap-2">
{data.cards.map((c) => <CardRow key={c.card_id} card={c} />)}
</ol>
<h4 className="mt-5 text-xs font-semibold text-base-content/45">
와일드카드 {data.wild_cards.length}종 — 마지막 라운드 승부수
</h4>
<ol className="mt-2 flex flex-col gap-2">
{data.wild_cards.map((c) => <CardRow key={c.card_id} card={c} />)}
</ol>
</>
)}
</div>
</div>
<form method="dialog" className="modal-backdrop">
<button aria-label="닫기">닫기</button>
</form>
</dialog>
</>
)
}
+2 -1
View File
@@ -1,6 +1,7 @@
import type { ChatMetadata } from '../lib/api'
import type { DemoCase } from '../content/cases'
import type { NegoState, Round } from '../App'
import { CardCatalog } from './CardCatalog'
const FLOW = ['서비스안내', '담당자확인', '협상품목안내', '가격협상', '협상종료']
const MAX_ROUNDS = 6 // 시작 제안 1회 + 재협상 5회(엔진 MAX_ITERATION)
@@ -113,7 +114,7 @@ export function Dashboard({
)}
</Panel>
<Panel title="엔진 판단">
<Panel title="엔진 판단" right={<CardCatalog activeCardId={meta?.card_id ?? null} />}>
{meta ? (
<dl className="flex flex-col gap-4">
{/* 이 패널의 주인공 — 지금 발동 중인 협상 카드 */}
+17
View File
@@ -63,6 +63,23 @@ export async function invalidateSession(sessionId: string): Promise<void> {
})
}
export interface CardInfo {
card_id: string
card_name: string
script: string
}
export interface CardCatalogResponse {
cards: CardInfo[]
wild_cards: CardInfo[]
}
export async function fetchCards(): Promise<CardCatalogResponse> {
const res = await fetch('/api/v1/nego/cards')
if (!res.ok) throw new Error(`서버 응답 오류 (${res.status})`)
return res.json()
}
export async function serverAlive(): Promise<boolean> {
try {
const res = await fetch('/api/health')
+29
View File
@@ -1,11 +1,20 @@
"""상태 확인 엔드포인트."""
import json
from fastapi import APIRouter, Request
from common.paths import RESOURCES_DIR
from router.v1.nego.protocol import HealthResponse
router = APIRouter(tags=["admin"])
# 와일드카드는 스텝 ID로 관리되므로 표시용 이름을 여기서 부여한다
WILD_CARD_LABELS = {
"wild_card_1pct": "1% 추가 제안",
"wild_card_budget": "재원부족 제안",
}
@router.get("/health", response_model=HealthResponse)
async def health_check():
@@ -31,3 +40,23 @@ async def get_config(request: Request):
},
"cards": engine.card_script_repo.count(),
}
@router.get("/v1/nego/cards")
async def list_cards(request: Request):
"""협상 카드 전체 목록 — 데모 콘솔의 카드 팝업용 (정본 = resources/cards)."""
engine = request.app.state.engine
cards = [
{"card_id": c.get("card_id"), "card_name": c.get("card_name"), "script": c.get("script", "")}
for c in engine.card_script_repo.find_all()
]
wild_cards = []
try:
wild = json.loads((RESOURCES_DIR / "cards" / "wild_card.json").read_text(encoding="utf-8"))
wild_cards = [
{"card_id": key, "card_name": WILD_CARD_LABELS.get(key, key), "script": item.get("script", "")}
for key, item in wild.items()
]
except (OSError, json.JSONDecodeError):
pass
return {"cards": cards, "wild_cards": wild_cards}
+10
View File
@@ -119,3 +119,13 @@ def test_session_invalidate():
json={"session_id": "TEST-01", "reason": "테스트"})
assert res.status_code == 200
assert res.json()["status"] == "ok"
def test_cards_endpoint():
"""카드 목록 — 데모 카드 팝업용. 일반 9종 + 와일드 2종, 이름 필수."""
res = client.get("/v1/nego/cards")
assert res.status_code == 200
body = res.json()
assert len(body["cards"]) == 9
assert all(c["card_id"] and c["card_name"] and c["script"] for c in body["cards"])
assert {w["card_id"] for w in body["wild_cards"]} == {"wild_card_1pct", "wild_card_budget"}