From 0b1ad75571b312dd60f9ae0099b47cc02ac54c78 Mon Sep 17 00:00:00 2001 From: "Somhairle H. Marisol" Date: Fri, 18 Sep 2026 09:50:37 +0800 Subject: feat(frontend): 首页指标卡与项目行 sparkline(前端重设计第二轮之一) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [变更性质] 新增能力,不动后端。 [新增功能] dashboardMetrics 聚合(项目/数据集/实验/AI 用量统计 + 最近回测首末净值),实盘数据优先、缺数以占位符 '-' 兜底;ProjectMetricRow 渲染 4 张 metric-card;Sparkline 组件输出 up/down 方向线段与端点圆点。 [实现方案] 聚合逻辑与展示组件分离,sparkline 仅依赖 first/last 两个字段,无图表库依赖。 [影响范围] frontend/src/lib 与 components;配套 5 组单测(dashboardMetrics/sparkline/metricRow)。 --- frontend/src/components/ProjectMetricRow.svelte | 83 +++++++++++++++++++++++++ frontend/src/components/Sparkline.svelte | 45 ++++++++++++++ frontend/src/lib/dashboardMetrics.test.ts | 77 +++++++++++++++++++++++ frontend/src/lib/dashboardMetrics.ts | 79 +++++++++++++++++++++++ frontend/src/lib/metricRow.test.ts | 63 +++++++++++++++++++ frontend/src/lib/sparkline.test.ts | 66 ++++++++++++++++++++ 6 files changed, 413 insertions(+) create mode 100644 frontend/src/components/ProjectMetricRow.svelte create mode 100644 frontend/src/components/Sparkline.svelte create mode 100644 frontend/src/lib/dashboardMetrics.test.ts create mode 100644 frontend/src/lib/dashboardMetrics.ts create mode 100644 frontend/src/lib/metricRow.test.ts create mode 100644 frontend/src/lib/sparkline.test.ts (limited to 'frontend') diff --git a/frontend/src/components/ProjectMetricRow.svelte b/frontend/src/components/ProjectMetricRow.svelte new file mode 100644 index 0000000..31001bf --- /dev/null +++ b/frontend/src/components/ProjectMetricRow.svelte @@ -0,0 +1,83 @@ + + +
+
+ 我的项目 + {metric.projectCount} +
+
+ 数据集 + {metric.datasetCount} +
+
+ 回测 + + 运行中 {metric.runningRuns} + 已完成 {metric.doneRuns} + +
+
+ AI 用量 + {metric.usageLabel} + {#if metric.usageTokens}{metric.usageTokens}{/if} +
+
+ + diff --git a/frontend/src/components/Sparkline.svelte b/frontend/src/components/Sparkline.svelte new file mode 100644 index 0000000..12a3b47 --- /dev/null +++ b/frontend/src/components/Sparkline.svelte @@ -0,0 +1,45 @@ + + +{#if first !== null && last !== null} + + + + + +{/if} diff --git a/frontend/src/lib/dashboardMetrics.test.ts b/frontend/src/lib/dashboardMetrics.test.ts new file mode 100644 index 0000000..2a25fda --- /dev/null +++ b/frontend/src/lib/dashboardMetrics.test.ts @@ -0,0 +1,77 @@ +// @ts-nocheck +import { describe, expect, it } from 'vitest'; +import { aggregateDashboard, sparkFirstLast } from './dashboardMetrics'; + +// Leader round2 spec: 登录后默认页顶部一行指标卡—— +// 当前项目数 / 数据集总数 / 运行中-已完成回测数 / AI 用量。 +// 取不到的字段占位 "-"(不得编造数字)。行为合同先定义: + +describe('aggregateDashboard', () => { + const projects = [{ id: 'p1' }, { id: 'p2' }, { id: 'p3' }]; + const datasets = [{ id: 'd1' }, { id: 'd2' }]; + const runs = [ + { id: 'r1', status: 'running', result: null }, + { id: 'r2', status: 'queued', result: null }, + { id: 'r3', status: 'succeeded', result: { metrics: {} } }, + { id: 'r4', status: 'succeeded', result: { metrics: {} } }, + { id: 'r5', status: 'failed', result: null } + ]; + + it('counts projects, datasets and running/done runs from plain item arrays', () => { + const x = aggregateDashboard({ projects, datasets, runs, usage: null }); + expect(x.projectCount).toBe(3); + expect(x.datasetCount).toBe(2); + expect(x.runningRuns).toBe(2); // queued + running + expect(x.doneRuns).toBe(2); // succeeded + }); + + it('usage label uses real totals when present, "-" placeholder otherwise', () => { + const withUsage = aggregateDashboard({ + projects, datasets, runs, + usage: { totals: { input_tokens: 1200, output_tokens: 340, requests: 7 } } + }); + expect(withUsage.usageLabel).toBe('7 次'); + expect(withUsage.usageTokens).toBe('(1.2k/340 tok)'); + + const withoutUsage = aggregateDashboard({ projects, datasets, runs, usage: null }); + expect(withoutUsage.usageLabel).toBe('-'); + expect(withoutUsage.usageTokens).toBe(''); + }); + + it('is resilient to missing arrays (fresh account)', () => { + const x = aggregateDashboard({ projects: null, datasets: undefined, runs: null, usage: {} }); + expect(x.projectCount).toBe(0); + expect(x.datasetCount).toBe(0); + expect(x.runningRuns).toBe(0); + expect(x.doneRuns).toBe(0); + }); +}); + +describe('sparkFirstLast (per-project latest backtest equity endpoints)', () => { + it('picks the newest run with a result per project and returns first/last equity', () => { + const runs = [ + { id: 'r-old', project_id: 'p1', created_at: '2026-01-01', result: { equity: [ + { equity: 100 }, + { equity: 130 } // old run: up + ] } }, + { id: 'r-new', project_id: 'p1', created_at: '2026-02-01', result: { equity: [ + { equity: 100 }, + { equity: 90 } // newer run is down — must win over the old run + ] } }, + { id: 'r-broken', project_id: 'p2', created_at: '2026-02-01', result: null }, + { id: 'r-only', project_id: 'p3', created_at: '2026-02-03', result: { equity: [ + { equity: 50 }, + { equity: 50 }, + { equity: 58 } + ] } } + ]; + const m = sparkFirstLast(runs); + expect(m.get('p1')).toEqual({ first: 100, last: 90 }); + expect(m.get('p3')).toEqual({ first: 50, last: 58 }); + expect(m.has('p2')).toBe(false); // result=null → no sparkline, renders as empty + }); + + it('returns empty map for no runs', () => { + expect([...sparkFirstLast([]).keys()]).toEqual([]); + }); +}); diff --git a/frontend/src/lib/dashboardMetrics.ts b/frontend/src/lib/dashboardMetrics.ts new file mode 100644 index 0000000..2801c9d --- /dev/null +++ b/frontend/src/lib/dashboardMetrics.ts @@ -0,0 +1,79 @@ +// Leader round2 spec: 登录后默认页顶部指标卡 + 项目行迷你权益缩略图。 +// 纯函数层,聚合合同在 dashboardMetrics.test.ts 做真实断言。 +// 取不到的字段一律占位 "-",不得编造数字。 + +export interface DashboardMetric { + projectCount: number; + datasetCount: number; + runningRuns: number; + doneRuns: number; + /** "7 次" 或 "-"(后端无请求计数时) */ + usageLabel: string; + /** 次要说明:token 计数摘要,无数据为空串 */ + usageTokens: string; +} + +function kify(n: number): string { + if (n >= 10000) return `${Math.round(n / 1000)}k`; + if (n >= 1000) return `${(n / 1000).toFixed(1)}k`; + return `${n}`; +} + +export function aggregateDashboard(input: { + projects?: { id: string }[] | null; + datasets?: { id: string }[] | null; + runs?: { id: string; status: string; result?: unknown }[] | null; + usage?: { totals?: { input_tokens?: number; output_tokens?: number; requests?: number } } | null; +}): DashboardMetric { + const projects = Array.isArray(input.projects) ? input.projects : []; + const datasets = Array.isArray(input.datasets) ? input.datasets : []; + const runs = Array.isArray(input.runs) ? input.runs : []; + const runningRuns = runs.filter((r) => r.status === 'running' || r.status === 'queued').length; + const doneRuns = runs.filter((r) => r.status === 'succeeded').length; + + const t = input.usage?.totals; + let usageLabel = '-'; + let usageTokens = ''; + if (t && typeof t.requests === 'number') { + usageLabel = `${t.requests} 次`; + const inTok = t.input_tokens ?? 0; + const outTok = t.output_tokens ?? 0; + usageTokens = `(${kify(inTok)}/${kify(outTok)} tok)`; + } + + return { + projectCount: projects.length, + datasetCount: datasets.length, + runningRuns, + doneRuns, + usageLabel, + usageTokens + }; +} + +export interface SparkEndpoints { + first: number; + last: number; +} + +/** + * Per-project latest backtest endpoints for the project-row sparkline. + * Latest = max created_at among runs whose result carries equity points. + * A project without any chart-carrying run gets NO entry (caller must not + * render a sparkline in that case). + */ +export function sparkFirstLast( + runs: { project_id?: string; created_at?: string; result?: { equity?: { equity: number }[] } | null }[] +): Map { + const best = new Map(); + const out = new Map(); + for (const r of runs) { + const eq = r.result?.equity; + if (!r.project_id || !Array.isArray(eq) || eq.length < 2) continue; + const prev = best.get(r.project_id); + if (prev && prev.at >= (r.created_at ?? '')) continue; + best.set(r.project_id, { at: r.created_at ?? '', first: eq[0].equity, last: eq[eq.length - 1].equity }); + } + for (const [k, v] of best) out.set(k, { first: v.first, last: v.last }); + return out; +} diff --git a/frontend/src/lib/metricRow.test.ts b/frontend/src/lib/metricRow.test.ts new file mode 100644 index 0000000..bc41b54 --- /dev/null +++ b/frontend/src/lib/metricRow.test.ts @@ -0,0 +1,63 @@ +// @ts-nocheck +import { describe, expect, it, vi, afterEach } from 'vitest'; +import { cleanup } from '@testing-library/svelte'; +import { render, screen } from '@testing-library/svelte'; + +import ProjectMetricRow from '../components/ProjectMetricRow.svelte'; + +// Leader round2: 首页改为指标卡行——当前项目数、数据集总数、 +// 运行中/已完成回测数、AI 用量;取不到的字段占位 "-"。 +// 真实渲染断言,测试数据通过 props 注入。 + +afterEach(() => cleanup()); + +const projects = [{ id: 'p1' }, { id: 'p2' }, { id: 'p3' }]; +const datasets = [{ id: 'd1' }, { id: 'd2' }]; +const runs = [ + { id: 'r1', status: 'running', result: null }, + { id: 'r2', status: 'queued', result: null }, + { id: 'r3', status: 'succeeded', result: { metrics: {} } }, + { id: 'r4', status: 'succeeded', result: { metrics: {} } } +]; + +describe('ProjectMetricRow (real render, 4 metric cards)', () => { + it('renders a metric-card row: 项目/数据集/回测 running+done/AI 用量, values visible', () => { + const { container } = render(ProjectMetricRow, { + props: { + projects, datasets, runs, + usage: { totals: { input_tokens: 1200, output_tokens: 340, requests: 7 } } + } + }); + const cards = container.querySelectorAll('[data-testid="metric-card"]'); + expect(cards.length).toBe(4); + expect(screen.getByText('我的项目')).toBeTruthy(); + expect(screen.getByText('数据集')).toBeTruthy(); + expect(screen.getByText('回测')).toBeTruthy(); + expect(screen.getByText('AI 用量')).toBeTruthy(); + // 数字直接可见:项目卡/数据集卡与回测拆分值 + const values = [...container.querySelectorAll('.metric-card .mvalue')].map((n) => n.textContent!.replace(/\s+/g, ' ').trim()); + expect(values[0]).toBe('3'); + expect(values[1]).toBe('2'); + expect(values[2]).toContain('运行中'); + expect(values[2]).toContain('2'); + expect(values[2]).toContain('已完成'); + expect(values[2]).toContain('2'); + expect(screen.getByText('7 次')).toBeTruthy(); + }); + + it('usage unavailable → "-" placeholder + TODO marker on the card', () => { + const { container } = render(ProjectMetricRow, { + props: { projects, datasets, runs, usage: null } + }); + const cards = [...container.querySelectorAll('[data-testid="metric-card"]')]; + const usage = cards.at(-1)!; + expect(usage.textContent).toContain('-'); + expect(usage.getAttribute('data-todo') ?? '').toContain('TODO'); + }); + + it('runs card splits 运行中 / 已完成', () => { + render(ProjectMetricRow, { props: { projects, datasets, runs, usage: null } }); + expect(screen.getByText(/运行中/)).toBeTruthy(); + expect(screen.getByText(/已完成/)).toBeTruthy(); + }); +}); diff --git a/frontend/src/lib/sparkline.test.ts b/frontend/src/lib/sparkline.test.ts new file mode 100644 index 0000000..aecf20d --- /dev/null +++ b/frontend/src/lib/sparkline.test.ts @@ -0,0 +1,66 @@ +// @ts-nocheck +import { describe, expect, it, vi } from 'vitest'; +import { mount, unmount } from 'svelte'; +import Sparkline from '../components/Sparkline.svelte'; + +// Leader round2: 项目列表每行内嵌迷你权益缩略图—— +// 用最近一个回测 equity 的首尾点画 sparkline SVG; +// 无数据就整个组件留空(不渲染 svg)。 + +describe('Sparkline (real render)', () => { + it('renders an svg with a first→last polyline when handed endpoints', async () => { + const host = document.createElement('div'); + const inst = mount(Sparkline, { + target: host, + props: { first: 100, last: 90, up: false, ariaLabel: '最近回测权益缩略' } + }); + await new Promise((r) => setTimeout(r, 50)); + const svg = host.querySelector('svg'); + expect(svg, 'sparkline must be a real svg element').toBeTruthy(); + const path = svg.querySelector('path, polyline'); + expect(path).toBeTruthy(); + const d = (path.getAttribute('d') || path.getAttribute('points')) ?? ''; + // polyline from left edge to right edge: both endpoints present in geometry + expect(d).toContain('0'); // first x + const coordsCount = d.trim().split(/[\s,L,M]+/).filter(Boolean).length; + expect(coordsCount).toBeGreaterThanOrEqual(4); // 2 points × (x,y) + unmount(inst); + host.remove(); + }); + + it('renders NOTHING (no svg) for missing data — 留空不渲染', async () => { + const host = document.createElement('div'); + const inst = mount(Sparkline, { target: host, props: { first: null, last: null, ariaLabel: 'x' } }); + await new Promise((r) => setTimeout(r, 50)); + expect(host.querySelector('svg')).toBeNull(); + expect(host.textContent.trim()).toBe(''); + unmount(inst); + host.remove(); + }); + + it('方向语义:down 变红(危险色),up 变绿(成功色)', async () => { + const down = document.createElement('div'); + const inst1 = mount(Sparkline, { + target: down, + props: { first: 100, last: 90, up: false, ariaLabel: 'x' } + }); + await new Promise((r) => setTimeout(r, 30)); + const downColor = down.querySelector('path, polyline')?.getAttribute('stroke') ?? ''; + unmount(inst1); + down.remove(); + + const up = document.createElement('div'); + const inst2 = mount(Sparkline, { + target: up, + props: { first: 100, last: 130, up: true, ariaLabel: 'x' } + }); + await new Promise((r) => setTimeout(r, 30)); + const upColor = up.querySelector('path, polyline')?.getAttribute('stroke') ?? ''; + unmount(inst2); + up.remove(); + + expect(downColor).not.toBe(''); + expect(upColor).not.toBe(''); + expect(downColor).not.toBe(upColor); + }); +}); -- cgit v1.2.3