diff --git a/CHANGELOG.md b/CHANGELOG.md index 609341b..9c46734 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -76,6 +76,17 @@ > `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯, > 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。 +## 开发快照 snapshot/v0.1.37 - 2026-10-19 + +### Added + +- 统计看板的覆盖率、正确率趋势支持独立持久保存的用户历史报表值,按北京时间ISO自然周展示、精确到两位小数并注明来源;和系统冻结使用分开的曲线,不伪造记录数、分子分母或冻结时间。 + +### Changed + +- 历史汇总只影响两个趋势图,不覆盖当前周质量或原始问答;关键词筛选不挪用无明细的历史汇总,所选截止后的数据不提前展示,缺失周留空。页面和完整PNG共用相同绘图数据。 +- 增加治理侧迁移57:历史统计独立表保留来源指纹与导入审计,禁止原位覆盖/删除,存在历史数据时拒绝破坏性down;普通来源同步不能覆盖该表,不修改DobotAI生产或既有冻结证据。 + ## 开发快照 snapshot/v0.1.36 - 2026-10-19 ### Added diff --git a/api/openapi.yaml b/api/openapi.yaml index a0b6c7b..75844cd 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -56,7 +56,7 @@ "get": {"tags":["QA operations"],"operationId":"getQAOrganizationSync","summary":"管理员读取通讯录同步执行器状态及最近任务的安全汇总,不返回人员名单或运行配置","responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"状态存储不可用,不伪装为空记录"}}}, "post": {"tags":["QA operations"],"operationId":"startQAOrganizationSync","summary":"管理员同源发起持久化通讯录同步;重复请求重放同一任务,进行中任务合并;失败保留现有快照","parameters":[{"$ref":"#/components/parameters/IdempotencyKey"},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-organization"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false}}}},"responses":{"202":{"$ref":"#/components/responses/OperationEnvelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员同源操作"},"409":{"description":"操作标识与原请求冲突"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"同步未接线、执行器离线或入队失败;未创建新任务"}}} }, - "/api/v1/qa-ops/dashboard": {"post":{"operationId":"readQAOperationsDashboard","tags":["QA operations"],"summary":"管理员只读正式总表一致性看板:累计、所选周、新增/有效质量/类别及截止月区域统计;历史质量仅真实冻结快照,缺失留空","description":"同一只读可重复读事务读取独立正式总表有效字段、质量及组织版本。不访问源端,不冻结或写入指标;区域分母为当前配置通讯录去重人数而非在职/绩效名单。冻结记录按保存的原始标量分子分母及问题文字支持字面关键词筛选,不用当前评估回填历史。","parameters":[{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-dashboard"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["start","end"],"properties":{"start":{"type":"string","format":"date-time"},"end":{"type":"string","format":"date-time"},"keyword":{"type":"string","maxLength":200}}}}}},"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员同源读取"},"409":{"description":"质量输入指纹变化,拒绝混合数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"本地副本或一致性投影不可用,不返回伪零"}}}}, + "/api/v1/qa-ops/dashboard": {"post":{"operationId":"readQAOperationsDashboard","tags":["QA operations"],"summary":"管理员只读正式总表一致性看板:累计、所选周、新增/有效质量/类别及截止月区域统计;历史趋势区分用户提供百分比与真实冻结快照,缺失留空","description":"同一只读可重复读事务读取独立正式总表有效字段、质量及组织版本。不访问源端,不冻结或写入指标;区域分母为当前配置通讯录去重人数而非在职/绩效名单。冻结记录按保存的原始标量分子分母及问题文字支持字面关键词筛选,不用当前评估回填历史。reported_weeks 独立返回用户提供的历史百分比(QAReportedHistoricalRate),没有分子分母或冻结时间;只含所选截止前已结束周,关键词非空时为空,原冻结记录与当前指标保持不变。","parameters":[{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-dashboard"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["start","end"],"properties":{"start":{"type":"string","format":"date-time"},"end":{"type":"string","format":"date-time"},"keyword":{"type":"string","maxLength":200}}}}}},"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员同源读取"},"409":{"description":"质量输入指纹变化,拒绝混合数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"本地副本或一致性投影不可用,不返回伪零"}}}}, "/api/v1/qa-ops/organization": { "get": { "tags": ["QA operations"], @@ -4392,6 +4392,48 @@ } }, "schemas": { + "QAReportedHistoricalRate": { + "type": "object", + "additionalProperties": false, + "required": [ + "week", + "week_start", + "week_end", + "coverage_percent", + "correctness_percent", + "source" + ], + "properties": { + "week": { + "type": "string", + "pattern": "^[0-9]{4}WK[0-9]{2}$" + }, + "week_start": { + "type": "string", + "format": "date-time" + }, + "week_end": { + "type": "string", + "format": "date-time" + }, + "coverage_percent": { + "type": "number", + "minimum": 0, + "maximum": 100, + "multipleOf": 0.01 + }, + "correctness_percent": { + "type": "number", + "minimum": 0, + "maximum": 100, + "multipleOf": 0.01 + }, + "source": { + "const": "user_provided_history" + } + }, + "description": "用户提供的历史报表百分比,不含也不推导分子、分母、记录数或冻结时点;不按现行规则重算,不用于关键词统计。" + }, "QAAISafeSettings": {"type": "object", "additionalProperties": false, "properties": {"revision": {"type": "integer", "minimum": 0}, "base_url": {"type": "string", "maxLength": 500, "description": "管理员配置的模型API地址,禁止地址内凭据、query或fragment"}, "model": {"type": "string", "maxLength": 200}, "key_configured": {"type": "boolean"}, "verification": {"enum": ["not_configured", "verified", "unverified", "rejected"]}, "checked_at": {"type": ["string", "null"], "format": "date-time"}, "automatic_evaluation": {"type": "boolean"}, "automatic_translation": {"type": "boolean"}, "storage_ready": {"type": "boolean"}}, "required": ["revision", "base_url", "model", "key_configured", "verification", "checked_at", "automatic_evaluation", "automatic_translation", "storage_ready"]}, "QAAISaveSettings": {"type": "object", "additionalProperties": false, "properties": {"base_revision": {"type": "integer", "minimum": 0}, "base_url": {"type": "string", "maxLength": 500, "description": "管理员配置的模型API地址,禁止地址内凭据、query或fragment"}, "model": {"type": "string", "maxLength": 200}, "key_action": {"enum": ["keep", "replace", "clear"]}, "api_key": {"type": "string", "writeOnly": true, "maxLength": 4096, "description": "仅replace携带;keep/clear不可携带;HTTPS或本机回环传输;响应不返回"}}, "required": ["base_revision", "base_url", "model", "key_action"]}, "QAAIBatch": {"type": "object", "additionalProperties": false, "properties": {"id": {"type": "string"}, "kind": {"type": "string", "enum": ["evaluation", "translation"]}, "state": {"enum": ["active", "paused"]}, "total": {"type": "integer", "minimum": 0}, "succeeded": {"type": "integer", "minimum": 0}, "failed": {"type": "integer", "minimum": 0}, "skipped": {"type": "integer", "minimum": 0}, "running": {"type": "integer", "minimum": 0}, "queued": {"type": "integer", "minimum": 0}, "retry": {"type": "integer", "minimum": 0}, "paused": {"type": "integer", "minimum": 0}, "created_at": {"type": "string", "format": "date-time"}}, "required": ["id", "kind", "state", "total", "succeeded", "failed", "skipped", "running", "queued", "retry", "paused", "created_at"]}, diff --git a/internal/platform/postgres/migrations/000057_qa_reported_history.down.sql b/internal/platform/postgres/migrations/000057_qa_reported_history.down.sql new file mode 100644 index 0000000..1ee8a1a --- /dev/null +++ b/internal/platform/postgres/migrations/000057_qa_reported_history.down.sql @@ -0,0 +1,7 @@ +DO $$ BEGIN + IF EXISTS (SELECT 1 FROM qa_ops_reported_weekly_rates) THEN + RAISE EXCEPTION 'cannot discard imported historical rates during rollback' USING ERRCODE='55000'; + END IF; +END $$; +DROP TABLE qa_ops_reported_weekly_rates; +DROP FUNCTION qa_ops_reported_history_immutable(); diff --git a/internal/platform/postgres/migrations/000057_qa_reported_history.up.sql b/internal/platform/postgres/migrations/000057_qa_reported_history.up.sql new file mode 100644 index 0000000..08abb50 --- /dev/null +++ b/internal/platform/postgres/migrations/000057_qa_reported_history.up.sql @@ -0,0 +1,21 @@ +-- Percent-only historical reports stay separate from computed/frozen evidence. +CREATE TABLE qa_ops_reported_weekly_rates ( + tenant_key TEXT NOT NULL CHECK (tenant_key<>'' AND length(tenant_key)<=128), + week_key TEXT NOT NULL CHECK (week_key ~ '^[0-9]{4}WK[0-9]{2}$'), + week_start TIMESTAMPTZ NOT NULL, + week_end TIMESTAMPTZ NOT NULL, + coverage_bp INTEGER NOT NULL CHECK (coverage_bp BETWEEN 0 AND 10000), + correctness_bp INTEGER NOT NULL CHECK (correctness_bp BETWEEN 0 AND 10000), + source_sha256 TEXT NOT NULL CHECK (source_sha256 ~ '^[a-f0-9]{64}$'), + imported_by TEXT NOT NULL CHECK (btrim(imported_by)<>''), + imported_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (tenant_key,week_key), + UNIQUE (tenant_key,week_start), + CHECK (week_end=week_start+interval '168 hours'), + CHECK (extract(isodow FROM week_start AT TIME ZONE 'Asia/Shanghai')=1), + CHECK ((week_start AT TIME ZONE 'Asia/Shanghai')::time=time '00:00:00'), + CHECK (week_key=to_char(week_start AT TIME ZONE 'Asia/Shanghai','IYYY"WK"IW')) +); +CREATE FUNCTION qa_ops_reported_history_immutable() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN RAISE EXCEPTION 'reported historical rates are immutable; keep the original source' USING ERRCODE='55000'; END $$; +CREATE TRIGGER qa_reported_history_immutable BEFORE UPDATE OR DELETE ON qa_ops_reported_weekly_rates FOR EACH ROW EXECUTE FUNCTION qa_ops_reported_history_immutable(); diff --git a/internal/platform/postgres/migrations_test.go b/internal/platform/postgres/migrations_test.go index d659a1e..982c6d7 100644 --- a/internal/platform/postgres/migrations_test.go +++ b/internal/platform/postgres/migrations_test.go @@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) { if err != nil { t.Fatalf("loadMigrations() error = %v", err) } - if len(migrations) != 56 { - t.Fatalf("migration count = %d, want 56", len(migrations)) + if len(migrations) != 57 { + t.Fatalf("migration count = %d, want 57", len(migrations)) } if migrations[0].Version != 1 || !strings.Contains(migrations[0].UpSQL, "CREATE TABLE IF NOT EXISTS jobs") { t.Fatalf("migration 1 = %#v", migrations[0]) diff --git a/internal/qaopsmirror/dashboard.go b/internal/qaopsmirror/dashboard.go index 72cb18f..880df88 100644 --- a/internal/qaopsmirror/dashboard.go +++ b/internal/qaopsmirror/dashboard.go @@ -14,6 +14,15 @@ type DashboardDaily struct { Date string `json:"date"` Count int `json:"count"` } +type DashboardReported struct { + Week string `json:"week"` + WeekStart time.Time `json:"week_start"` + WeekEnd time.Time `json:"week_end"` + CoveragePercent float64 `json:"coverage_percent"` + CorrectnessPercent float64 `json:"correctness_percent"` + Source string `json:"source"` +} + type DashboardFrozen struct { WeekStart time.Time `json:"week_start"` WeekEnd time.Time `json:"week_end"` @@ -49,6 +58,7 @@ type Dashboard struct { Daily []DashboardDaily `json:"daily"` Regions []DashboardRegion `json:"regions"` FrozenWeeks []DashboardFrozen `json:"frozen_weeks"` + ReportedWeeks []DashboardReported `json:"reported_weeks"` } var dashboardLocation = time.FixedZone("Asia/Shanghai", 8*60*60) diff --git a/internal/qaopsmirror/dashboard_reported.go b/internal/qaopsmirror/dashboard_reported.go new file mode 100644 index 0000000..231d0e1 --- /dev/null +++ b/internal/qaopsmirror/dashboard_reported.go @@ -0,0 +1,36 @@ +package qaopsmirror + +import ( + "context" + "github.com/jackc/pgx/v5" + "knowledge-governance/internal/dobotaiops" + "time" +) + +// Supplied aggregates have neither row-level evidence nor a keyword denominator. +func (s *Store) readReportedDashboard(ctx context.Context, tx pgx.Tx, keyword string, end time.Time) ([]DashboardReported, error) { + out := []DashboardReported{} + if keyword != "" { + return out, nil + } + rows, err := tx.Query(ctx, `SELECT week_key,week_start,week_end,coverage_bp,correctness_bp FROM qa_ops_reported_weekly_rates WHERE tenant_key=$1 AND week_end<=$2 ORDER BY week_start`, s.tenant, end) + if err != nil { + return nil, dobotaiops.ErrUnavailable + } + defer rows.Close() + for rows.Next() { + var p DashboardReported + var coverage, correctness int + if rows.Scan(&p.Week, &p.WeekStart, &p.WeekEnd, &coverage, &correctness) != nil { + return nil, dobotaiops.ErrUnavailable + } + p.CoveragePercent = float64(coverage) / 100 + p.CorrectnessPercent = float64(correctness) / 100 + p.Source = "user_provided_history" + out = append(out, p) + } + if rows.Err() != nil { + return nil, dobotaiops.ErrUnavailable + } + return out, nil +} diff --git a/internal/qaopsmirror/dashboard_reported_integration_test.go b/internal/qaopsmirror/dashboard_reported_integration_test.go new file mode 100644 index 0000000..460e579 --- /dev/null +++ b/internal/qaopsmirror/dashboard_reported_integration_test.go @@ -0,0 +1,77 @@ +package qaopsmirror + +import ( + "context" + "encoding/json" + "errors" + "github.com/jackc/pgx/v5/pgconn" + "knowledge-governance/internal/dobotaiops" + pg "knowledge-governance/internal/platform/postgres" + "strings" + "testing" + "time" +) + +func TestReportedHistoryIsIndependentExactScopedAndImmutable(t *testing.T) { + p := mirrorFixture(t) + ctx := context.Background() + s := NewStore(p, "fixture-reported-history") + insert := `INSERT INTO qa_ops_reported_weekly_rates(tenant_key,week_key,week_start,week_end,coverage_bp,correctness_bp,source_sha256,imported_by) VALUES($1,'2026WK40','2026-09-28T00:00:00+08:00','2026-10-05T00:00:00+08:00',5723,9234,$2,'fixture-admin')` + if _, err := p.Exec(ctx, insert, s.tenant, strings.Repeat("a", 64)); err != nil { + t.Fatal(err) + } + start, _ := time.Parse(time.RFC3339, "2026-10-05T00:00:00+08:00") + end := start.AddDate(0, 0, 7) + read := func(tenant, keyword string, until time.Time) map[string]any { + t.Helper() + data, err := NewStore(p, tenant).ReadMasterDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: tenant, Start: until.AddDate(0, 0, -7), End: until}, Keyword: keyword}) + if err != nil { + t.Fatal(err) + } + raw, _ := json.Marshal(data) + var wire map[string]any + if json.Unmarshal(raw, &wire) != nil { + t.Fatal("bad dashboard JSON") + } + return wire + } + data := read(s.tenant, "", end) + history, ok := data["reported_weeks"].([]any) + if !ok || len(history) != 1 { + t.Fatalf("reported percent-only history was not exposed independently: present=%v", ok) + } + row := history[0].(map[string]any) + if row["coverage_percent"] != 57.23 || row["correctness_percent"] != 92.34 || row["source"] != "user_provided_history" || row["week"] != "2026WK40" { + t.Fatal("reported precision or provenance lost") + } + for _, forbidden := range []string{"numerator", "denominator", "records", "frozen_at"} { + if _, exists := row[forbidden]; exists { + t.Fatal("invented historical evidence", forbidden) + } + } + if len(data["frozen_weeks"].([]any)) != 0 { + t.Fatal("historical input manufactured frozen evidence") + } + for _, wire := range []map[string]any{read(s.tenant, "needle", end), read("fixture-other-tenant", "", end), read(s.tenant, "", start.Add(-time.Hour))} { + if value, ok := wire["reported_weeks"].([]any); !ok || len(value) != 0 { + t.Fatal("history leaked across keyword, tenant or closing cutoff") + } + } + for _, query := range []string{`UPDATE qa_ops_reported_weekly_rates SET coverage_bp=123 WHERE tenant_key=$1`, `DELETE FROM qa_ops_reported_weekly_rates WHERE tenant_key=$1`} { + tx, e := p.Begin(ctx) + if e != nil { + t.Fatal(e) + } + _, e = tx.Exec(ctx, query, s.tenant) + _ = tx.Rollback(ctx) + var db *pgconn.PgError + if !errors.As(e, &db) || db.Code != "55000" { + t.Fatal("reported history could be overwritten or deleted") + } + } + e := pg.RollbackLatestMigration(ctx, p) + var failure *pgconn.PgError + if !errors.As(e, &failure) || failure.Code != "55000" { + t.Fatal("down did not explicitly protect historical data", e) + } +} diff --git a/internal/qaopsmirror/dashboard_store.go b/internal/qaopsmirror/dashboard_store.go index 4a3d999..9219289 100644 --- a/internal/qaopsmirror/dashboard_store.go +++ b/internal/qaopsmirror/dashboard_store.go @@ -256,6 +256,10 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas return out, dobotaiops.ErrInvalidQuery } } + out.ReportedWeeks, e = s.readReportedDashboard(ctx, tx, q.Keyword, q.Window.End) + if e != nil { + return out, e + } if tx.Commit(ctx) != nil { return out, dobotaiops.ErrUnavailable } diff --git a/web/src/QADashboardDrawing.test.tsx b/web/src/QADashboardDrawing.test.tsx index aa25cd4..95a2c7d 100644 --- a/web/src/QADashboardDrawing.test.tsx +++ b/web/src/QADashboardDrawing.test.tsx @@ -26,6 +26,29 @@ it('draws all eleven panels as a self-contained exportable SVG without HTML exec expect(html).toContain('data-frozen="missing"') expect(html).toContain('data-frozen="available"') }) +it('renders reported history in both existing trend panels with exact values and honest provenance', () => { + const data = parseQADashboard({ + ...dashboardFixture, + reported_weeks: [ + { + week: '2026WK40', + week_start: '2026-09-28T00:00:00+08:00', + week_end: '2026-10-05T00:00:00+08:00', + coverage_percent: 57.23, + correctness_percent: 92.34, + source: 'user_provided_history', + }, + ], + }) + const html = renderToStaticMarkup() + expect(html).toContain('57.23%') + expect(html).toContain('92.34%') + expect(html).toContain('用户提供历史统计') + expect(html).toContain('未提供分子/分母') + expect((html.match(/data-source="user_provided_history"/g) || []).length).toBe(2) + expect((html.match(/data-panel=/g) || []).length).toBe(11) + expect(html).toContain('data-frozen="available"') +}) it('reflows the same complete eleven panels at mobile width rather than clipping the canvas', () => { const html = renderToStaticMarkup() expect((html.match(/data-panel=/g) || []).length).toBe(11) diff --git a/web/src/QADashboardDrawing.tsx b/web/src/QADashboardDrawing.tsx index 360c6f1..ee5ff59 100644 --- a/web/src/QADashboardDrawing.tsx +++ b/web/src/QADashboardDrawing.tsx @@ -2,6 +2,7 @@ import type { ReactNode, Ref } from 'react' import type { QADashboardData, DashboardCount, DashboardRegion } from './qaDashboardData' import type { QualityRate } from './qaQuality' import { currentQAWeek } from './qaWeeks' +import { historicalTrend } from './qaHistoricalTrend' interface Box { x: number y: number @@ -271,6 +272,8 @@ interface PlotPoint { value: number | null hint: string frozen?: boolean + source?: 'user_provided_history' | 'system_frozen' + week?: string } function Plot({ box, @@ -295,18 +298,37 @@ function Plot({ 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) { + const color = (source: PlotPoint['source']) => (source === 'system_frozen' ? '#8b68c7' : blue) + const paths = [...new Set(points.map((p) => p.source))].map((source) => { + let path = '', open = false - continue + for (let i = 0; i < points.length; i++) { + const point = points[i] + if (point.value === null || point.source !== source) { + open = false + continue + } + path += `${open ? 'L' : 'M'} ${x(i)} ${y(point.value)} ` + open = true } - path += `${open ? 'L' : 'M'} ${x(i)} ${y(value)} ` - open = true - } + return { source, path } + }) const every = Math.max(1, Math.ceil(points.length / (box.w < 420 ? 5 : 8))) + const labelled = new Set() + points.forEach((point, i) => { + if ( + point.value !== null && + (i === 0 || + points[i - 1]?.source !== point.source || + i === points.length - 1 || + points[i + 1]?.source !== point.source) + ) + labelled.add(i) + }) + points.forEach((_, i) => { + if ((i % every === 0 || i === points.length - 1) && [...labelled].every((k) => Math.abs(x(k) - x(i)) >= 52)) + labelled.add(i) + }) return ( {Array.from({ length: 5 }, (_, i) => ( @@ -318,30 +340,58 @@ function Plot({ ))} - {path ? : null} + {paths + .filter((p) => p.path) + .map((p, i) => ( + + ))} {points.map((point, i) => ( {point.hint} {point.value !== null ? ( <> - - {points.length <= 14 || i % every === 0 || i === points.length - 1 ? ( - - {percent ? `${point.value.toFixed(1)}%` : number(point.value)} + + {labelled.has(i) ? ( + + {percent ? `${point.value.toFixed(2)}%` : number(point.value)} ) : null} ) : null} - {i % every === 0 || i === points.length - 1 ? ( + {labelled.has(i) ? ( {point.label} ) : null} ))} + {percent ? ( + + {points.some((p) => p.source === 'user_provided_history') + ? '蓝:用户提供(未提供分子/分母);紫:系统冻结' + : '缺失周留空;系统冻结与当前实时结果分开'} + + ) : null} {!points.some((p) => p.value !== null) ? ( {percent ? '暂无冻结快照' : '暂无数据'} @@ -489,19 +539,7 @@ export function QADashboardDrawing({ 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 frozen = (correctness: boolean): PlotPoint[] => historicalTrend(data, correctness) const month = new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7) return ( - - 问题统计看板 · {week.year}年第{week.week}周 - + {`问题统计看板 · ${week.year}年第${week.week}周`} 问题统计看板 diff --git a/web/src/qaDashboardData.test.ts b/web/src/qaDashboardData.test.ts index 7d85833..000301b 100644 --- a/web/src/qaDashboardData.test.ts +++ b/web/src/qaDashboardData.test.ts @@ -1,6 +1,36 @@ import { describe, it, expect } from 'vitest' import { parseQADashboard } from './qaDashboardData' import { dashboardFixture } from './qaDashboard.fixture' +const reported = { + week: '2026WK40', + week_start: '2026-09-28T00:00:00+08:00', + week_end: '2026-10-05T00:00:00+08:00', + coverage_percent: 57.23, + correctness_percent: 92.34, + source: 'user_provided_history', +} +describe('reported historical rates', () => { + it('keeps supplied percentages without inventing denominator or freeze time', () => { + const result = parseQADashboard({ ...dashboardFixture, reported_weeks: [reported] }) + expect(result.reported_weeks).toEqual([reported]) + expect(result.frozen_weeks).toEqual(parseQADashboard(dashboardFixture).frozen_weeks) + expect(result.quality).toEqual(parseQADashboard(dashboardFixture).quality) + }) + it('rejects invalid, duplicate, future, wrongly labelled and keyword-scoped supplied history', () => { + for (const input of [ + { ...dashboardFixture, reported_weeks: [reported, reported] }, + { ...dashboardFixture, reported_weeks: [{ ...reported, denominator: 100 }] }, + { ...dashboardFixture, reported_weeks: [{ ...reported, coverage_percent: 100.01 }] }, + { ...dashboardFixture, reported_weeks: [{ ...reported, correctness_percent: null }] }, + { ...dashboardFixture, reported_weeks: [{ ...reported, source: 'frozen' }] }, + { ...dashboardFixture, reported_weeks: [{ ...reported, week: '2026WK41' }] }, + { ...dashboardFixture, reported_weeks: [{ ...reported, week_end: '2027-01-01T00:00:00+08:00' }] }, + { ...dashboardFixture, keyword: 'needle', reported_weeks: [reported] }, + ]) + expect(() => parseQADashboard(input)).toThrow() + }) +}) + describe('complete dashboard data contract', () => { it('keeps distinct cumulative, week, month and genuinely frozen periods', () => { const data = parseQADashboard(dashboardFixture) diff --git a/web/src/qaDashboardData.ts b/web/src/qaDashboardData.ts index ae121a0..99361b8 100644 --- a/web/src/qaDashboardData.ts +++ b/web/src/qaDashboardData.ts @@ -1,4 +1,5 @@ import { parseQAOrganizationVersion } from './qaOps' +import { currentQAWeek } from './qaWeeks' import type { QAOrganizationVersion, QAQuery } from './qaOps' import { parseQualitySummary, parseQualityRate } from './qaQuality' import type { QualitySummary, QualityRate } from './qaQuality' @@ -6,6 +7,14 @@ export interface DashboardCount { label: string count: number } +export interface DashboardReported { + week: string + week_start: string + week_end: string + coverage_percent: number + correctness_percent: number + source: 'user_provided_history' +} export interface DashboardFrozen { week_start: string week_end: string @@ -41,6 +50,7 @@ export interface QADashboardData { daily: { date: string; count: number }[] regions: DashboardRegion[] frozen_weeks: DashboardFrozen[] + reported_weeks: DashboardReported[] } const bad = (): never => { throw new Error('统计看板响应无效,未展示可能失真的指标') @@ -186,6 +196,43 @@ export function parseQADashboard(value: unknown): QADashboardData { (frozen_weeks.length && Date.parse(frozen_weeks[frozen_weeks.length - 1].week_end) < Date.parse(end)) ) return bad() + const reported_weeks = list(v.reported_weeks === undefined ? [] : v.reported_weeks).map((raw, i) => { + const p = obj(raw), + week = text(p.week), + begin = stamp(p.week_start), + finish = stamp(p.week_end) + const iso = currentQAWeek(new Date(begin)) + const percent = (value: unknown) => + typeof value === 'number' && + Number.isFinite(value) && + value >= 0 && + value <= 100 && + Math.abs(value * 100 - Math.round(value * 100)) < 1e-8 + ? value + : bad() + if ( + Object.keys(p).some( + (k) => !['week', 'week_start', 'week_end', 'coverage_percent', 'correctness_percent', 'source'].includes(k) + ) || + keyword !== '' || + p.source !== 'user_provided_history' || + week !== `${iso.year}WK${String(iso.week).padStart(2, '0')}` || + monday(Date.parse(begin)) !== Date.parse(begin) || + Date.parse(finish) - Date.parse(begin) !== 7 * dayMS || + Date.parse(finish) > Date.parse(end) + ) + return bad() + if (i > 0 && Date.parse(begin) <= Date.parse(text(obj(list(v.reported_weeks)[i - 1]).week_start))) return bad() + return { + week, + week_start: begin, + week_end: finish, + coverage_percent: percent(p.coverage_percent), + correctness_percent: percent(p.correctness_percent), + source: 'user_provided_history' as const, + } + }) + if (reported_weeks.length > 5200) return bad() return { start, end, @@ -193,6 +240,7 @@ export function parseQADashboard(value: unknown): QADashboardData { as_of, week_start, month_start, + reported_weeks, local_revision: count(v.local_revision), organization, total_issues, diff --git a/web/src/qaHistoricalTrend.test.ts b/web/src/qaHistoricalTrend.test.ts new file mode 100644 index 0000000..dd181a4 --- /dev/null +++ b/web/src/qaHistoricalTrend.test.ts @@ -0,0 +1,27 @@ +import { it, expect } from 'vitest' +import { parseQADashboard } from './qaDashboardData' +import { dashboardFixture } from './qaDashboard.fixture' +import { historicalTrend } from './qaHistoricalTrend' +it('keeps absent weeks null, preserves supplied precision and never mutates real frozen evidence', () => { + const input = parseQADashboard({ + ...dashboardFixture, + reported_weeks: [ + { + week: '2026WK38', + week_start: '2026-09-14T00:00:00+08:00', + week_end: '2026-09-21T00:00:00+08:00', + coverage_percent: 57.23, + correctness_percent: 92.34, + source: 'user_provided_history', + }, + ], + }) + const before = JSON.stringify(input) + const points = historicalTrend(input, false) + expect(points.map((p) => p.week)).toEqual(['2026WK38', '2026WK39', '2026WK40', '2026WK41']) + expect(points.map((p) => p.value)).toEqual([57.23, null, null, 50]) + expect(points[0].source).toBe('user_provided_history') + expect(points[3].source).toBe('system_frozen') + expect(historicalTrend(input, true)[0].value).toBe(92.34) + expect(JSON.stringify(input)).toBe(before) +}) diff --git a/web/src/qaHistoricalTrend.ts b/web/src/qaHistoricalTrend.ts new file mode 100644 index 0000000..1c604cf --- /dev/null +++ b/web/src/qaHistoricalTrend.ts @@ -0,0 +1,47 @@ +import type { QADashboardData } from './qaDashboardData' +import { currentQAWeek } from './qaWeeks' +export interface HistoricalPlotPoint { + label: string + value: number | null + hint: string + frozen?: boolean + source?: 'user_provided_history' | 'system_frozen' + week?: string +} +// Never manufacture row counts or connect a line across missing weeks/policy changes. +export function historicalTrend(data: QADashboardData, correctness: boolean): HistoricalPlotPoint[] { + const frozen = new Map(data.frozen_weeks.map((p) => [Date.parse(p.week_start), p])) + const reported = new Map(data.reported_weeks.map((p) => [Date.parse(p.week_start), p])) + const starts = [...frozen.keys(), ...reported.keys()] + if (!starts.length) return [] + const out: HistoricalPlotPoint[] = [] + for (let at = Math.min(...starts); at < Date.parse(data.end) && out.length < 5200; at += 7 * 86400000) { + const w = currentQAWeek(new Date(at)), + label = `${w.year}W${String(w.week).padStart(2, '0')}`, + supplied = reported.get(at), + point = frozen.get(at) + if (supplied) { + const value = correctness ? supplied.correctness_percent : supplied.coverage_percent + out.push({ + label, + week: supplied.week, + value, + source: 'user_provided_history', + hint: `${supplied.week}:${value.toFixed(2)}%;用户提供历史统计,未提供分子/分母;不按当前规则重算`, + }) + continue + } + const rate = point ? (correctness ? point.correctness : point.coverage) : null + out.push({ + label, + week: `${w.year}WK${String(w.week).padStart(2, '0')}`, + value: rate?.percent ?? null, + frozen: point?.frozen_at !== null && point?.frozen_at !== undefined, + source: point?.frozen_at ? 'system_frozen' : undefined, + hint: point?.frozen_at + ? `${label}:${rate?.percent?.toFixed(2) ?? '—'}%;${rate?.numerator}/${rate?.denominator};系统冻结于 ${point.frozen_at}` + : `${label}:未提供历史统计,缺少当时冻结快照`, + }) + } + return out +}