feat(qa-ops): 交付十一项统计看板与完整图片导出
build / build (push) Successful in 1m10s

以治理库单一只读事务分开聚合累计、自然周、截止月及当前通讯录使用分母;浏览器不再读取全量长答案来构建看板。

新增迁移52与普通worker周质量冻结,保留真实冻结时点、规则和标量贡献;缺少当时快照留空。提交后冻结头与贡献不可修改、删除或追加;只读接口保留管理员、固定租户、严格JSON与输入冲突保护。

已验证:make verify退出0,686个Go用例和305个前端用例通过,必需跳过0;镜像与组织隔离PostgreSQL竞态回归退出0。真实治理副本浏览器核对第41周累计1885与新增471、十一项和完整PNG下载,390px无外溢、JS异常0;明确模拟503后不伪零且重试恢复。没有修改DobotAI原始问答、真实区域规则或生产发布门禁。
This commit is contained in:
姚章浩
2026-10-18 23:26:55 +08:00
parent 76671e0784
commit 6e67034fbd
32 changed files with 2103 additions and 356 deletions
+5 -11
View File
@@ -2,6 +2,8 @@ import { renderToStaticMarkup } from 'react-dom/server'
import { describe, it, expect, vi } from 'vitest'
import { qaDailySeries, qaCategorySeries } from './qaDashboard'
import { QADashboardView } from './QADashboard'
import { parseQADashboard } from './qaDashboardData'
import { dashboardFixture } from './qaDashboard.fixture'
import type { QARecord, QAQuery } from './qaOps'
const query: QAQuery = { start: '2026-10-11T16:00:00Z', end: '2026-10-13T16:00:00Z', keyword: '', cursor: '' }
const records = [
@@ -24,19 +26,11 @@ describe('question dashboard projections', () => {
})
it('renders the real dashboard panels and escaped category text', () => {
const html = renderToStaticMarkup(
<QADashboardView
page={{ items: records, columns: [], total: 2, has_more: false, next_cursor: '', as_of: query.end }}
query={query}
quality={null}
usage={null}
loading={false}
error=""
onRetry={vi.fn()}
/>
<QADashboardView data={parseQADashboard(dashboardFixture)} loading={false} error="" onRetry={vi.fn()} />
)
for (const title of ['问题总量', '每日提问趋势', '质量分布', '区域分布', '产品分类', '问题类型'])
for (const title of ['问题总数', '本周新增', '覆盖率趋势', '正确率趋势', '产品问题排行', '导出看板图片'])
expect(html).toContain(title)
expect(html).not.toContain('<img src=x')
expect(html).not.toContain('0.0%')
expect((html.match(/data-panel=/g) || []).length).toBe(11)
})
})
+74 -172
View File
@@ -1,219 +1,121 @@
import { useEffect, useState } from 'react'
import type { QARecordPage, QAQuery } from './qaOps'
import type { QualitySummary, QualityRate } from './qaQuality'
import type { QAUsage } from './qaUsage'
import { fetchQAUsage, usageLabels } from './qaUsage'
import { qaDailySeries, qaCategorySeries, fetchQADashboardQuality } from './qaDashboard'
import type { QACountPoint } from './qaDashboard'
import { useEffect, useRef, useState } from 'react'
import type { QAQuery } from './qaOps'
import { fetchQADashboard } from './qaDashboardData'
import type { QADashboardData } from './qaDashboardData'
import { QADashboardDrawing } from './QADashboardDrawing'
import { createDashboardPNG } from './qaDashboardExport'
import { currentQAWeek } from './qaWeeks'
import { QAMonthly } from './QAMonthly'
import './qaDashboard.css'
export interface QADashboardProps {
page: QARecordPage | null
query: QAQuery | null
quality: QualitySummary | null
usage: QAUsage | null
data: QADashboardData | null
loading: boolean
error: string
onRetry: () => void
}
const percent = (r: QualityRate | undefined) => (r?.percent == null ? '—' : `${r.percent.toFixed(1)}%`)
function Bars({ points }: { points: QACountPoint[] }) {
const max = Math.max(1, ...points.map((p) => p.count))
return points.length ? (
<div className="qa-chart-bars">
{points.map((p) => (
<div className="qa-chart-bar" key={p.label}>
<span title={p.label}>{p.label}</span>
<div className="qa-chart-track">
<i style={{ width: `${(p.count / max) * 100}%` }} />
</div>
<b>{p.count}</b>
</div>
))}
</div>
) : (
<p className="qa-chart-empty">暂无数据</p>
)
}
export function QADashboardView(p: QADashboardProps) {
const page = p.loading ? null : p.page,
items = page?.items || [],
q = page && p.quality?.summary.total === page.total ? p.quality : null
const b = q?.summary.rates.breakdown
const daily = page && p.query ? qaDailySeries(items, p.query) : []
const max = Math.max(1, ...daily.map((d) => d.count))
const outcomes = b
? [
['已覆盖', b.covered],
['未覆盖', b.uncovered],
['部分覆盖', b.partial],
['待确认', b.pending],
['未评估', b.unassessed],
['不计入', b.excluded],
['待重新核对', b.stale],
].map(([label, count]) => ({ label: String(label), count: Number(count) }))
: []
export function QADashboardView({ data, loading, error, onRetry }: QADashboardProps) {
const host = useRef<HTMLDivElement>(null),
svg = useRef<SVGSVGElement>(null)
const [width, setWidth] = useState(1280),
[exporting, setExporting] = useState(false),
[exportError, setExportError] = useState('')
useEffect(() => {
const element = host.current
if (!element) return
const update = () => setWidth(Math.max(240, Math.floor(element.clientWidth)))
update()
const observer = new ResizeObserver(update)
observer.observe(element)
return () => observer.disconnect()
}, [])
useEffect(() => setExportError(''), [data])
async function download() {
if (!svg.current || !data || loading || error || exporting) return
setExporting(true)
setExportError('')
try {
const blob = await createDashboardPNG(svg.current),
url = URL.createObjectURL(blob),
link = document.createElement('a'),
week = currentQAWeek(new Date(data.week_start))
link.href = url
link.download = `DobotAI_QA_Dashboard_${week.year}_W${String(week.week).padStart(2, '0')}.png`
document.body.append(link)
link.click()
link.remove()
window.setTimeout(() => URL.revokeObjectURL(url), 1000)
} catch (e) {
setExportError(e instanceof Error ? e.message : '看板图片生成失败')
} finally {
setExporting(false)
}
}
return (
<section className="qa-dashboard" aria-label="问题统计看板">
{p.error ? (
<div className="qa-dashboard-toolbar">
<button type="button" disabled={!data || loading || !!error || exporting} onClick={() => void download()}>
{exporting ? '正在生成图片…' : '导出看板图片'}
</button>
</div>
{error ? (
<div role="alert" className="error-banner">
{p.error}{' '}
<button type="button" onClick={p.onRetry}>
{error}{' '}
<button type="button" onClick={onRetry}>
重新读取
</button>
</div>
) : null}
{p.loading ? <p role="status">正在读取完整统计范围…</p> : null}
<div className="qa-dashboard-metrics" aria-label="问题概览">
<div>
<span>问题总量</span>
<strong>{page?.total ?? '—'}</strong>
<small>条</small>
{exportError ? (
<div role="alert" className="error-banner">
{exportError}
</div>
<div>
<span>知识覆盖率</span>
<strong>{percent(q?.summary.rates.coverage)}</strong>
<small>
{q ? `${q.summary.rates.coverage.numerator} / ${q.summary.rates.coverage.denominator}` : '分子 / 分母'}
</small>
</div>
<div>
<span>回答正确率</span>
<strong>{percent(q?.summary.rates.correctness)}</strong>
<small>
{q
? `${q.summary.rates.correctness.numerator} / ${q.summary.rates.correctness.denominator}`
: '分子 / 分母'}
</small>
</div>
<div>
<span>已人工复核</span>
<strong>{q?.summary.reviewed ?? '—'}</strong>
<small>{q ? `待复核 ${q.summary.unreviewed}` : '条'}</small>
</div>
</div>
<div className="qa-dashboard-grid">
<section className="qa-chart qa-chart-wide">
<h3>每日提问趋势</h3>
{daily.length ? (
<div className="qa-daily-chart" role="img" aria-label="北京时间每日提问量">
{daily.map((d) => (
<div key={d.label} title={`${d.label}:${d.count} 条`}>
<b>{d.count}</b>
<div>
<i style={{ height: `${(d.count / max) * 100}%` }} />
</div>
<span>{d.label.slice(5)}</span>
</div>
))}
</div>
) : (
<p className="qa-chart-empty">暂无数据</p>
)}
</section>
<section className="qa-chart">
<h3>质量分布</h3>
<Bars points={outcomes} />
</section>
<section className="qa-chart qa-chart-wide">
<h3>区域分布</h3>
<Bars
points={
p.usage?.rows
.filter((r) => r.questions > 0)
.map((r) => ({ label: usageLabels[r.key] || r.key, count: r.questions })) || []
}
/>
{p.usage ? (
<div className="qa-dashboard-region-table">
<table>
<thead>
<tr>
<th>区域</th>
<th>提问量</th>
<th>已关联使用人数</th>
</tr>
</thead>
<tbody>
{p.usage.rows
.filter((r) => r.questions > 0 || r.roster_people !== null)
.map((r) => (
<tr key={r.key}>
<td>{usageLabels[r.key] || r.key}</td>
<td>{r.questions}</td>
<td>{r.users ?? '—'}</td>
</tr>
))}
</tbody>
</table>
</div>
) : null}
</section>
<section className="qa-chart">
<h3>问题类型</h3>
<Bars points={qaCategorySeries(items, 'problem_type')} />
</section>
<section className="qa-chart qa-chart-full">
<h3>产品分类</h3>
<Bars points={qaCategorySeries(items, 'product_category')} />
</section>
) : null}
{loading ? <p role="status">正在读取完整统计范围…</p> : null}
<div className="qa-dashboard-canvas" ref={host}>
{!loading && !error && data ? <QADashboardDrawing data={data} width={width} svgRef={svg} /> : null}
</div>
</section>
)
}
export function QADashboard({
page,
query,
loading,
error,
revision,
onRetry,
}: {
page: QARecordPage | null
query: QAQuery | null
loading: boolean
error: string | null
revision: number
onRetry: () => void
}) {
const [quality, setQuality] = useState<QualitySummary | null>(null),
[usage, setUsage] = useState<QAUsage | null>(null),
const [data, setData] = useState<QADashboardData | null>(null),
[failure, setFailure] = useState(''),
[loading, setLoading] = useState(false),
[monthly, setMonthly] = useState(false)
useEffect(() => {
setQuality(null)
setUsage(null)
setData(null)
setFailure('')
if (!query) return
if (!query) {
setLoading(false)
return
}
const abort = new AbortController()
void fetchQADashboardQuality(query, abort.signal)
setLoading(true)
void fetchQADashboard(query, abort.signal)
.then((v) => {
if (!abort.signal.aborted) setQuality(v)
if (!abort.signal.aborted) setData(v)
})
.catch((e) => {
if (!abort.signal.aborted) setFailure(e instanceof Error ? e.message : '质量统计读取失败')
if (!abort.signal.aborted) setFailure(e instanceof Error ? e.message : '统计看板读取失败')
})
void fetchQAUsage(query, abort.signal)
.then((v) => {
if (!abort.signal.aborted) setUsage(v)
})
.catch((e) => {
if (!abort.signal.aborted) setFailure(e instanceof Error ? e.message : '区域统计读取失败')
.finally(() => {
if (!abort.signal.aborted) setLoading(false)
})
return () => abort.abort()
}, [query, revision])
const mismatch = !!page && !!quality && page.total !== quality.summary.total
return (
<div className="qa-dashboard-scroll">
<QADashboardView
page={page}
query={query}
quality={quality}
usage={usage}
loading={loading}
error={error || failure || (mismatch ? '统计范围已更新,请重新查询' : '')}
onRetry={onRetry}
/>
<QADashboardView data={data} loading={loading} error={error || failure} onRetry={onRetry} />
<details className="qa-monthly-disclosure" onToggle={(e) => setMonthly(e.currentTarget.open)}>
<summary>个人月明细</summary>
{monthly ? <QAMonthly /> : null}
+33
View File
@@ -0,0 +1,33 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { it, expect } from 'vitest'
import { QADashboardDrawing } from './QADashboardDrawing'
import { dashboardFixture } from './qaDashboard.fixture'
import { parseQADashboard } from './qaDashboardData'
it('draws all eleven panels as a self-contained exportable SVG without HTML execution', () => {
const html = renderToStaticMarkup(<QADashboardDrawing data={parseQADashboard(dashboardFixture)} width={1280} />)
expect((html.match(/data-panel=/g) || []).length).toBe(11)
for (const title of [
'问题总数',
'本周新增',
'覆盖率',
'正确率',
'问题类型分布',
'产品问题排行',
'问题趋势',
'区域平均使用频率',
'区域使用覆盖率',
'覆盖率趋势',
'正确率趋势',
])
expect(html).toContain(title)
expect(html).toContain('&lt;img src=x')
expect(html).not.toContain('<foreignObject')
expect(html).not.toContain('<img src=x')
expect(html).toContain('data-frozen="missing"')
expect(html).toContain('data-frozen="available"')
})
it('reflows the same complete eleven panels at mobile width rather than clipping the canvas', () => {
const html = renderToStaticMarkup(<QADashboardDrawing data={parseQADashboard(dashboardFixture)} width={350} />)
expect((html.match(/data-panel=/g) || []).length).toBe(11)
expect(html).toContain('viewBox="0 0 350 ')
})
+589
View File
@@ -0,0 +1,589 @@
import type { ReactNode, Ref } from 'react'
import type { QADashboardData, DashboardCount, DashboardRegion } from './qaDashboardData'
import type { QualityRate } from './qaQuality'
import { currentQAWeek } from './qaWeeks'
interface Box {
x: number
y: number
w: number
h: number
}
const blue = '#3274e6',
ink = '#23344d',
muted = '#7a8799',
line = '#eaf0f7'
const colors = [blue, '#59a9f3', '#69c6bc', '#f3c25a', '#f39b6c', '#9b8ade', '#86b8a1', '#d6a3cf', '#8aacc9', '#c4cb76']
const number = (n: number) => new Intl.NumberFormat('zh-CN').format(n)
const pct = (n: number | null) => (n === null ? '—' : `${n.toFixed(1)}%`)
function wrap(value: string, width: number, size = 12): string[] {
const max = Math.max(2, width / size),
out: string[] = []
let row = '',
units = 0
for (const c of Array.from(value)) {
const next = c.charCodeAt(0) < 128 ? 0.57 : 1
if (row && units + next > max) {
out.push(row)
row = ''
units = 0
}
row += c
units += next
}
if (row || !out.length) out.push(row)
return out
}
function Text({
value,
x,
y,
width,
size = 12,
fill = ink,
weight = 400,
anchor = 'start',
}: {
value: string
x: number
y: number
width: number
size?: number
fill?: string
weight?: number
anchor?: 'start' | 'middle' | 'end'
}) {
return (
<text x={x} y={y} fontSize={size} fill={fill} fontWeight={weight} textAnchor={anchor}>
{wrap(value, width, size).map((row, i) => (
<tspan key={i} x={x} dy={i ? size * 1.35 : 0}>
{row}
</tspan>
))}
</text>
)
}
function Panel({
box,
title,
en,
id,
children,
tint = '#fff',
}: {
box: Box
title: string
en: string
id: string
children: ReactNode
tint?: string
}) {
return (
<g data-panel={id} transform={`translate(${box.x} ${box.y})`}>
<rect width={box.w} height={box.h} rx={7} fill={tint} />
<text x={16} y={25} fontSize={14} fontWeight={650} fill={ink}>
{title}
</text>
<text x={16} y={43} fontSize={10.5} fill={muted}>
{en}
</text>
{children}
</g>
)
}
function Metric({
box,
value,
title,
en,
id,
tint,
color,
subtitle,
}: {
box: Box
value: number
title: string
en: string
id: string
tint: string
color: string
subtitle: string
}) {
const text = number(value),
size = Math.min(box.w < 220 ? 40 : 54, (box.w - 32) / (text.length * 0.62))
return (
<Panel box={box} title={title} en={en} id={id} tint={tint}>
<text x={16} y={box.h - 43} fontSize={size} fill={color} fontWeight={700} data-value={value}>
{text}
</text>
<text x={16} y={box.h - 17} fill={muted} fontSize={11}>
{subtitle}
</text>
</Panel>
)
}
function polar(cx: number, cy: number, r: number, degrees: number) {
const a = (degrees * Math.PI) / 180
return { x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) }
}
function arc(cx: number, cy: number, r: number, start: number, end: number) {
const a = polar(cx, cy, r, start),
b = polar(cx, cy, r, end)
return `M ${a.x} ${a.y} A ${r} ${r} 0 ${end - start > 180 ? 1 : 0} 1 ${b.x} ${b.y}`
}
function Gauge({ box, rate, title, en, id }: { box: Box; rate: QualityRate; title: string; en: string; id: string }) {
const r = Math.min(42, box.w * 0.27),
cx = box.w / 2,
cy = 94,
d = arc(cx, cy, r, 135, 405)
return (
<Panel box={box} title={title} en={en} id={id}>
<title>{`${title}:${rate.numerator} / ${rate.denominator};分母为有效已评估记录`}</title>
<path d={d} fill="none" stroke="#e8ecf2" strokeWidth={8} strokeLinecap="round" />
{rate.percent !== null && rate.percent > 0 ? (
<path
d={d}
fill="none"
stroke={blue}
strokeWidth={8}
strokeLinecap="round"
pathLength={100}
strokeDasharray={`${rate.percent} 100`}
/>
) : null}
<text
x={cx}
y={cy + 6}
textAnchor="middle"
fontSize={box.w < 220 ? 22 : 27}
fontWeight={650}
fill={ink}
data-value={rate.percent ?? 'unknown'}
>
{pct(rate.percent)}
</text>
<text x={cx} y={box.h - 14} fontSize={11} fill={muted} textAnchor="middle">
{rate.denominator ? `${number(rate.numerator)} / ${number(rate.denominator)}` : '暂无有效分母'}
</text>
</Panel>
)
}
function pieHeight(points: DashboardCount[], w: number) {
const mobile = w < 500,
legendW = mobile ? w - 60 : w * 0.45
return Math.max(
mobile ? 270 : 300,
(mobile ? 225 : 65) + points.reduce((n, p) => n + Math.max(24, wrap(p.label, legendW - 85).length * 16 + 9), 0)
)
}
function Pie({ box, points }: { box: Box; points: DashboardCount[] }) {
const mobile = box.w < 500,
total = points.reduce((n, p) => n + p.count, 0),
legendW = mobile ? box.w - 32 : box.w * 0.47,
cx = mobile ? box.w / 2 : box.w * 0.76,
cy = mobile ? 135 : Math.max(155, box.h / 2),
radius = Math.min(mobile ? 73 : 112, box.w * (mobile ? 0.25 : 0.21))
let angle = -90,
legendY = mobile ? 236 : 76
return (
<Panel box={box} title="问题类型分布" en="Issue Type Distribution" id="issue-types">
{!total ? (
<text x={box.w / 2} y={box.h / 2} textAnchor="middle" fill={muted} fontSize={13}>
暂无分类记录
</text>
) : null}
{points.map((point, i) => {
const start = angle
angle += (point.count / total) * 360
const a = polar(cx, cy, radius, start),
b = polar(cx, cy, radius, angle)
const y = legendY
legendY += Math.max(24, wrap(point.label, legendW - 85).length * 16 + 9)
return (
<g key={point.label}>
{points.length === 1 ? (
<circle cx={cx} cy={cy} r={radius} fill={colors[i % colors.length]} />
) : (
<path
d={`M ${cx} ${cy} L ${a.x} ${a.y} A ${radius} ${radius} 0 ${angle - start > 180 ? 1 : 0} 1 ${b.x} ${b.y} Z`}
fill={colors[i % colors.length]}
stroke="#fff"
strokeWidth={1}
/>
)}
<title>{`${point.label}:${point.count}(${((point.count / total) * 100).toFixed(1)}%)`}</title>
<circle cx={22} cy={y - 4} r={4} fill={colors[i % colors.length]} />
<Text x={34} y={y} width={legendW - 91} value={point.label} size={11.5} />
<text x={legendW + 8} y={y} textAnchor="end" fill={ink} fontSize={11.5}>
{number(point.count)}
</text>
</g>
)
})}
</Panel>
)
}
function productRows(points: DashboardCount[], w: number) {
return points.map((p) => ({ point: p, lines: wrap(p.label, Math.max(70, w * 0.3), 11) }))
}
function productHeight(points: DashboardCount[], w: number) {
return Math.max(300, 75 + productRows(points, w).reduce((n, r) => n + Math.max(30, r.lines.length * 15 + 10), 0))
}
function Products({ box, points }: { box: Box; points: DashboardCount[] }) {
const left = Math.max(85, box.w * 0.32),
right = box.w - 58,
max = Math.max(1, ...points.map((p) => p.count))
let y = 78
return (
<Panel box={box} title="产品问题排行" en="Product Issue Ranking" id="products">
{points.length ? (
productRows(points, box.w).map(({ point, lines }) => {
const at = y
y += Math.max(30, lines.length * 15 + 10)
return (
<g key={point.label}>
<title>{`${point.label}:${point.count}`}</title>
<Text x={16} y={at + 2} width={left - 26} value={point.label} size={11} />
<rect
x={left}
y={at - 11}
width={Math.max(1, (point.count / max) * (right - left))}
height={15}
rx={2}
fill={blue}
/>
<text x={left + (point.count / max) * (right - left) + 5} y={at + 1} fontSize={11} fill={ink}>
{number(point.count)}
</text>
</g>
)
})
) : (
<text x={16} y={100} fill={muted} fontSize={13}>
暂无分类记录
</text>
)}
</Panel>
)
}
interface PlotPoint {
label: string
value: number | null
hint: string
frozen?: boolean
}
function Plot({
box,
title,
en,
id,
points,
percent = false,
}: {
box: Box
title: string
en: string
id: string
points: PlotPoint[]
percent?: boolean
}) {
const left = 44,
right = box.w - 22,
top = 74,
bottom = box.h - 47,
max = percent ? 100 : Math.max(4, Math.ceil(Math.max(0, ...points.map((p) => p.value ?? 0)) / 4) * 4),
x = (i: number) =>
points.length === 1 ? (left + right) / 2 : left + (i * (right - left)) / Math.max(1, points.length - 1),
y = (n: number) => bottom - (n / max) * (bottom - top)
let path = '',
open = false
for (let i = 0; i < points.length; i++) {
const value = points[i].value
if (value === null) {
open = false
continue
}
path += `${open ? 'L' : 'M'} ${x(i)} ${y(value)} `
open = true
}
const every = Math.max(1, Math.ceil(points.length / (box.w < 420 ? 5 : 8)))
return (
<Panel box={box} title={title} en={en} id={id}>
{Array.from({ length: 5 }, (_, i) => (
<g key={i}>
<line x1={left} x2={right} y1={y((max * i) / 4)} y2={y((max * i) / 4)} stroke={line} />
<text x={left - 9} y={y((max * i) / 4) + 4} textAnchor="end" fill={muted} fontSize={10}>
{(max * i) / 4}
{percent ? '%' : ''}
</text>
</g>
))}
{path ? <path d={path} fill="none" stroke={blue} strokeWidth={2} data-series={id} /> : null}
{points.map((point, i) => (
<g
key={point.label}
data-frozen={point.frozen === undefined ? undefined : point.frozen ? 'available' : 'missing'}
>
<title>{point.hint}</title>
{point.value !== null ? (
<>
<circle cx={x(i)} cy={y(point.value)} r={3} fill="#fff" stroke={blue} strokeWidth={1.5} />
{points.length <= 14 || i % every === 0 || i === points.length - 1 ? (
<text x={x(i)} y={Math.max(top - 9, y(point.value) - 9)} fill={blue} fontSize={10} textAnchor="middle">
{percent ? `${point.value.toFixed(1)}%` : number(point.value)}
</text>
) : null}
</>
) : null}
{i % every === 0 || i === points.length - 1 ? (
<text x={x(i)} y={bottom + 22} textAnchor="middle" fill={muted} fontSize={10}>
{point.label}
</text>
) : null}
</g>
))}
{!points.some((p) => p.value !== null) ? (
<text x={(left + right) / 2} y={(top + bottom) / 2} fill={muted} textAnchor="middle" fontSize={12}>
{percent ? '暂无冻结快照' : '暂无数据'}
</text>
) : null}
</Panel>
)
}
function regionalHeight(regions: DashboardRegion[], w: number) {
return Math.max(
290,
130 + regions.reduce((n, r) => n + Math.max(34, wrap(r.name, Math.max(70, w - 125), 11.5).length * 16 + 12), 0)
)
}
function RegionTable({
box,
regions,
frequency,
month,
}: {
box: Box
regions: DashboardRegion[]
frequency: boolean
month: string
}) {
const rows = [...regions].sort((a, b) => {
const av = frequency ? a.frequency : a.usage_coverage.percent,
bv = frequency ? b.frequency : b.usage_coverage.percent
return (bv ?? -1) - (av ?? -1) || a.name.localeCompare(b.name, 'zh-CN')
})
let y = 104
return (
<Panel
box={box}
title={frequency ? '区域平均使用频率' : '区域使用覆盖率'}
en={frequency ? 'Average usage frequency' : 'Usage coverage'}
id={frequency ? 'frequency' : 'usage-coverage'}
>
<rect x={10} y={57} width={box.w - 20} height={box.h - 68} rx={5} fill="#fff" stroke="#e4eaf2" />
<text x={19} y={77} fontSize={10.5} fill={muted}>
排名
</text>
<text x={58} y={77} fontSize={10.5} fill={muted}>
区域
</text>
<text x={box.w - 19} y={77} textAnchor="end" fontSize={10.5} fill={muted}>
{frequency ? '人均次数' : '使用覆盖率'}
</text>
<line x1={15} x2={box.w - 15} y1={85} y2={85} stroke={line} />
{rows.map((r, i) => {
const at = y,
value = frequency ? r.frequency : r.usage_coverage.percent
const h = Math.max(34, wrap(r.name, Math.max(70, box.w - 125), 11.5).length * 16 + 12)
y += h
return (
<g key={r.id}>
<title>{`${r.name};${month}月内提问 ${r.questions} 次;去重使用 ${r.users ?? '未知'} 人 / 通讯录归属 ${r.roster_people ?? '未知'} 人`}</title>
{i % 2 === 0 ? <rect x={11} y={at - 15} width={box.w - 22} height={h} fill="#f7faff" /> : null}
{value !== null && i < 3 ? (
<circle cx={30} cy={at - 4} r={9} fill={['#e9bd54', '#a8b6c9', '#dc9c73'][i]} />
) : null}
<text x={30} y={at} textAnchor="middle" fontSize={10.5} fill={value !== null && i < 3 ? '#fff' : muted}>
{value === null ? '—' : i + 1}
</text>
<Text x={53} y={at} width={Math.max(70, box.w - 125)} value={r.name} size={11.5} />
<text x={box.w - 19} y={at} textAnchor="end" fontSize={12} fill={ink}>
{value === null ? '—' : frequency ? value.toFixed(2) : `${value.toFixed(1)}%`}
</text>
</g>
)
})}
<text x={box.w - 17} y={box.h - 17} textAnchor="end" fontSize={9.5} fill={muted}>
{month}月累计
</text>
</Panel>
)
}
export function QADashboardDrawing({
data,
width,
svgRef,
}: {
data: QADashboardData
width: number
svgRef?: Ref<SVGSVGElement>
}) {
const w = Math.max(240, Math.round(width)),
pad = w < 700 ? 10 : 16,
gap = w < 700 ? 12 : 18,
inner = w - pad * 2,
mobile = w < 700,
unit = (inner - gap * 3) / 4,
week = currentQAWeek(new Date(data.week_start)),
filterLines = wrap(data.keyword ? `关键词:${data.keyword}` : '', inner - 16, 11),
header = 62 + (data.keyword ? filterLines.length * 15 : 0),
metricH = mobile ? 154 : 166
const metrics: Box[] = Array.from({ length: 4 }, (_, i) =>
mobile
? {
x: pad + ((i % 2) * (inner + gap)) / 2,
y: header + Math.floor(i / 2) * (metricH + gap),
w: (inner - gap) / 2,
h: metricH,
}
: { x: pad + i * (unit + gap), y: header, w: unit, h: metricH }
)
let cursor = header + (mobile ? 2 * metricH + gap : metricH) + gap
const pieW = mobile ? inner : (inner - gap) * 0.54,
productW = mobile ? inner : inner - gap - pieW,
pieH = pieHeight(data.issue_types, pieW),
productsH = productHeight(data.products, productW),
row2H = Math.max(pieH, productsH)
const pie: Box = { x: pad, y: cursor, w: pieW, h: mobile ? pieH : row2H },
products: Box = {
x: mobile ? pad : pad + pieW + gap,
y: mobile ? cursor + pieH + gap : cursor,
w: productW,
h: mobile ? productsH : row2H,
}
cursor += mobile ? pieH + productsH + gap * 2 : row2H + gap
const trendW = mobile ? inner : unit * 2 + gap,
regionW = mobile ? inner : unit,
regionH = regionalHeight(data.regions, regionW),
row3H = Math.max(290, regionH)
const trend: Box = { x: pad, y: cursor, w: trendW, h: mobile ? 270 : row3H },
freq: Box = {
x: mobile ? pad : pad + trendW + gap,
y: mobile ? cursor + trend.h + gap : cursor,
w: regionW,
h: mobile ? regionH : row3H,
},
usage: Box = {
x: mobile ? pad : pad + trendW + regionW + gap * 2,
y: mobile ? cursor + trend.h + regionH + gap * 2 : cursor,
w: regionW,
h: mobile ? regionH : row3H,
}
cursor += mobile ? trend.h + regionH * 2 + gap * 3 : row3H + gap
const historyW = mobile ? inner : (inner - gap) / 2,
coverage: Box = { x: pad, y: cursor, w: historyW, h: 270 },
accuracy: Box = {
x: mobile ? pad : pad + historyW + gap,
y: mobile ? cursor + 270 + gap : cursor,
w: historyW,
h: 270,
},
height = mobile ? cursor + 540 + gap + pad : cursor + 270 + pad
const frozen = (correctness: boolean): PlotPoint[] =>
data.frozen_weeks.map((p) => {
const rate = correctness ? p.correctness : p.coverage,
week = currentQAWeek(new Date(p.week_start))
return {
label: `${week.year}W${String(week.week).padStart(2, '0')}`,
value: rate.percent,
frozen: p.frozen_at !== null,
hint: p.frozen_at
? `${week.year}年第${week.week}周:${rate.numerator}/${rate.denominator};冻结于 ${p.frozen_at}`
: `${week.year}年第${week.week}周:缺少当时冻结快照`,
}
})
const month = new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7)
return (
<svg
ref={svgRef}
className="qa-dashboard-svg"
xmlns="http://www.w3.org/2000/svg"
width="100%"
viewBox={`0 0 ${w} ${height}`}
role="img"
aria-label="完整十一项问题统计看板"
style={{
display: 'block',
fontFamily: 'Arial, "Noto Sans CJK SC", "Microsoft YaHei", sans-serif',
fontVariantNumeric: 'tabular-nums',
background: '#fff',
}}
>
<title>
问题统计看板 · {week.year}年第{week.week}周
</title>
<rect width={w} height={height} fill="#fff" />
<text x={pad + 6} y={27} fontSize={mobile ? 17 : 21} fontWeight={700} fill={ink}>
问题统计看板
</text>
<text x={w - pad - 6} y={27} textAnchor="end" fontSize={12} fill={muted}>
{week.year} · W{String(week.week).padStart(2, '0')}
</text>
<text x={pad + 6} y={46} fontSize={10.5} fill={muted}>
{data.week_start.slice(0, 10)} 起的自然周 · 区域统计 {month} 月累计
</text>
{data.keyword ? (
<Text x={pad + 6} y={62} width={inner - 16} value={`关键词:${data.keyword}`} size={11} fill={muted} />
) : null}
<Metric
box={metrics[0]}
title="问题总数"
en="Total Issues"
id="total"
value={data.total_issues}
tint="#fff4e2"
color="#c69b00"
subtitle="所选周截止前累计"
/>
<Metric
box={metrics[1]}
title="本周新增"
en="New This week"
id="new-week"
value={data.new_this_week}
tint="#ececff"
color="#4056d6"
subtitle="所选自然周"
/>
<Gauge box={metrics[2]} title="覆盖率" en="Coverage Rate" id="coverage" rate={data.quality.rates.coverage} />
<Gauge box={metrics[3]} title="正确率" en="Accuracy Rate" id="accuracy" rate={data.quality.rates.correctness} />
<Pie box={pie} points={data.issue_types} />
<Products box={products} points={data.products} />
<Plot
box={trend}
title="问题趋势"
en="Issue Trend"
id="issue-trend"
points={data.daily.map((p) => ({ label: p.date.slice(5), value: p.count, hint: `${p.date}:${p.count} 条` }))}
/>
<RegionTable box={freq} regions={data.regions} frequency month={month} />
<RegionTable box={usage} regions={data.regions} frequency={false} month={month} />
<Plot
box={coverage}
title="覆盖率趋势"
en="Coverage Rate Trend"
id="coverage-trend"
points={frozen(false)}
percent
/>
<Plot
box={accuracy}
title="正确率趋势"
en="Accuracy Rate Trend"
id="accuracy-trend"
points={frozen(true)}
percent
/>
</svg>
)
}
+2 -3
View File
@@ -334,8 +334,9 @@ export function QAOperations() {
useEffect(() => {
if (!query || !canRead) return
if (view !== 'records' && view !== 'dashboard') {
if (view !== 'records') {
setLoading(false)
setError(null)
detailRequest.current?.abort()
setDetail(null)
return
@@ -504,9 +505,7 @@ export function QAOperations() {
<QAWeekly query={query} />
) : view === 'dashboard' ? (
<QADashboard
page={page}
query={query}
loading={loading}
error={error}
revision={qualityRevision}
onRetry={() => {
+7 -166
View File
@@ -10,146 +10,19 @@
flex-direction: column;
gap: 16px;
}
.qa-dashboard-metrics {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
border: 1px solid var(--border-base);
background: var(--bg-panel);
}
.qa-dashboard-metrics > div {
padding: 18px 22px;
.qa-dashboard-toolbar {
display: flex;
flex-direction: column;
gap: 8px;
border-right: 1px solid var(--border-base);
justify-content: flex-end;
}
.qa-dashboard-metrics > div:last-child {
border-right: 0;
}
.qa-dashboard-metrics span {
color: var(--ink-mute);
font-size: 12px;
}
.qa-dashboard-metrics strong {
color: var(--ink-strong);
font-size: 30px;
font-weight: 650;
font-variant-numeric: tabular-nums;
letter-spacing: -0.04em;
}
.qa-dashboard-metrics small {
font-size: 11px;
color: var(--ink-mute);
}
.qa-dashboard-grid {
display: grid;
grid-template-columns: minmax(0, 1.6fr) minmax(260px, 1fr);
gap: 14px;
}
.qa-chart {
.qa-dashboard-canvas {
min-width: 0;
padding: 18px 20px;
background: var(--bg-panel);
border: 1px solid var(--border-base);
}
.qa-chart-full {
grid-column: 1/-1;
}
.qa-chart h3 {
font-size: 14px;
font-weight: 600;
margin: 0 0 20px;
color: var(--ink-strong);
}
.qa-chart-bars {
display: grid;
gap: 13px;
}
.qa-chart-bar {
display: grid;
grid-template-columns: minmax(70px, 120px) minmax(0, 1fr) 40px;
gap: 12px;
align-items: center;
font-size: 12px;
}
.qa-chart-bar > span {
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
background: #fff;
}
.qa-chart-bar b {
text-align: right;
font-weight: 500;
font-variant-numeric: tabular-nums;
}
.qa-chart-track {
height: 7px;
background: var(--bg-canvas, #f1f5f9);
overflow: hidden;
border-radius: 2px;
}
.qa-chart-track i {
display: block;
height: 100%;
background: #377bc9;
border-radius: 2px;
}
.qa-chart-empty {
padding: 28px 0;
text-align: center;
color: var(--ink-mute);
font-size: 12px;
}
.qa-daily-chart {
display: flex;
gap: clamp(6px, 1.5vw, 22px);
height: 180px;
align-items: stretch;
overflow-x: auto;
}
.qa-daily-chart > div {
flex: 1;
min-width: 24px;
display: flex;
flex-direction: column;
align-items: center;
gap: 7px;
font-size: 11px;
color: var(--ink-mute);
}
.qa-daily-chart > div > div {
height: 125px;
.qa-dashboard-svg {
width: 100%;
display: flex;
align-items: flex-end;
border-bottom: 1px solid var(--border-base);
}
.qa-daily-chart i {
display: block;
width: 100%;
background: #377bc9;
border-radius: 2px 2px 0 0;
min-height: 0;
}
.qa-daily-chart b {
font-size: 11px;
color: var(--ink-strong);
font-variant-numeric: tabular-nums;
font-weight: 500;
}
.qa-dashboard-region-table {
margin-top: 18px;
overflow-x: auto;
}
.qa-dashboard-region-table table {
width: 100%;
font-size: 12px;
}
.qa-dashboard-region-table th,
.qa-dashboard-region-table td {
padding: 8px 10px;
text-align: left;
white-space: normal;
height: auto;
}
.qa-monthly-disclosure {
margin-top: 14px;
@@ -166,38 +39,6 @@
margin-top: 12px;
overflow: auto;
}
@media (max-width: 900px) {
.qa-dashboard-grid {
grid-template-columns: minmax(0, 1fr);
}
.qa-chart-full {
grid-column: auto;
}
.qa-dashboard-metrics > div {
padding: 14px;
}
.qa-dashboard-metrics strong {
font-size: 25px;
}
}
@media (max-width: 560px) {
.qa-dashboard-metrics {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.qa-dashboard-metrics > div:nth-child(2) {
border-right: 0;
}
.qa-dashboard-metrics > div:nth-child(-n + 2) {
border-bottom: 1px solid var(--border-base);
}
.qa-chart {
padding: 16px 12px;
}
.qa-chart-bar {
grid-template-columns: minmax(65px, 100px) minmax(0, 1fr) 30px;
}
}
.qa-weekly {
display: flex;
flex-direction: column;
+89
View File
@@ -0,0 +1,89 @@
export const dashboardFixture = {
start: '2026-10-05T00:00:00+08:00',
end: '2026-10-12T00:00:00+08:00',
keyword: '',
as_of: '2026-10-18T10:00:00Z',
local_revision: 1,
organization: {
state: 'ready',
directory_id: 'd',
directory_source: 'weekly_report_live',
synced_at: '2026-10-17T10:00:00Z',
revision_id: 'r',
basis: 'current_directory',
region_names: ['国内教育'],
},
total_issues: 4,
new_this_week: 2,
week_start: '2026-10-05T00:00:00+08:00',
month_start: '2026-10-01T00:00:00+08:00',
quality: {
total: 2,
reviewed: 1,
unreviewed: 1,
stale: 0,
pending_confirmation: 0,
rule_uncovered: 1,
rates: {
policy_version: 'quality-rates-human-first-v1',
coverage: { numerator: 1, denominator: 2, percent: 50 },
correctness: { numerator: 1, denominator: 1, percent: 100 },
breakdown: {
covered: 1,
uncovered: 1,
partial: 0,
pending: 0,
unassessed: 0,
excluded: 0,
stale: 0,
covered_correct: 1,
covered_incorrect: 0,
covered_pending: 0,
covered_unassessed: 0,
},
},
},
issue_types: [
{ label: '使用咨询', count: 1 },
{ label: '未分类', count: 1 },
],
products: [
{ label: '<img src=x onerror=alert(1)>', count: 1 },
{ label: '未分类', count: 1 },
],
daily: Array.from({ length: 7 }, (_, i) => ({
date: `2026-10-${String(i + 5).padStart(2, '0')}`,
count: i === 1 || i === 5 ? 1 : 0,
})),
regions: [
{
id: 'education',
name: '国内教育',
questions: 3,
users: 1,
roster_people: 2,
frequency: 1.5,
usage_coverage: { numerator: 1, denominator: 2, percent: 50 },
},
],
frozen_weeks: [
{
week_start: '2026-09-28T00:00:00+08:00',
week_end: '2026-10-05T00:00:00+08:00',
frozen_at: null,
policy_version: '',
records: 0,
coverage: { numerator: 0, denominator: 0, percent: null },
correctness: { numerator: 0, denominator: 0, percent: null },
},
{
week_start: '2026-10-05T00:00:00+08:00',
week_end: '2026-10-12T00:00:00+08:00',
frozen_at: '2026-10-12T00:06:00+08:00',
policy_version: 'quality-rates-human-first-v1',
records: 2,
coverage: { numerator: 1, denominator: 2, percent: 50 },
correctness: { numerator: 1, denominator: 1, percent: 100 },
},
],
}
+25
View File
@@ -0,0 +1,25 @@
import { describe, it, expect } from 'vitest'
import { parseQADashboard } from './qaDashboardData'
import { dashboardFixture } from './qaDashboard.fixture'
describe('complete dashboard data contract', () => {
it('keeps distinct cumulative, week, month and genuinely frozen periods', () => {
const data = parseQADashboard(dashboardFixture)
expect([data.total_issues, data.new_this_week, data.regions[0].questions]).toEqual([4, 2, 3])
expect(data.frozen_weeks[0].coverage.percent).toBeNull()
expect(data.frozen_weeks[1].coverage.percent).toBe(50)
})
it('rejects fabricated percentages, category omissions and historical backfill', () => {
for (const bad of [
{ ...dashboardFixture, new_this_week: 5 },
{ ...dashboardFixture, products: [] },
{ ...dashboardFixture, regions: [{ ...dashboardFixture.regions[0], frequency: 3 }] },
{
...dashboardFixture,
frozen_weeks: [
{ ...dashboardFixture.frozen_weeks[0], coverage: { numerator: 1, denominator: 2, percent: 50 } },
],
},
])
expect(() => parseQADashboard(bad)).toThrow()
})
})
+230
View File
@@ -0,0 +1,230 @@
import { parseQAOrganizationVersion } from './qaOps'
import type { QAOrganizationVersion, QAQuery } from './qaOps'
import { parseQualitySummary, parseQualityRate } from './qaQuality'
import type { QualitySummary, QualityRate } from './qaQuality'
export interface DashboardCount {
label: string
count: number
}
export interface DashboardFrozen {
week_start: string
week_end: string
frozen_at: string | null
policy_version: string
records: number
coverage: QualityRate
correctness: QualityRate
}
export interface DashboardRegion {
id: string
name: string
questions: number
users: number | null
roster_people: number | null
frequency: number | null
usage_coverage: QualityRate
}
export interface QADashboardData {
start: string
end: string
keyword: string
as_of: string
local_revision: number
organization: QAOrganizationVersion
total_issues: number
new_this_week: number
week_start: string
month_start: string
quality: QualitySummary['summary']
issue_types: DashboardCount[]
products: DashboardCount[]
daily: { date: string; count: number }[]
regions: DashboardRegion[]
frozen_weeks: DashboardFrozen[]
}
const bad = (): never => {
throw new Error('统计看板响应无效,未展示可能失真的指标')
}
const obj = (v: unknown): Record<string, unknown> =>
v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : bad()
const text = (v: unknown): string => (typeof v === 'string' ? v : bad())
const count = (v: unknown): number => (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? v : bad())
const stamp = (v: unknown): string => {
const s = text(v)
return Number.isFinite(Date.parse(s)) ? s : bad()
}
const list = (v: unknown): unknown[] => (Array.isArray(v) ? v : bad())
const dayMS = 86400000,
offset = 8 * 3600000
const day = (at: number) => Math.floor((at + offset) / dayMS) * dayMS - offset
const monday = (at: number) => {
const d = day(at)
return d - ((new Date(d + offset).getUTCDay() + 6) % 7) * dayMS
}
const month = (at: number) => {
const d = new Date(at + offset)
return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), 1) - offset
}
function categories(value: unknown, total: number): DashboardCount[] {
const seen = new Set<string>()
const out = list(value).map((raw) => {
const v = obj(raw),
label = text(v.label),
n = count(v.count)
if (!label || seen.has(label) || !n) return bad()
seen.add(label)
return { label, count: n }
})
if (out.reduce((n, r) => n + r.count, 0) !== total) return bad()
return out
}
export function parseQADashboard(value: unknown): QADashboardData {
const v = obj(value),
start = stamp(v.start),
end = stamp(v.end),
keyword = text(v.keyword),
as_of = stamp(v.as_of),
week_start = stamp(v.week_start),
month_start = stamp(v.month_start)
if (
Date.parse(start) >= Date.parse(end) ||
Date.parse(week_start) !== monday(Date.parse(end) - 1) ||
Date.parse(month_start) !== month(Date.parse(end) - 1)
)
return bad()
const quality = parseQualitySummary({
summary: v.quality,
start,
end,
keyword,
as_of,
scope: 'whole_filter',
ai_state: 'not_configured',
}).summary
const organization = parseQAOrganizationVersion(v.organization),
total_issues = count(v.total_issues),
new_this_week = count(v.new_this_week)
if (new_this_week > total_issues || quality.total > total_issues) return bad()
const regionIDs = new Set<string>(),
regionNames = new Set<string>()
const regions = list(v.regions).map((raw) => {
const r = obj(raw),
id = text(r.id),
name = text(r.name),
questions = count(r.questions),
users = r.users === null ? null : count(r.users),
roster_people = r.roster_people === null ? null : count(r.roster_people),
usage_coverage = parseQualityRate(r.usage_coverage)
if (!id || !name || regionIDs.has(id) || regionNames.has(name) || !organization.region_names?.includes(name))
return bad()
regionIDs.add(id)
regionNames.add(name)
if (
(users === null) !== (roster_people === null) ||
(users !== null && roster_people !== null && users > roster_people)
)
return bad()
if (usage_coverage.numerator !== (users ?? 0) || usage_coverage.denominator !== (roster_people ?? 0)) return bad()
let frequency: number | null = null
if (roster_people !== null && roster_people > 0) {
if (
typeof r.frequency !== 'number' ||
!Number.isFinite(r.frequency) ||
r.frequency < 0 ||
Math.abs(r.frequency - questions / roster_people) > 1e-8
)
return bad()
frequency = r.frequency
} else if (r.frequency !== null) return bad()
return { id, name, questions, users, roster_people, frequency, usage_coverage }
})
if (regions.length !== (organization.region_names?.length ?? 0)) return bad()
const daily = list(v.daily).map((raw, i) => {
const d = obj(raw),
date = text(d.date),
n = count(d.count)
if (
!/^\d{4}-\d{2}-\d{2}$/.test(date) ||
Date.parse(date + 'T00:00:00+08:00') !== Date.parse(week_start) + i * dayMS
)
return bad()
return { date, count: n }
})
if (
daily.length < 1 ||
daily.length > 7 ||
daily.reduce((n, r) => n + r.count, 0) !== new_this_week ||
Date.parse(daily[daily.length - 1].date + 'T00:00:00+08:00') >= Date.parse(end)
)
return bad()
const frozen_weeks = list(v.frozen_weeks).map((raw, i) => {
const p = obj(raw),
week_start = stamp(p.week_start),
week_end = stamp(p.week_end),
frozen_at = p.frozen_at === null ? null : stamp(p.frozen_at),
policy_version = text(p.policy_version),
records = count(p.records),
coverage = parseQualityRate(p.coverage),
correctness = parseQualityRate(p.correctness)
if (
monday(Date.parse(week_start)) !== Date.parse(week_start) ||
Date.parse(week_end) - Date.parse(week_start) !== 7 * dayMS ||
Date.parse(week_start) >= Date.parse(end) ||
coverage.denominator > records ||
correctness.denominator > records
)
return bad()
if (frozen_at === null) {
if (policy_version || records || coverage.denominator || correctness.denominator) return bad()
} else if (!policy_version || Date.parse(frozen_at) < Date.parse(week_end)) return bad()
const previous = list(v.frozen_weeks)[i - 1]
if (i > 0 && Date.parse(week_start) !== Date.parse(text(obj(previous).week_end))) return bad()
return { week_start, week_end, frozen_at, policy_version, records, coverage, correctness }
})
if (
frozen_weeks.length > 5200 ||
(frozen_weeks.length && Date.parse(frozen_weeks[frozen_weeks.length - 1].week_end) < Date.parse(end))
)
return bad()
return {
start,
end,
keyword,
as_of,
week_start,
month_start,
local_revision: count(v.local_revision),
organization,
total_issues,
new_this_week,
quality,
issue_types: categories(v.issue_types, quality.total),
products: categories(v.products, quality.total),
daily,
regions,
frozen_weeks,
}
}
export async function fetchQADashboard(query: QAQuery, signal?: AbortSignal): Promise<QADashboardData> {
const response = await fetch('/api/v1/qa-ops/dashboard', {
method: 'POST',
credentials: 'same-origin',
cache: 'no-store',
signal,
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-dashboard' },
body: JSON.stringify({ start: query.start, end: query.end, keyword: query.keyword }),
})
const body: unknown = await response.json().catch(() => null)
if (!response.ok) {
const message = body && typeof body === 'object' ? (body as Record<string, unknown>).error : undefined
throw new Error(typeof message === 'string' ? message : `统计看板读取失败(HTTP ${response.status})`)
}
const data = parseQADashboard(obj(body).data)
if (
Date.parse(data.start) !== Date.parse(query.start) ||
Date.parse(data.end) !== Date.parse(query.end) ||
data.keyword !== query.keyword
)
throw new Error('看板返回范围与当前查询不一致,请重新读取')
return data
}
+14
View File
@@ -0,0 +1,14 @@
import { it, expect } from 'vitest'
import { dashboardExportSize } from './qaDashboardExport'
it('exports the complete viewBox at double resolution and refuses unsafe canvas sizes', () => {
expect(dashboardExportSize(1280, 1500)).toEqual({ width: 1280 * 2, height: 1500 * 2, scale: 2 })
expect(dashboardExportSize(2000, 9000)).toEqual({ width: 2000, height: 9000, scale: 1 })
for (const size of [
[0, 100],
[-1, 100],
[Infinity, 100],
[100, 40000],
[20000, 20000],
])
expect(() => dashboardExportSize(...(size as [number, number]))).toThrow()
})
+48
View File
@@ -0,0 +1,48 @@
export function dashboardExportSize(w: number, h: number): { width: number; height: number; scale: number } {
if (!Number.isFinite(w) || !Number.isFinite(h) || w <= 0 || h <= 0 || w > 32760 || h > 32760 || w * h > 64000000)
throw new Error('看板过大,无法完整生成 PNG,请缩小统计范围')
const scale = w * 2 <= 32760 && h * 2 <= 32760 && w * h * 4 <= 64000000 ? 2 : 1
return { width: Math.ceil(w * scale), height: Math.ceil(h * scale), scale }
}
export async function createDashboardPNG(svg: SVGSVGElement): Promise<Blob> {
const box = svg.viewBox.baseVal,
size = dashboardExportSize(box.width, box.height),
copy = svg.cloneNode(true) as SVGSVGElement
if (
copy.querySelectorAll('[data-panel]').length !== 11 ||
copy.querySelector('foreignObject,image,script,iframe,use')
)
throw new Error('看板内容不完整,未生成图片')
copy.setAttribute('width', String(box.width))
copy.setAttribute('height', String(box.height))
copy.style.width = `${box.width}px`
copy.style.height = `${box.height}px`
copy.style.fontFamily = getComputedStyle(svg).fontFamily
if (document.fonts) await document.fonts.ready
const source = new Blob([new XMLSerializer().serializeToString(copy)], { type: 'image/svg+xml;charset=utf-8' }),
url = URL.createObjectURL(source)
try {
const image = new Image()
await new Promise<void>((resolve, reject) => {
image.onload = () => resolve()
image.onerror = () => reject(new Error('看板图片绘制失败'))
image.src = url
})
const canvas = document.createElement('canvas')
canvas.width = size.width
canvas.height = size.height
const context = canvas.getContext('2d', { alpha: false })
if (!context) throw new Error('浏览器无法创建完整图片画布')
context.fillStyle = '#fff'
context.fillRect(0, 0, size.width, size.height)
context.drawImage(image, 0, 0, size.width, size.height)
return await new Promise<Blob>((resolve, reject) =>
canvas.toBlob(
(blob) => (blob && blob.size > 0 ? resolve(blob) : reject(new Error('PNG生成失败,请重试'))),
'image/png'
)
)
} finally {
URL.revokeObjectURL(url)
}
}
+1
View File
@@ -238,6 +238,7 @@ function qualityRate(value: unknown): QualityRate {
return bad()
return { numerator, denominator, percent: v.percent }
}
export { qualityRate as parseQualityRate }
function qualityRates(value: unknown, total: number, stale: number): QualityRates {
const v = obj(value),
r = obj(v.breakdown)