Prechádzať zdrojové kódy

feat:console.html页面

tanjingyu 4 mesiacov pred
rodič
commit
6a18cad827
3 zmenil súbory, kde vykonal 1000 pridanie a 2 odobranie
  1. 75 1
      app/main.py
  2. 1 1
      app/models.py
  3. 924 0
      app/static/console.html

+ 75 - 1
app/main.py

@@ -1,6 +1,7 @@
-from fastapi import FastAPI, BackgroundTasks, Request, Depends, HTTPException, Header
+from fastapi import FastAPI, BackgroundTasks, Request, Depends, HTTPException, Header, Query
 from fastapi.responses import FileResponse
 from sqlalchemy.orm import Session
+from sqlalchemy import func as sqlfunc
 from typing import List, Optional
 from app.config import settings
 from app.database import engine, Base, get_db, SessionLocal
@@ -86,6 +87,12 @@ def read_root():
     return FileResponse(os.path.join(STATIC_DIR, "index.html"), media_type="text/html")
 
 
+@app.get("/console")
+def console_page():
+    """Serve the console UI."""
+    return FileResponse(os.path.join(STATIC_DIR, "console.html"), media_type="text/html")
+
+
 @app.get("/api/health")
 def health_check():
     """Health check endpoint."""
@@ -157,6 +164,73 @@ def get_project_by_name(project_name: str, db: Session = Depends(get_db)):
     return project
 
 
+# ==================== Console APIs ====================
+
+@app.get("/stages/all")
+def get_all_stages(db: Session = Depends(get_db)):
+    """Get all stages across all projects with version counts."""
+    results = db.query(
+        DataVersion.stage,
+        DataVersion.project_id,
+        Project.project_name,
+        sqlfunc.count(DataVersion.id).label("count")
+    ).join(Project).group_by(
+        DataVersion.stage, DataVersion.project_id, Project.project_name
+    ).all()
+    return [{
+        "name": r[0],
+        "project_id": r[1],
+        "project_name": r[2],
+        "version_count": r[3]
+    } for r in results]
+
+
+@app.get("/projects/{project_id}/stages")
+def get_project_stages(project_id: str, db: Session = Depends(get_db)):
+    """Get all unique stages for a project with version counts."""
+    results = db.query(
+        DataVersion.stage,
+        sqlfunc.count(DataVersion.id).label("count")
+    ).filter(
+        DataVersion.project_id == project_id
+    ).group_by(DataVersion.stage).all()
+    return [{"name": r[0], "version_count": r[1]} for r in results]
+
+
+@app.get("/projects/{project_id}/stage-files")
+def get_stage_files(
+    project_id: str,
+    stage: str = Query(...),
+    skip: int = 0,
+    limit: int = 20,
+    db: Session = Depends(get_db)
+):
+    """Get versions with files for a specific stage, ordered by newest first."""
+    versions = db.query(DataVersion).filter(
+        DataVersion.project_id == project_id,
+        DataVersion.stage == stage
+    ).order_by(DataVersion.created_at.desc()).offset(skip).limit(limit).all()
+
+    result = []
+    for v in versions:
+        files = db.query(DataFile).filter(DataFile.version_id == v.id).all()
+        result.append({
+            "version_id": v.id,
+            "commit_id": v.commit_id,
+            "author": v.author,
+            "created_at": v.created_at.isoformat() if v.created_at else None,
+            "files": [{
+                "id": f.id,
+                "name": f.relative_path.split("/")[-1] if f.relative_path else "",
+                "relative_path": f.relative_path,
+                "file_size": f.file_size,
+                "file_type": f.file_type,
+                "file_sha": f.file_sha,
+            } for f in files]
+        })
+    return result
+
+
 # ==================== Version APIs ====================
 
 @app.get("/projects/{project_id}/versions", response_model=List[schemas.DataVersionOut])

+ 1 - 1
app/models.py

@@ -26,7 +26,7 @@ class DataVersion(Base):
 
     id = Column(String(26), primary_key=True, default=generate_ulid)
     project_id = Column(String(26), ForeignKey("projects.id"))
-    stage = Column(String(50), nullable=False)
+    stage = Column(String(200), nullable=False)
     commit_id = Column(String(64), nullable=False)
     author = Column(String(50))
     manifest_snapshot = Column(Text)

+ 924 - 0
app/static/console.html

@@ -0,0 +1,924 @@
+<!DOCTYPE html>
+<html lang="zh-CN">
+
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Data Nexus - 数据控制台</title>
+    <meta name="description" content="Data Nexus 数据中台管理控制台">
+    <link rel="preconnect" href="https://fonts.googleapis.com">
+    <link
+        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap"
+        rel="stylesheet">
+    <style>
+        *,
+        *::before,
+        *::after {
+            margin: 0;
+            padding: 0;
+            box-sizing: border-box;
+        }
+
+        :root {
+            --bg-base: #080c18;
+            --bg-sidebar: #0c1222;
+            --bg-surface: #111827;
+            --bg-card: #151f32;
+            --bg-card-head: rgba(0, 0, 0, 0.2);
+            --bg-hover: rgba(255, 255, 255, 0.04);
+            --bg-active: rgba(99, 179, 237, 0.08);
+            --border: rgba(255, 255, 255, 0.06);
+            --border-card: rgba(255, 255, 255, 0.08);
+            --border-active: rgba(99, 179, 237, 0.35);
+            --text-primary: #e2e8f0;
+            --text-secondary: #8b9ab5;
+            --text-muted: #556477;
+            --accent: #63b3ed;
+            --accent-light: #90cdf4;
+            --accent-dim: rgba(99, 179, 237, 0.12);
+            --green: #68d391;
+            --green-dim: rgba(104, 211, 145, 0.12);
+            --orange: #f6ad55;
+            --orange-dim: rgba(246, 173, 85, 0.12);
+            --purple: #b794f4;
+            --radius: 8px;
+            --sidebar-w: 280px;
+        }
+
+        body {
+            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'PingFang SC', 'Microsoft YaHei', sans-serif;
+            background: var(--bg-base);
+            color: var(--text-primary);
+            height: 100vh;
+            overflow: hidden;
+            line-height: 1.5;
+        }
+
+        ::-webkit-scrollbar {
+            width: 5px;
+        }
+
+        ::-webkit-scrollbar-track {
+            background: transparent;
+        }
+
+        ::-webkit-scrollbar-thumb {
+            background: rgba(255, 255, 255, 0.08);
+            border-radius: 3px;
+        }
+
+        ::-webkit-scrollbar-thumb:hover {
+            background: rgba(255, 255, 255, 0.14);
+        }
+
+        /* Layout */
+        .app {
+            display: grid;
+            grid-template-columns: var(--sidebar-w) 1fr;
+            height: 100vh;
+        }
+
+        /* Sidebar */
+        .sidebar {
+            background: var(--bg-sidebar);
+            border-right: 1px solid var(--border);
+            display: flex;
+            flex-direction: column;
+            overflow: hidden;
+        }
+
+        .sidebar-header {
+            display: flex;
+            align-items: center;
+            gap: 10px;
+            padding: 20px 20px 16px;
+            flex-shrink: 0;
+        }
+
+        .sidebar-header svg {
+            width: 26px;
+            height: 26px;
+            color: var(--accent);
+            flex-shrink: 0;
+        }
+
+        .sidebar-header span {
+            font-size: 16px;
+            font-weight: 700;
+            background: linear-gradient(135deg, var(--accent-light), var(--purple));
+            -webkit-background-clip: text;
+            background-clip: text;
+            -webkit-text-fill-color: transparent;
+        }
+
+        .sidebar-section {
+            padding: 0 16px;
+            flex-shrink: 0;
+        }
+
+        .sidebar-label {
+            display: block;
+            font-size: 11px;
+            font-weight: 600;
+            color: var(--text-muted);
+            text-transform: uppercase;
+            letter-spacing: 0.8px;
+            padding: 12px 4px 8px;
+        }
+
+        .sidebar-divider {
+            height: 1px;
+            background: var(--border);
+            margin: 8px 16px;
+            flex-shrink: 0;
+        }
+
+        /* Project select */
+        .select-wrap {
+            position: relative;
+        }
+
+        .select-wrap::after {
+            content: '';
+            position: absolute;
+            right: 12px;
+            top: 50%;
+            transform: translateY(-50%);
+            border: 4px solid transparent;
+            border-top: 5px solid var(--text-muted);
+            pointer-events: none;
+        }
+
+        .project-select {
+            width: 100%;
+            padding: 9px 32px 9px 12px;
+            background: var(--bg-surface);
+            border: 1px solid var(--border);
+            border-radius: 6px;
+            color: var(--text-primary);
+            font-family: inherit;
+            font-size: 13px;
+            cursor: pointer;
+            appearance: none;
+            outline: none;
+            transition: border-color 0.2s;
+        }
+
+        .project-select:focus {
+            border-color: var(--accent);
+        }
+
+        .project-select option {
+            background: var(--bg-surface);
+            color: var(--text-primary);
+        }
+
+        /* Stage tree */
+        .stage-tree-wrap {
+            flex: 1;
+            overflow-y: auto;
+            padding: 0 8px 16px;
+        }
+
+        .tree-branch-header {
+            display: flex;
+            align-items: center;
+            gap: 4px;
+            padding: 7px 10px;
+            cursor: pointer;
+            border-radius: 6px;
+            transition: background 0.12s;
+            user-select: none;
+            font-size: 13px;
+            color: var(--text-secondary);
+        }
+
+        .tree-branch-header:hover {
+            background: var(--bg-hover);
+        }
+
+        .tree-arrow {
+            width: 16px;
+            height: 16px;
+            color: var(--text-muted);
+            transition: transform 0.2s;
+            flex-shrink: 0;
+        }
+
+        .tree-arrow.open {
+            transform: rotate(90deg);
+        }
+
+        .tree-children {
+            display: none;
+            padding-left: 8px;
+            margin-left: 12px;
+            border-left: 1px solid var(--border);
+        }
+
+        .tree-children.open {
+            display: block;
+        }
+
+        .tree-leaf {
+            display: flex;
+            align-items: center;
+            gap: 8px;
+            padding: 7px 10px 7px 12px;
+            cursor: pointer;
+            border-radius: 6px;
+            transition: all 0.12s;
+            font-size: 13px;
+            color: var(--text-secondary);
+        }
+
+        .tree-leaf:hover {
+            background: var(--bg-hover);
+            color: var(--text-primary);
+        }
+
+        .tree-leaf.active {
+            background: var(--bg-active);
+            color: var(--accent);
+            font-weight: 500;
+        }
+
+        .tree-dot {
+            width: 5px;
+            height: 5px;
+            border-radius: 50%;
+            background: var(--text-muted);
+            flex-shrink: 0;
+        }
+
+        .tree-leaf.active .tree-dot {
+            background: var(--accent);
+        }
+
+        .tree-count {
+            margin-left: auto;
+            font-size: 11px;
+            color: var(--text-muted);
+            background: rgba(255, 255, 255, 0.04);
+            padding: 1px 6px;
+            border-radius: 4px;
+        }
+
+        /* Content */
+        .content {
+            display: flex;
+            flex-direction: column;
+            height: 100vh;
+            overflow: hidden;
+        }
+
+        .content-header {
+            flex-shrink: 0;
+            padding: 18px 28px;
+            border-bottom: 1px solid var(--border);
+            background: rgba(12, 18, 34, 0.6);
+            backdrop-filter: blur(12px);
+            display: flex;
+            align-items: center;
+            justify-content: space-between;
+            min-height: 60px;
+        }
+
+        .stage-path {
+            display: flex;
+            align-items: center;
+            gap: 6px;
+            font-size: 14px;
+        }
+
+        .stage-path .sep {
+            color: var(--text-muted);
+            font-size: 11px;
+        }
+
+        .stage-path .seg {
+            color: var(--text-secondary);
+        }
+
+        .stage-path .seg:last-child {
+            color: var(--text-primary);
+            font-weight: 600;
+        }
+
+        .header-info {
+            font-size: 12px;
+            color: var(--text-muted);
+        }
+
+        .content-body {
+            flex: 1;
+            overflow-y: auto;
+            padding: 24px 28px;
+        }
+
+        /* Welcome state */
+        .state-box {
+            display: flex;
+            flex-direction: column;
+            align-items: center;
+            justify-content: center;
+            height: 100%;
+            text-align: center;
+            color: var(--text-muted);
+            padding: 40px;
+        }
+
+        .state-box svg {
+            width: 56px;
+            height: 56px;
+            margin-bottom: 20px;
+            opacity: 0.25;
+        }
+
+        .state-box h2 {
+            font-size: 17px;
+            font-weight: 600;
+            color: var(--text-secondary);
+            margin-bottom: 6px;
+        }
+
+        .state-box p {
+            font-size: 13px;
+        }
+
+        /* Spinner */
+        .spinner {
+            width: 28px;
+            height: 28px;
+            border: 3px solid var(--border);
+            border-top-color: var(--accent);
+            border-radius: 50%;
+            animation: spin 0.7s linear infinite;
+            margin-bottom: 16px;
+        }
+
+        @keyframes spin {
+            to {
+                transform: rotate(360deg);
+            }
+        }
+
+        .table-header {
+            display: grid;
+            grid-template-columns: minmax(200px, 3fr) 120px 140px 100px 80px;
+            gap: 16px;
+            padding: 12px 20px;
+            background: rgba(0, 0, 0, 0.2);
+            border-bottom: 1px solid var(--border);
+            font-size: 13px;
+            font-weight: 600;
+            color: var(--text-secondary);
+            position: sticky;
+            top: 0;
+            z-index: 10;
+        }
+
+        .table-body {
+            display: flex;
+            flex-direction: column;
+        }
+
+        /* File row grid */
+        .file-row {
+            display: grid;
+            grid-template-columns: minmax(200px, 3fr) 120px 140px 100px 80px;
+            gap: 16px;
+            align-items: center;
+            padding: 12px 20px;
+            border-bottom: 1px solid var(--border);
+            transition: background 0.1s;
+        }
+
+        .file-row:last-child {
+            border-bottom: none;
+        }
+
+        .file-row:hover {
+            background: var(--bg-hover);
+        }
+
+        .file-name-col {
+            display: flex;
+            align-items: center;
+            gap: 10px;
+            min-width: 0;
+            /* allows text truncation */
+        }
+
+        @keyframes fadeUp {
+            from {
+                opacity: 0;
+                transform: translateY(10px);
+            }
+
+            to {
+                opacity: 1;
+                transform: translateY(0);
+            }
+        }
+
+        .f-icon {
+            width: 18px;
+            height: 18px;
+            flex-shrink: 0;
+            color: var(--text-muted);
+        }
+
+        .f-name {
+            font-size: 13px;
+            color: var(--text-primary);
+            white-space: nowrap;
+            overflow: hidden;
+            text-overflow: ellipsis;
+        }
+
+        .f-size {
+            font-size: 11px;
+            color: var(--text-muted);
+            margin-left: 6px;
+        }
+
+        .col-text {
+            font-size: 13px;
+            color: var(--text-secondary);
+            white-space: nowrap;
+            overflow: hidden;
+            text-overflow: ellipsis;
+        }
+
+        .commit-tag {
+            font-family: 'JetBrains Mono', monospace;
+            color: var(--accent);
+        }
+
+        .btn-dl-wrap {
+            display: flex;
+            justify-content: flex-end;
+        }
+
+        .btn-dl {
+            display: inline-flex;
+            align-items: center;
+            gap: 4px;
+            padding: 4px 10px;
+            border-radius: 5px;
+            border: none;
+            background: var(--accent-dim);
+            color: var(--accent);
+            font-size: 12px;
+            font-family: inherit;
+            cursor: pointer;
+            transition: all 0.15s;
+            text-decoration: none;
+            flex-shrink: 0;
+        }
+
+        .btn-dl:hover {
+            background: rgba(99, 179, 237, 0.2);
+        }
+
+        .btn-dl svg {
+            width: 13px;
+            height: 13px;
+        }
+
+        /* File group (folder) */
+        .fg-header {
+            display: grid;
+            grid-template-columns: minmax(200px, 3fr) 120px 140px 100px 80px;
+            gap: 16px;
+            align-items: center;
+            padding: 12px 20px;
+            border-bottom: 1px solid var(--border);
+            cursor: pointer;
+            transition: background 0.1s;
+            user-select: none;
+        }
+
+        .fg-header:hover {
+            background: var(--bg-hover);
+        }
+
+        .fg-name-wrap {
+            display: flex;
+            align-items: center;
+            gap: 8px;
+            min-width: 0;
+        }
+
+        .fg-header:hover {
+            background: var(--bg-hover);
+        }
+
+        .fg-arrow {
+            width: 14px;
+            height: 14px;
+            color: var(--text-muted);
+            transition: transform 0.2s;
+            flex-shrink: 0;
+        }
+
+        .fg-arrow.open {
+            transform: rotate(90deg);
+        }
+
+        .fg-icon {
+            width: 18px;
+            height: 18px;
+            flex-shrink: 0;
+            color: var(--orange);
+        }
+
+        .fg-name {
+            font-size: 13px;
+            color: var(--text-primary);
+            font-weight: 500;
+        }
+
+        .fg-count {
+            font-size: 11px;
+            color: var(--text-muted);
+            background: rgba(255, 255, 255, 0.04);
+            padding: 1px 7px;
+            border-radius: 4px;
+            margin-left: 4px;
+        }
+
+        .fg-children {
+            display: none;
+            background: rgba(0, 0, 0, 0.1);
+        }
+
+        .fg-children.open {
+            display: block;
+        }
+
+        /* Load more */
+        .load-more {
+            display: flex;
+            justify-content: center;
+            padding: 16px;
+        }
+
+        .load-more-btn {
+            padding: 9px 28px;
+            border-radius: 6px;
+            border: 1px solid var(--border);
+            background: transparent;
+            color: var(--text-secondary);
+            font-family: inherit;
+            font-size: 13px;
+            cursor: pointer;
+            transition: all 0.2s;
+        }
+
+        .load-more-btn:hover {
+            background: var(--bg-hover);
+            color: var(--text-primary);
+            border-color: var(--border-active);
+        }
+
+        .load-more-btn:disabled {
+            opacity: 0.4;
+            cursor: default;
+        }
+    </style>
+</head>
+
+<body>
+    <div class="app">
+        <aside class="sidebar">
+            <div class="sidebar-header">
+                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
+                    <path
+                        d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z" />
+                    <polyline points="3.27 6.96 12 12.01 20.73 6.96" />
+                    <line x1="12" y1="22.08" x2="12" y2="12" />
+                </svg>
+                <span>Data Nexus</span>
+            </div>
+            <div class="sidebar-divider"></div>
+            <div class="stage-tree-wrap" id="stageTreeWrap"></div>
+        </aside>
+        <main class="content">
+            <div class="content-header">
+                <div class="stage-path" id="stagePath"><span class="seg" style="color:var(--text-muted)">选择左侧数据阶段</span>
+                </div>
+                <div class="header-info" id="headerInfo"></div>
+            </div>
+            <div class="content-body" id="contentBody">
+                <div class="state-box">
+                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
+                        <path
+                            d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z" />
+                        <polyline points="3.27 6.96 12 12.01 20.73 6.96" />
+                        <line x1="12" y1="22.08" x2="12" y2="12" />
+                    </svg>
+                    <h2>欢迎使用数据控制台</h2>
+                    <p>从左侧选择数据阶段,查看文件版本历史</p>
+                </div>
+            </div>
+        </main>
+    </div>
+
+    <script>
+        // ============ Icons ============
+        const IC = {
+            commit: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="4"/><line x1="1.05" y1="12" x2="7" y2="12"/><line x1="17.01" y1="12" x2="22.96" y2="12"/></svg>',
+            file: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>',
+            folder: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z"/></svg>',
+            download: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>',
+            chevron: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="9 18 15 12 9 6"/></svg>',
+        };
+
+        // ============ State ============
+        const PAGE_SIZE = 20;
+        let S = {
+            stages: [],       // raw stage data from /stages/all
+            stageProjectMap: {}, // stage name -> project_id
+            stage: null,
+            versions: [],
+            skip: 0,
+            hasMore: true,
+            loading: false,
+        };
+
+        const $ = id => document.getElementById(id);
+
+        // ============ Utils ============
+        function esc(s) { if (!s) return ''; const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
+        function fmtSize(b) {
+            if (!b && b !== 0) return '-';
+            const u = ['B', 'KB', 'MB', 'GB']; let i = 0, s = b;
+            while (s >= 1024 && i < u.length - 1) { s /= 1024; i++; }
+            return s.toFixed(i > 0 ? 1 : 0) + ' ' + u[i];
+        }
+        function fmtTime(iso) {
+            if (!iso) return '';
+            const d = new Date(iso), p = n => String(n).padStart(2, '0');
+            return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
+        }
+        function relTime(iso) {
+            if (!iso) return '';
+            const m = Math.floor((Date.now() - new Date(iso).getTime()) / 60000);
+            if (m < 1) return '刚刚'; if (m < 60) return m + ' 分钟前';
+            const h = Math.floor(m / 60); if (h < 24) return h + ' 小时前';
+            const d = Math.floor(h / 24); if (d < 30) return d + ' 天前';
+            return fmtTime(iso);
+        }
+        async function api(url) { const r = await fetch(url); if (!r.ok) throw new Error(r.status); return r.json(); }
+
+        // ============ Load All Stages ============
+        async function loadAllStages() {
+            $('stageTreeWrap').innerHTML = '<div style="padding:16px;text-align:center;"><div class="spinner" style="margin:0 auto 8px;"></div><span style="font-size:12px;color:var(--text-muted)">加载中...</span></div>';
+            try {
+                S.stages = await api('/stages/all');
+                // Build stage -> project_id mapping
+                S.stageProjectMap = {};
+                S.stages.forEach(st => { S.stageProjectMap[st.name] = st.project_id; });
+                renderStageTree();
+            } catch (e) { $('stageTreeWrap').innerHTML = '<div style="padding:16px;color:#fc8181;font-size:13px;">加载失败</div>'; }
+        }
+
+        // ============ Stage Tree ============
+        function buildTree(stages) {
+            const root = [];
+            for (const st of stages) {
+                const parts = st.name.split('/');
+                let cur = root;
+                for (let i = 0; i < parts.length; i++) {
+                    let node = cur.find(n => n.label === parts[i]);
+                    if (!node) {
+                        node = { label: parts[i], children: [] };
+                        cur.push(node);
+                    }
+                    if (i === parts.length - 1) {
+                        node.stage = st.name;
+                        node.count = st.version_count;
+                    }
+                    cur = node.children;
+                }
+            }
+            return root;
+        }
+
+        function renderStageTree() {
+            const tree = buildTree(S.stages);
+            $('stageTreeWrap').innerHTML = tree.length ? renderNodes(tree) : '<div style="padding:16px;font-size:13px;color:var(--text-muted)">暂无数据阶段</div>';
+        }
+
+        function renderNodes(nodes) {
+            let h = '';
+            for (const n of nodes) {
+                if (n.stage && n.children.length === 0) {
+                    // Leaf
+                    h += `<div class="tree-leaf" data-stage="${esc(n.stage)}" onclick="selectStage(this, '${esc(n.stage)}')">
+                <span class="tree-dot"></span>
+                <span>${esc(n.label)}</span>
+                <span class="tree-count">${n.count || ''}</span>
+            </div>`;
+                } else {
+                    // Branch (may also be a stage itself)
+                    const id = 'tb_' + Math.random().toString(36).substr(2, 6);
+                    h += `<div>
+                <div class="tree-branch-header" onclick="toggleBranch('${id}', this)">
+                    <span class="tree-arrow" id="a_${id}">${IC.chevron}</span>
+                    <span>${esc(n.label)}</span>
+                </div>
+                <div class="tree-children" id="${id}">${renderNodes(n.children)}</div>
+            </div>`;
+                }
+            }
+            return h;
+        }
+
+        function toggleBranch(id, el) {
+            const ch = $(id), ar = $('a_' + id);
+            if (ch) ch.classList.toggle('open');
+            if (ar) ar.classList.toggle('open');
+        }
+
+        function selectStage(el, stageName) {
+            // Highlight
+            document.querySelectorAll('.tree-leaf.active').forEach(e => e.classList.remove('active'));
+            el.classList.add('active');
+            S.stage = stageName;
+            S.versions = []; S.skip = 0; S.hasMore = true;
+            updateHeader();
+            loadVersions();
+        }
+
+        // ============ Header ============
+        function updateHeader() {
+            if (!S.stage) {
+                $('stagePath').innerHTML = '<span class="seg" style="color:var(--text-muted)">选择左侧数据阶段</span>';
+                $('headerInfo').textContent = '';
+                return;
+            }
+            const parts = S.stage.split('/');
+            $('stagePath').innerHTML = parts.map((p, i) =>
+                `${i > 0 ? '<span class="sep">/</span>' : ''}<span class="seg">${esc(p)}</span>`
+            ).join('');
+        }
+
+        // ============ Versions ============
+        async function loadVersions(append) {
+            if (S.loading) return;
+            S.loading = true;
+            if (!append) {
+                $('contentBody').innerHTML = '<div class="state-box"><div class="spinner"></div><p>加载中...</p></div>';
+            }
+            try {
+                const pid = S.stageProjectMap[S.stage];
+                const data = await api(`/projects/${pid}/stage-files?stage=${encodeURIComponent(S.stage)}&skip=${S.skip}&limit=${PAGE_SIZE}`);
+                if (!append) S.versions = [];
+                S.versions.push(...data);
+                S.hasMore = data.length >= PAGE_SIZE;
+                S.skip += data.length;
+                renderVersions();
+                const stageInfo = S.stages.find(s => s.name === S.stage);
+                $('headerInfo').textContent = stageInfo ? `共 ${stageInfo.version_count} 次提交` : '';
+            } catch (e) {
+                if (!append) $('contentBody').innerHTML = '<div class="state-box"><p style="color:#fc8181;">加载失败: ' + esc(e.message) + '</p></div>';
+            }
+            S.loading = false;
+        }
+
+        function renderVersions() {
+            if (!S.versions.length) {
+                $('contentBody').innerHTML = '<div class="state-box"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/></svg><h2>暂无数据</h2><p>该阶段还没有提交记录</p></div>';
+                return;
+            }
+            let h = `<div style="background: var(--bg-card); border: 1px solid var(--border-card); border-radius: var(--radius); overflow: hidden;">
+                <div class="table-header">
+                    <div>文件 / 文件夹</div>
+                    <div>Commit ID</div>
+                    <div>提交时间</div>
+                    <div>作者</div>
+                    <div style="text-align: right;">操作</div>
+                </div>
+                <div class="table-body">`;
+
+            S.versions.forEach((v, i) => {
+                const groups = groupFiles(v.files);
+                h += renderGroups(groups, v);
+            });
+
+            h += `</div></div>`;
+            if (S.hasMore) {
+                h += '<div class="load-more"><button class="load-more-btn" onclick="loadMore()">加载更多</button></div>';
+            }
+            $('contentBody').innerHTML = h;
+        }
+
+        function loadMore() {
+            const btn = document.querySelector('.load-more-btn');
+            if (btn) { btn.disabled = true; btn.textContent = '加载中...'; }
+            loadVersions(true);
+        }
+
+        // ============ File Grouping ============
+        function groupFiles(files) {
+            if (!files || !files.length) return [];
+            const map = {};
+            files.forEach(f => {
+                const parts = f.relative_path.split('/');
+                const parentDir = parts.slice(0, -1).join('/');
+                if (!map[parentDir]) map[parentDir] = [];
+                map[parentDir].push(f);
+            });
+            const result = [];
+            Object.entries(map).forEach(([dir, fls]) => {
+                if (dir !== '') {
+                    const segments = dir.split('/');
+                    const dirName = segments[segments.length - 1] || dir;
+                    result.push({ type: 'folder', name: dirName, path: dir, files: fls });
+                } else {
+                    fls.forEach(f => result.push({ type: 'file', file: f }));
+                }
+            });
+            result.sort((a, b) => {
+                if (a.type !== b.type) return a.type === 'folder' ? -1 : 1;
+                return (a.name || a.file.name).localeCompare(b.name || b.file.name);
+            });
+            return result;
+        }
+
+        function renderGroups(groups, version) {
+            if (!groups.length) return '';
+            let h = '';
+            groups.forEach(g => {
+                if (g.type === 'folder') {
+                    const gid = 'fg_' + Math.random().toString(36).substr(2, 6);
+                    h += `
+            <div class="fg-header" onclick="toggleFG('${gid}')">
+                <div class="fg-name-wrap">
+                    <span class="fg-arrow" id="fa_${gid}">${IC.chevron}</span>
+                    <span class="fg-icon">${IC.folder}</span>
+                    <span class="fg-name">${esc(g.name)}/</span>
+                    <span class="fg-count">${g.files.length}</span>
+                </div>
+                <div class="col-text commit-tag" title="${esc(version.commit_id)}">${esc(version.commit_id.substring(0, 8))}</div>
+                <div class="col-text" title="${fmtTime(version.created_at)}">${relTime(version.created_at)}</div>
+                <div class="col-text">${version.author ? esc(version.author) : '-'}</div>
+                <div></div>
+            </div>
+            <div class="fg-children" id="${gid}">
+                ${g.files.map(f => fileRow(f, version, true)).join('')}
+            </div>`;
+                } else {
+                    h += fileRow(g.file, version, false);
+                }
+            });
+            return h;
+        }
+
+        function fileRow(f, version, isChild) {
+            const padding = isChild ? 'padding-left: 44px;' : '';
+            return `
+    <div class="file-row" style="${padding}">
+        <div class="file-name-col" title="${esc(f.relative_path)}">
+            <span class="f-icon">${IC.file}</span>
+            <span class="f-name">${esc(f.name)}</span>
+            <span class="f-size">${fmtSize(f.file_size)}</span>
+        </div>
+        <div class="col-text commit-tag" title="${esc(version.commit_id)}">${esc(version.commit_id.substring(0, 8))}</div>
+        <div class="col-text" title="${fmtTime(version.created_at)}">${relTime(version.created_at)}</div>
+        <div class="col-text">${version.author ? esc(version.author) : '-'}</div>
+        <div class="btn-dl-wrap">
+            <a class="btn-dl" href="/files/${f.id}/content" download="${esc(f.name)}" onclick="event.stopPropagation();">${IC.download}</a>
+        </div>
+    </div>`;
+        }
+
+        function toggleFG(id) {
+            const ch = $(id), ar = $('fa_' + id);
+            if (ch) ch.classList.toggle('open');
+            if (ar) ar.classList.toggle('open');
+        }
+
+        // ============ UI Helpers ============
+        function showWelcome() {
+            $('stagePath').innerHTML = '<span class="seg" style="color:var(--text-muted)">选择左侧数据阶段</span>';
+            $('headerInfo').textContent = '';
+            $('contentBody').innerHTML = `<div class="state-box">
+        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
+            <path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/>
+            <polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/>
+        </svg>
+        <h2>欢迎使用数据控制台</h2>
+        <p>从左侧选择数据阶段,查看文件版本历史</p>
+    </div>`;
+        }
+
+        // ============ Init ============
+        loadAllStages();
+    </script>
+</body>
+
+</html>