prepare.py 8.46 KB
#!/usr/bin/env python3
"""将 data/F-XX.json 合并为 planning-state.json,预计算 tab_buttons/tab_contents/coverage_rows"""
import json, os, re

DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
OUTPUT = os.path.join(os.path.dirname(__file__), "planning-state.json")

FEATURE_FILES = [
    "F-01-model-providers-and-accounts.json",
    "F-02-call-strategy-management.json",
    "F-03-prompt-templates.json",
    "F-04-call-and-task-records.json",
    "F-05-call-statistics.json",
    "F-06-api-auth-users.json",
    "F-07-word-bank.json",
    "F-08-call-orchestration.json",
    "F-09-llm-adapter.json",
    "F-10-async-task-worker.json",
    "F-11-log-storage.json",
]

TAB_LABELS = {
    "admin": "管理后台",
    "user": "用户端",
    "api": "API 客户端",
    "other": "系统/运维",
}

TAG_LABELS = {
    "receive": "接收请求",
    "validate": "参数校验",
    "query": "查询",
    "write": "写入",
    "return": "返回结果",
}

def build_tab_buttons(scenarios):
    """构建 tab 导航按钮 HTML"""
    tabs = {}
    for s in scenarios:
        t = s.get("tab", "admin")
        if t not in tabs:
            tabs[t] = {"label": TAB_LABELS.get(t, t), "count": 0}
        tabs[t]["count"] += len(s.get("steps", []))
    
    buttons = ""
    first = True
    for tab_id in sorted(tabs.keys(), key=lambda x: ["admin","user","api","other"].index(x) if x in ["admin","user","api","other"] else 99):
        t = tabs[tab_id]
        active = " active" if first else ""
        buttons += f'<button class="tab-btn{active}" onclick="switchTab(event, \'tab-{tab_id}\')">{t["label"]} ({t["count"]})</button>\n'
        first = False
    return buttons

def build_tab_contents(scenarios):
    """构建 tab 内容面板 HTML"""
    tabs_content = {}
    for s in scenarios:
        t = s.get("tab", "admin")
        if t not in tabs_content:
            tabs_content[t] = []
        tabs_content[t].append(s)
    
    contents = ""
    first_tab = True
    for tab_id in sorted(tabs_content.keys(), key=lambda x: ["admin","user","api","other"].index(x) if x in ["admin","user","api","other"] else 99):
        active = " active" if first_tab else ""
        contents += f'<div class="tab-content{active}" id="tab-{tab_id}">\n'
        for s in tabs_content[tab_id]:
            contents += build_scenario_card(s)
        contents += '</div>\n'
        first_tab = False
    return contents

def build_scenario_card(scenario):
    """构建单个场景卡片 HTML"""
    req = "✅ 必须" if scenario.get("required", False) else "⬜ 可选"
    html = '<div class="scenario-card">\n'
    html += f'<div class="scenario-header"><span class="scenario-title">{scenario["title"]}</span><span class="badge badge-{"p0" if scenario.get("required") else "p2"}">{req}</span></div>\n'
    html += f'<div class="scenario-meta"><strong>前置条件:</strong>{scenario.get("precondition", "无")}</div>\n'
    for step in scenario.get("steps", []):
        html += build_step_card(step)
    html += f'<div class="scenario-expect"><span class="scenario-expect-label">✅ 预期结果</span>{scenario.get("expect", "")}</div>\n'
    html += '</div>\n'
    return html

def build_step_card(step):
    """构建单个步骤卡片 HTML"""
    status = step.get("status", "notimpl")
    impl_class = "impl-not" if status == "notimpl" else "impl-done"
    impl_label = "未实现" if status == "notimpl" else "已实现"
    impl_color = "#f59e0b" if status == "notimpl" else "#10b981"
    
    html = f'<div class="step-card {impl_class}">\n'
    
    # Header
    html += '<div class="step-header">\n<div class="step-header-left">\n'
    html += f'<span class="op-badge op-badge-{"admin" if step.get("tab")=="admin" else "external" if step.get("tab")=="api" else "system"}" onclick="copyOP(\'{step.get("op","")}\')" title="点击复制 OP 编号">{step.get("op","")}</span>\n'
    html += f'<span class="impl-status {impl_class}"><span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:{impl_color};"></span> {impl_label}</span>\n'
    html += '</div>\n<div class="step-header-right">\n'
    
    # Nav breadcrumb
    for i, nav_item in enumerate(step.get("nav", [])):
        active = " active" if i == len(step.get("nav", [])) - 1 else ""
        html += f'<span class="crumb{active}">{nav_item}</span>'
        if i < len(step.get("nav", [])) - 1:
            html += '<span class="crumb-arrow">›</span>'
    
    html += '</div>\n</div>\n'
    
    # Changelog
    changelog = step.get("changelog")
    if changelog:
        html += '<div class="step-changelog-row">\n'
        html += f'<span class="op-changelog-new">变更</span>'
        html += f'<span class="op-changelog-label">关联:</span><span class="op-changelog-id">{changelog.get("id","")}</span>'
        html += f'<span class="op-changelog-label">日期:</span><span class="op-changelog-date">{changelog.get("date","")}</span>'
        html += f'<span class="op-changelog-label">原因:</span><span class="op-changelog-reason">{changelog.get("reason","")}</span>'
        html += '</div>\n'
    
    # Body - Actions + Backend in two columns
    html += '<div class="step-body">\n<div style="display:grid;grid-template-columns:1fr 2fr;gap:20px;">\n'
    
    # Actions column
    html += '<div>\n<span class="step-label">👆 操作步骤</span>\n<ol class="action-list">\n'
    for action in step.get("actions", []):
        html += f'<li>{action}</li>\n'
    html += '</ol>\n</div>\n'
    
    # Backend column
    html += '<div>\n<span class="step-label">⚙️ 后端处理逻辑</span>\n<ul class="backend-list">\n'
    for be in step.get("backend", []):
        tag = be.get("tag", "")
        text = be.get("text", "")
        tag_label = TAG_LABELS.get(tag, tag)
        html += f'<li><span class="backend-tag tag-{tag}">{tag_label}</span> {text}</li>\n'
    html += '</ul>\n</div>\n'
    
    # Expected
    html += '</div>\n</div>\n'
    html += '<div class="step-footer">\n'
    for exp in step.get("expected", []):
        html += f'<span class="badge" style="background:#f0fdf4;color:#166534;border:1px solid #bbf7d0;">{exp}</span>\n'
    html += '</div>\n'
    
    html += '</div>\n'
    return html

def build_coverage_rows(features):
    """构建 OP 覆盖总览行"""
    rows = ""
    for f in features:
        file_key = f.get("fileKey", f["id"])
        detail_page = f"{f['id']}-{file_key}-operation.html"
        total_ops = f.get("op_count", 0)
        rows += '<div class="coverage-row">\n'
        rows += '<div class="coverage-info">\n'
        rows += f'<span class="coverage-module"><span style="font-family:var(--font-mono);font-weight:700;color:var(--color-primary);">{f["id"]}</span> {f["title"]}</span>\n'
        rows += f'<span class="coverage-count">{total_ops} 个 OP</span>\n'
        rows += '</div>\n'
        rows += '<div class="coverage-bar"><div class="coverage-fill" style="width:0%"></div></div>\n'
        rows += f'<span class="coverage-pct">0 / {total_ops}</span>\n'
        rows += f'<a href="{detail_page}" class="coverage-detail-link">查看详情 →</a>\n'
        rows += '</div>\n'
    return rows

def main():
    features = []
    for fname in FEATURE_FILES:
        path = os.path.join(DATA_DIR, fname)
        if not os.path.exists(path):
            print(f"Warning: {fname} not found, skipping")
            continue
        with open(path, encoding="utf-8") as f:
            feat = json.load(f)
        
        # Pre-compute tab_buttons and tab_contents
        scenarios = feat.get("scenarios", [])
        feat["tab_buttons"] = build_tab_buttons(scenarios)
        feat["tab_contents"] = build_tab_contents(scenarios)
        feat["version"] = "1.0"
        features.append(feat)
    
    # Load overview.json for shared data
    overview_path = os.path.join(DATA_DIR, "overview.json")
    overview = {}
    if os.path.exists(overview_path):
        with open(overview_path, encoding="utf-8") as f:
            overview = json.load(f)
    
    # Build final output
    output = {
        "project": "llm-call-platform",
        "version": "1.0",
        "date": "2026-06-11",
        "test_env_rows": overview.get("test_env_rows", ""),
        "cleanup_rows": overview.get("cleanup_rows", ""),
        "coverage_rows": build_coverage_rows(features),
        "features": features,
    }
    
    with open(OUTPUT, "w", encoding="utf-8") as f:
        json.dump(output, f, ensure_ascii=False, indent=2)
    
    print(f"已生成 {OUTPUT},共 {len(features)} 个模块,{sum(f.get('op_count',0) for f in features)} 个 OP")

if __name__ == "__main__":
    main()