feat(qaops): 看板改用自然月质量指标并增加统计口径
build / build (push) Successful in 1m10s

去掉看板个人月明细;十一卡悬停和键盘可读的真实统计范围、公式与排除数。
自然月独立计算;跨月周取周一所在月,保留旧周证据和已存周报正文。

验证:make verify;一次性PG全镜像套件-race;真实恢复数据7个月与周报calc_metrics对拍。
真实浏览器十一卡逐项悬停、Tab/Escape、30秒刷新、跨月周、390px和完整PNG通过。
没有写DobotAI源问答、触发付费模型、外发或应用新迁移。
This commit is contained in:
姚章浩
2026-10-21 08:48:55 +08:00
parent 1580ebd826
commit cb9f0c389f
24 changed files with 878 additions and 169 deletions
+8
View File
@@ -76,6 +76,14 @@
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯,
> 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。
## 开发快照 snapshot/v0.1.44 - 2026-10-21
### Changed
- 问题统计看板去掉个人月明细入口,十一张卡片右上角新增“统计口径”,悬停、键盘聚焦及触屏可查看实际范围、公式与排除数量;图片导出保留完整十一项及口径入口,不包含交互浮层。
- 覆盖率与正确率趋势改为北京时间逐自然月独立计算,每月1日重新累计;使用总表当前有效结论、人工优先及点踩否,分别按是÷(是+否)计算,待确认等排除,空月/零分母留空。旧周上报、冻结及第40–43周累计证据保留,不再混画到月轴。
- 每周看板的两项质量仪表与新建/主动重新预填周报使用月内累计;跨月周取周一所在月并截止该月底,非跨月周截止该周实际时点,当前周不预读未来。保留已保存周报正文、修订与重试标识,不自动改写旧稿,不修改源问答或触发付费模型及对外发送。
## 开发快照 snapshot/v0.1.43 - 2026-10-20
### Added
+1 -1
View File
@@ -125,7 +125,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":"管理员只读正式总表一致性看板:累计、所选周及区域统计;第40–43周动态累计、历史上报与真实冻结分别保留","description":"同一只读可重复读事务读取独立正式总表有效字段、质量及组织版本。不访问源端,不冻结或写入指标;区域分母为当前配置通讯录去重人数而非在职/绩效名单。冻结记录按保存的原始标量分子分母及问题文字支持字面关键词筛选,不用当前评估回填历史。reported_weeks 独立返回用户提供的历史百分比(QAReportedHistoricalRate),没有分子分母或冻结时间;只含所选截止前已结束周,关键词非空时为空,原冻结记录与当前指标保持不变。cumulative_weeks 独立返回2026WK40–WK43的master_live_cumulative_v1实时累计曲线,policy_version为weekly-strict-yes-over-yes-no-v1:各周成员为整张总表中提问时间早于北京时间下周一的记录,当前周截止min(查询end,事务当前时点),不被查询start截断;字段取当前有效结论,补值和后续点踩会追溯更新相关累计周。覆盖率与正确率分别按是÷(是+否),待确认/部分覆盖及其他值不入严格分母,零分母percent=null;各点保留成员数、两组分子分母、周边界、实际截止和计算时点。仅查询治理本地总表,不写历史上报/冻结证据;网页30秒顺序刷新,已闭查询周不推进到后周。","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),没有分子分母或冻结时间;只含所选截止前已结束周,关键词非空时为空,原冻结记录与当前指标保持不变。cumulative_weeks 独立返回2026WK40–WK43的master_live_cumulative_v1实时累计曲线,policy_version为weekly-strict-yes-over-yes-no-v1:各周成员为整张总表中提问时间早于北京时间下周一的记录,当前周截止min(查询end,事务当前时点),不被查询start截断;字段取当前有效结论,补值和后续点踩会追溯更新相关累计周。覆盖率与正确率分别按是÷(是+否),待确认/部分覆盖及其他值不入严格分母,零分母percent=null;各点保留成员数、两组分子分母、周边界、实际截止和计算时点。仅查询治理本地总表,不写历史上报/冻结证据。新增 quality_period(统计月、月初、实际截止、计算时点及规则)和 monthly_quality(该月内成员数、独立覆盖及正确率分子分母);以所选周周一所在月为质量归属月,跨月周截止该月下月1日,非跨月周截止查询end,均不超过事务当前时点。calendar_months 返回从首个总表数据月起逐自然月独立计算的月点,policy_version=calendar-month-strict-yes-over-yes-no-v1,source=master_live_calendar_month_v1;每月重置,使用当前有效字段,待确认等排除,零分母null,空月保留,最后点与仪表使用相同截止。旧 reported_weeks、frozen_weeks、cumulative_weeks 保留但不混画到月轴;不平均旧周百分比。网页30秒顺序刷新,已闭查询周不推进到后周。","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"],
+3
View File
@@ -60,6 +60,9 @@ type Dashboard struct {
FrozenWeeks []DashboardFrozen `json:"frozen_weeks"`
ReportedWeeks []DashboardReported `json:"reported_weeks"`
CumulativeWeeks []DashboardCumulative `json:"cumulative_weeks"`
QualityPeriod *DashboardQualityPeriod `json:"quality_period,omitempty"`
MonthlyQuality *DashboardStrictQuality `json:"monthly_quality,omitempty"`
CalendarMonths []DashboardMonth `json:"calendar_months"`
}
var dashboardLocation = time.FixedZone("Asia/Shanghai", 8*60*60)
+46 -49
View File
@@ -23,25 +23,25 @@ type DashboardCumulative struct {
PolicyVersion string `json:"policy_version"`
}
// Membership closes at each week's cutoff; labels deliberately stay live. This is
// not a frozen snapshot and must never replace the older reported/frozen evidence.
func (s *Store) readMasterCumulativeDashboard(ctx context.Context, tx pgx.Tx, keyword string, end time.Time) ([]DashboardCumulative, error) {
out := []DashboardCumulative{}
type dashboardTimedQuality struct {
at time.Time
view qaopsquality.View
}
// Resolve effective labels once in the same read-only repeatable-read snapshot.
// Both legacy cumulative evidence and calendar-month statistics share this input.
func (s *Store) readMasterQualityTimeline(ctx context.Context, tx pgx.Tx, keyword string, end time.Time) ([]dashboardTimedQuality, time.Time, error) {
var now time.Time
if e := tx.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&now); e != nil {
return nil, e
return nil, now, e
}
cutoff := end
if now.Before(cutoff) {
cutoff = now
}
first := time.Date(2026, time.September, 28, 0, 0, 0, 0, dashboardLocation)
if !first.Before(cutoff) {
return out, nil
}
rows, e := tx.Query(ctx, `SELECT id,asked_at,quality_hash,effective_fields,inline_fields,coverage_result,current_feedback FROM qa_ops_master_read_model WHERE tenant_key=$1 AND asked_at<$2 AND ($3='' OR position(lower($3) IN lower(question||E'\n'||chinese_question||E'\n'||COALESCE(ai_fields->>'question_chinese','')))>0) ORDER BY asked_at,id LIMIT 100001`, s.tenant, cutoff, keyword)
if e != nil {
return nil, dobotaiops.ErrUnavailable
return nil, now, dobotaiops.ErrUnavailable
}
records := []dashboardRecord{}
keys := []dobotaiops.QualityKey{}
@@ -50,11 +50,11 @@ func (s *Store) readMasterCumulativeDashboard(ctx context.Context, tx pgx.Tx, ke
var f, ed, cov, fb []byte
if e = rows.Scan(&r.id, &r.at, &r.hash, &f, &ed, &cov, &fb); e != nil {
rows.Close()
return nil, e
return nil, now, e
}
if json.Unmarshal(f, &r.fields) != nil || json.Unmarshal(ed, &r.edits) != nil || json.Unmarshal(cov, &r.coverage) != nil || json.Unmarshal(fb, &r.feedback) != nil {
rows.Close()
return nil, dobotaiops.ErrUnavailable
return nil, now, dobotaiops.ErrUnavailable
}
records = append(records, r)
keys = append(keys, dobotaiops.QualityKey{ID: r.id, InputHash: r.hash})
@@ -62,23 +62,49 @@ func (s *Store) readMasterCumulativeDashboard(ctx context.Context, tx pgx.Tx, ke
e = rows.Err()
rows.Close()
if e != nil {
return nil, e
return nil, now, e
}
if len(records) > dobotaiops.MaxMirrorRecords {
return nil, dobotaiops.ErrInvalidQuery
return nil, now, dobotaiops.ErrInvalidQuery
}
views := map[string]qaopsquality.View{}
store := qaopsquality.NewStore(s.pool, s.tenant+"::master")
for begin := 0; begin < len(keys); begin += 5000 {
limit := min(begin+5000, len(keys))
part, e := store.ReadViewsInTx(ctx, tx, keys[begin:limit])
part, e := store.ReadViewsInTx(ctx, tx, keys[begin:min(begin+5000, len(keys))])
if e != nil {
return nil, e
return nil, now, e
}
for id, v := range part {
views[id] = v
}
}
out := make([]dashboardTimedQuality, 0, len(records))
for _, r := range records {
v, ok := views[r.id]
if !ok {
return nil, now, qaopsquality.ErrUnavailable
}
out = append(out, dashboardTimedQuality{at: r.at, view: qaopsquality.ProjectMasterWithEdits(v, r.fields, r.coverage, r.edits, r.feedback)})
}
return out, now, nil
}
// Membership closes at each week's cutoff; labels deliberately stay live. This is
// not a frozen snapshot and must never replace older reported/frozen evidence.
func (s *Store) readMasterCumulativeDashboard(ctx context.Context, tx pgx.Tx, keyword string, end time.Time) ([]DashboardCumulative, error) {
records, now, e := s.readMasterQualityTimeline(ctx, tx, keyword, end)
if e != nil {
return nil, e
}
return dashboardCumulativeFromTimeline(records, end, now), nil
}
func dashboardCumulativeFromTimeline(records []dashboardTimedQuality, end, now time.Time) []DashboardCumulative {
out := []DashboardCumulative{}
cutoff := end
if now.Before(cutoff) {
cutoff = now
}
first := time.Date(2026, time.September, 28, 0, 0, 0, 0, dashboardLocation)
for i := 0; i < 4; i++ {
start := first.AddDate(0, 0, 7*i)
if !start.Before(cutoff) {
@@ -90,37 +116,8 @@ func (s *Store) readMasterCumulativeDashboard(ctx context.Context, tx pgx.Tx, ke
until = cutoff
}
year, week := start.ISOWeek()
point := DashboardCumulative{Week: fmt.Sprintf("%dWK%02d", year, week), WeekStart: start, WeekEnd: finish, CutoffAt: until, CalculatedAt: now, Source: "master_live_cumulative_v1", PolicyVersion: "weekly-strict-yes-over-yes-no-v1"}
covered, uncovered, correct, incorrect := 0, 0, 0, 0
for _, r := range records {
if !r.at.Before(until) {
continue
}
point.Records++
v, ok := views[r.id]
if !ok {
return nil, qaopsquality.ErrUnavailable
}
v = qaopsquality.ProjectMasterWithEdits(v, r.fields, r.coverage, r.edits, r.feedback)
if v.State == "stale" {
continue
}
switch v.Effective.Coverage {
case "covered":
covered++
case "uncovered":
uncovered++
}
switch v.Effective.Correctness {
case "correct":
correct++
case "incorrect":
incorrect++
}
}
point.Coverage = dashboardRate(covered, covered+uncovered)
point.Correctness = dashboardRate(correct, correct+incorrect)
out = append(out, point)
rates := dashboardStrictQuality(records, time.Time{}, until)
out = append(out, DashboardCumulative{Week: fmt.Sprintf("%dWK%02d", year, week), WeekStart: start, WeekEnd: finish, CutoffAt: until, CalculatedAt: now, Records: rates.Records, Coverage: rates.Coverage, Correctness: rates.Correctness, Source: "master_live_cumulative_v1", PolicyVersion: "weekly-strict-yes-over-yes-no-v1"})
}
return out, nil
return out
}
+107
View File
@@ -0,0 +1,107 @@
package qaopsmirror
import (
"knowledge-governance/internal/qaopsquality"
"time"
)
const dashboardMonthlySource = "master_live_calendar_month_v1"
const dashboardMonthlyPolicy = "calendar-month-strict-yes-over-yes-no-v1"
type DashboardQualityPeriod struct {
Month string `json:"month"`
Start time.Time `json:"start"`
CutoffAt time.Time `json:"cutoff_at"`
CalculatedAt time.Time `json:"calculated_at"`
Source string `json:"source"`
PolicyVersion string `json:"policy_version"`
}
type DashboardStrictQuality struct {
Records int `json:"records"`
Coverage qaopsquality.Rate `json:"coverage"`
Correctness qaopsquality.Rate `json:"correctness"`
}
type DashboardMonth struct {
Month string `json:"month"`
MonthStart time.Time `json:"month_start"`
MonthEnd time.Time `json:"month_end"`
CutoffAt time.Time `json:"cutoff_at"`
CalculatedAt time.Time `json:"calculated_at"`
Source string `json:"source"`
PolicyVersion string `json:"policy_version"`
DashboardStrictQuality
}
// The weekly skill uses strict yes/(yes+no) independently for each metric.
// In particular, correctness is NOT restricted to covered questions and partial
// coverage is NOT a negative vote. Keep the old Summary policy unchanged.
func dashboardStrictQuality(records []dashboardTimedQuality, start, end time.Time) DashboardStrictQuality {
out := DashboardStrictQuality{}
covered, uncovered, correct, incorrect := 0, 0, 0, 0
for _, r := range records {
if r.at.Before(start) || !r.at.Before(end) {
continue
}
out.Records++
if r.view.State == "stale" {
continue
}
switch r.view.Effective.Coverage {
case "covered":
covered++
case "uncovered":
uncovered++
}
switch r.view.Effective.Correctness {
case "correct":
correct++
case "incorrect":
incorrect++
}
}
out.Coverage = dashboardRate(covered, covered+uncovered)
out.Correctness = dashboardRate(correct, correct+incorrect)
return out
}
func dashboardCalendarMonths(records []dashboardTimedQuality, end, now time.Time) []DashboardMonth {
out := []DashboardMonth{}
cutoff := end
if now.Before(cutoff) {
cutoff = now
}
var first time.Time
for _, r := range records {
if r.at.Before(cutoff) && (first.IsZero() || r.at.Before(first)) {
first = r.at
}
}
if first.IsZero() {
return out
}
first = first.In(dashboardLocation)
begin := time.Date(first.Year(), first.Month(), 1, 0, 0, 0, 0, dashboardLocation)
for ; begin.Before(cutoff); begin = begin.AddDate(0, 1, 0) {
finish := begin.AddDate(0, 1, 0)
until := finish
if cutoff.Before(until) {
until = cutoff
}
out = append(out, DashboardMonth{Month: begin.Format("2006-01"), MonthStart: begin, MonthEnd: finish, CutoffAt: until, CalculatedAt: now, Source: dashboardMonthlySource, PolicyVersion: dashboardMonthlyPolicy, DashboardStrictQuality: dashboardStrictQuality(records, begin, until)})
}
return out
}
// dashboardQualityMonth resolves the quality month for a selected week.
func dashboardQualityMonth(start, end, now time.Time) (time.Time, time.Time) {
weekMonday := dashboardWeek(start)
month := time.Date(weekMonday.Year(), weekMonday.Month(), 1, 0, 0, 0, 0, dashboardLocation)
cutoff := month.AddDate(0, 1, 0)
if end.Before(cutoff) {
cutoff = end
}
if now.Before(cutoff) {
cutoff = now
}
return month, cutoff
}
@@ -0,0 +1,33 @@
package qaopsmirror
import (
"testing"
"time"
)
func monthlyTestTime(t *testing.T, value string) time.Time {
t.Helper()
at, err := time.Parse(time.RFC3339, value)
if err != nil {
t.Fatal(err)
}
return at
}
func TestQualityMonthCrossingWeekIsPreviousMonthReport(t *testing.T) {
for _, c := range []struct{ name, start, end, now, wantStart, wantEnd string }{
{"cross-month", "2026-09-28T00:00:00+08:00", "2026-10-05T00:00:00+08:00", "2026-10-21T08:00:00+08:00", "2026-09-01T00:00:00+08:00", "2026-10-01T00:00:00+08:00"},
{"within-month", "2026-10-05T00:00:00+08:00", "2026-10-12T00:00:00+08:00", "2026-10-21T08:00:00+08:00", "2026-10-01T00:00:00+08:00", "2026-10-12T00:00:00+08:00"},
{"current-week-clamps-now", "2026-10-19T00:00:00+08:00", "2026-10-26T00:00:00+08:00", "2026-10-21T08:00:00+08:00", "2026-10-01T00:00:00+08:00", "2026-10-21T08:00:00+08:00"},
{"cross-year", "2025-12-29T00:00:00+08:00", "2026-01-05T00:00:00+08:00", "2026-10-21T08:00:00+08:00", "2025-12-01T00:00:00+08:00", "2026-01-01T00:00:00+08:00"},
{"utc-same-boundary", "2026-09-27T16:00:00Z", "2026-10-04T16:00:00Z", "2026-10-21T00:00:00Z", "2026-09-01T00:00:00+08:00", "2026-10-01T00:00:00+08:00"},
{"crossing-week-before-month-complete", "2026-09-28T00:00:00+08:00", "2026-09-29T08:00:00+08:00", "2026-09-29T08:00:00+08:00", "2026-09-01T00:00:00+08:00", "2026-09-29T08:00:00+08:00"},
} {
t.Run(c.name, func(t *testing.T) {
begin, end := dashboardQualityMonth(monthlyTestTime(t, c.start), monthlyTestTime(t, c.end), monthlyTestTime(t, c.now))
if !begin.Equal(monthlyTestTime(t, c.wantStart)) || !end.Equal(monthlyTestTime(t, c.wantEnd)) {
t.Fatalf("quality month = [%s,%s), want [%s,%s)", begin, end, c.wantStart, c.wantEnd)
}
})
}
}
+10 -3
View File
@@ -265,12 +265,19 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
}
}
if master {
out.CumulativeWeeks, e = s.readMasterCumulativeDashboard(ctx, tx, q.Keyword, q.Window.End)
if e != nil {
return out, e
timeline, calculated, err := s.readMasterQualityTimeline(ctx, tx, q.Keyword, q.Window.End)
if err != nil {
return out, err
}
out.CumulativeWeeks = dashboardCumulativeFromTimeline(timeline, q.Window.End, calculated)
month, cutoff := dashboardQualityMonth(out.WeekStart, q.Window.End, calculated)
out.QualityPeriod = &DashboardQualityPeriod{Month: month.Format("2006-01"), Start: month, CutoffAt: cutoff, CalculatedAt: calculated, Source: dashboardMonthlySource, PolicyVersion: dashboardMonthlyPolicy}
rates := dashboardStrictQuality(timeline, month, cutoff)
out.MonthlyQuality = &rates
out.CalendarMonths = dashboardCalendarMonths(timeline, cutoff, calculated)
} else {
out.CumulativeWeeks = []DashboardCumulative{}
out.CalendarMonths = []DashboardMonth{}
}
out.ReportedWeeks, e = s.readReportedDashboard(ctx, tx, q.Keyword, q.Window.End)
if e != nil {
@@ -0,0 +1,115 @@
package qaopsmirror
import (
"context"
"encoding/json"
"knowledge-governance/internal/dobotaiops"
pg "knowledge-governance/internal/platform/postgres"
"strings"
"testing"
"time"
)
func TestMasterCalendarMonthsResetAndCrossingWeekReadsPreviousMonth(t *testing.T) {
p := mirrorFixture(t)
ctx := context.Background()
s := NewStore(p, "fixture-calendar-month")
queue := pg.NewStore(p)
dates := []string{"2026-08-31T08:00:00+08:00", "2026-09-01T00:00:00+08:00", "2026-09-15T08:00:00+08:00", "2026-09-30T23:59:59+08:00", "2026-10-01T00:00:00+08:00", "2026-10-07T08:00:00+08:00", "2026-10-12T00:00:00+08:00"}
ids := []string{"aug", "sep1", "sep15", "sep30pending", "oct1", "oct7", "oct12boundary"}
cov := []string{"是", "是", "否", "是", "否", "是", "是"}
correct := []string{"否", "是", "否", "待确认", "否", "是", "是"}
source := &fixtureSource{}
for i, at := range dates {
entry := fixtureEntry(ids[i], "已有正文")
var wire map[string]any
_ = json.Unmarshal(entry.Payload, &wire)
wire["asked_at"] = at
entry.Payload, _ = json.Marshal(wire)
source.rows = append(source.rows, entry)
}
job := claimMirrorJob(t, s, queue, "seed-monthly")
if e := s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
t.Fatal(e)
}
if e := queue.Complete(ctx, job.ID, job.LeaseOwner, time.Now()); e != nil {
t.Fatal(e)
}
for i, id := range ids {
fields, _ := json.Marshal(map[string]string{"coverage": cov[i], "is_correct": correct[i]})
if _, e := p.Exec(ctx, "UPDATE qa_ops_master_records SET local_fields=local_fields||$3::jsonb WHERE tenant_key=$1 AND id=$2", s.tenant, id, fields); e != nil {
t.Fatal(e)
}
}
read := func(start, end string) map[string]any {
t.Helper()
data, e := s.ReadMasterDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: monthlyTestTime(t, start), End: monthlyTestTime(t, end)}})
if e != nil {
t.Fatal(e)
}
raw, _ := json.Marshal(data)
var v map[string]any
_ = json.Unmarshal(raw, &v)
return v
}
crossing := read("2026-09-28T00:00:00+08:00", "2026-10-05T00:00:00+08:00")
period, ok := crossing["quality_period"].(map[string]any)
if !ok {
t.Fatal("missing calendar-month quality period; weekly/cumulative rates cannot substitute")
}
if period["month"] != "2026-09" || !monthlyTestTime(t, period["start"].(string)).Equal(monthlyTestTime(t, "2026-09-01T00:00:00+08:00")) || !monthlyTestTime(t, period["cutoff_at"].(string)).Equal(monthlyTestTime(t, "2026-10-01T00:00:00+08:00")) {
t.Fatal("crossing week did not select the previous month")
}
assertRates := func(raw any, records, covN, covD, accN, accD float64) {
t.Helper()
point := raw.(map[string]any)
rates := point
if v, ok := point["rates"].(map[string]any); ok {
rates = v
if point["total"] != records {
t.Fatal("monthly quality member count differs", point)
}
} else if point["records"] != records {
t.Fatal("monthly point member count differs", point)
}
coverage := rates["coverage"].(map[string]any)
accuracy := rates["correctness"].(map[string]any)
if coverage["numerator"] != covN || coverage["denominator"] != covD || accuracy["numerator"] != accN || accuracy["denominator"] != accD {
t.Fatalf("monthly rates did not reset or pending entered denominator: %v", point)
}
}
assertRates(crossing["monthly_quality"], 3, 2, 3, 1, 2)
months, ok := crossing["calendar_months"].([]any)
if !ok || len(months) != 2 {
t.Fatal("expected August and September independent month points, no October fragment")
}
assertRates(months[0], 1, 1, 1, 0, 1)
assertRates(months[1], 3, 2, 3, 1, 2)
inside := read("2026-10-05T00:00:00+08:00", "2026-10-12T00:00:00+08:00")
assertRates(inside["monthly_quality"], 2, 1, 2, 1, 2)
if len(inside["calendar_months"].([]any)) != 3 {
t.Fatal("missing October monthly point")
}
prefill, e := s.PrefillWeeklyDraft(ctx, "2026-W40", WeeklyDraftPrefillRequest{BaseRevision: 0, Nonce: "fixture_monthly_prefill_0001"}, "fixture-admin", time.Now())
if e != nil || !strings.Contains(prefill.Draft.Markdown, "质量统计月:2026-09") || !strings.Contains(prefill.Draft.Markdown, "Coverage Rate: 66.67%") || !strings.Contains(prefill.Draft.Markdown, "Accuracy Rate: 50.00%") {
t.Fatal("new prefill did not use the same September rates", e)
}
var before string
if e := p.QueryRow(ctx, `SELECT md5(string_agg(md5(payload::text||original_fields::text||local_fields::text),'' ORDER BY id)) FROM qa_ops_master_records WHERE tenant_key=$1`, s.tenant).Scan(&before); e != nil {
t.Fatal(e)
}
if _, e := p.Exec(ctx, `UPDATE qa_ops_mirror_records SET payload=jsonb_set(payload,'{feedback}','{"asker_value":"down","down":1,"up":0}') WHERE tenant_key=$1 AND id='sep1'`, s.tenant); e != nil {
t.Fatal(e)
}
fresh := read("2026-09-28T00:00:00+08:00", "2026-10-05T00:00:00+08:00")
assertRates(fresh["monthly_quality"], 3, 2, 3, 0, 2)
assertRates(fresh["calendar_months"].([]any)[1], 3, 2, 3, 0, 2)
saved, e := s.ReadWeeklyDraft(ctx, "2026-W40", time.Now())
if e != nil || saved.Markdown != prefill.Draft.Markdown || saved.Revision != prefill.Draft.Revision {
t.Fatal("live rate refresh overwrote a previously saved weekly draft", e)
}
var after string
if e := p.QueryRow(ctx, `SELECT md5(string_agg(md5(payload::text||original_fields::text||local_fields::text),'' ORDER BY id)) FROM qa_ops_master_records WHERE tenant_key=$1`, s.tenant).Scan(&after); e != nil || before != after {
t.Fatal("monthly read modified master original/local labels")
}
}
+21 -1
View File
@@ -90,6 +90,21 @@ func renderWeeklyTemplate(week string, data Dashboard, now time.Time) (string, j
qualitySourceWeekKey = p.Week
}
}
qualityPeriodEN, qualityPeriodZH := "", ""
if data.QualityPeriod != nil || data.MonthlyQuality != nil {
period, rates := data.QualityPeriod, data.MonthlyQuality
if period == nil || rates == nil || period.Source != dashboardMonthlySource || period.PolicyVersion != dashboardMonthlyPolicy || rates.Records < 0 {
return "", nil, dobotaiops.ErrInvalidQuery
}
wantStart, wantEnd := dashboardQualityMonth(start, end, period.CalculatedAt)
if !period.Start.Equal(wantStart) || !period.CutoffAt.Equal(wantEnd) || period.Month != wantStart.Format("2006-01") {
return "", nil, dobotaiops.ErrInvalidQuery
}
coverage, accuracy = rates.Coverage.Percent, rates.Correctness.Percent
qualitySource, qualitySourceWeekKey = dashboardMonthlySource, ""
qualityPeriodEN = fmt.Sprintf("Quality month (Beijing): %s; [%s, %s). Each rate is yes / (yes + no); pending and other unresolved values are excluded.", period.Month, period.Start.In(dashboardLocation).Format(time.RFC3339), period.CutoffAt.In(dashboardLocation).Format(time.RFC3339))
qualityPeriodZH = fmt.Sprintf("质量统计月:%s(北京时间);范围 [%s, %s)。分别按是÷(是+否)计算,待确认等不计分母;跨月周按周一所在月。", period.Month, period.Start.In(dashboardLocation).Format(time.RFC3339), period.CutoffAt.In(dashboardLocation).Format(time.RFC3339))
}
if !validWeeklyValue(coverage, true) || !validWeeklyValue(accuracy, true) {
return "", nil, dobotaiops.ErrInvalidQuery
}
@@ -103,13 +118,14 @@ func renderWeeklyTemplate(week string, data Dashboard, now time.Time) (string, j
"{{YEAR}}", week[:4], "{{WEEK}}", week[6:],
"{{TOTAL_QUESTIONS}}", fmt.Sprint(data.TotalIssues), "{{NEW_THIS_WEEK}}", fmt.Sprint(data.NewThisWeek),
"{{COVERAGE_RATE}}", weeklyPercent(coverage), "{{ACCURACY_RATE}}", weeklyPercent(accuracy),
"{{QUALITY_PERIOD_EN}}", qualityPeriodEN, "{{QUALITY_PERIOD_ZH}}", qualityPeriodZH,
"{{MONTH_EN}}", month.Format("January 2006"), "{{MONTH_ZH}}", fmt.Sprintf("%d年%d月", month.Year(), month.Month()),
"{{AVERAGE_USAGE_RANKING_EN}}", weeklyRegionRanking(data.Regions, false, true), "{{AVERAGE_USAGE_RANKING_ZH}}", weeklyRegionRanking(data.Regions, false, false),
"{{USAGE_COVERAGE_RANKING_EN}}", weeklyRegionRanking(data.Regions, true, true), "{{USAGE_COVERAGE_RANKING_ZH}}", weeklyRegionRanking(data.Regions, true, false),
"{{WEEKLY_HIGHLIGHTS_EN}}", "[To be completed]", "{{NEXT_WEEK_PRIORITIES_EN}}", "[To be completed]",
"{{WEEKLY_HIGHLIGHTS_ZH}}", "[待填写]", "{{NEXT_WEEK_PRIORITIES_ZH}}", "[待填写]"}
markdown := strings.NewReplacer(replacements...).Replace(weeklySkillTemplate)
seed, _ := json.Marshal(map[string]any{"template_version": "dobot-weekly-six-sections-v1", "week": week, "start": start, "end": end, "generated_at": now, "source": "governance-master", "local_revision": data.LocalRevision, "source_observed_at": data.AsOf, "organization": data.Organization, "quality_source": qualitySource, "quality_source_week_key": qualitySourceWeekKey, "total_issues": data.TotalIssues, "new_this_week": data.NewThisWeek, "coverage_percent": coverage, "correctness_percent": accuracy, "month": month.Format("2006-01"), "regions": data.Regions})
seed, _ := json.Marshal(map[string]any{"template_version": "dobot-weekly-six-sections-v1", "week": week, "start": start, "end": end, "generated_at": now, "source": "governance-master", "local_revision": data.LocalRevision, "source_observed_at": data.AsOf, "organization": data.Organization, "quality_source": qualitySource, "quality_source_week_key": qualitySourceWeekKey, "quality_period": data.QualityPeriod, "quality_counts": data.MonthlyQuality, "total_issues": data.TotalIssues, "new_this_week": data.NewThisWeek, "coverage_percent": coverage, "correctness_percent": accuracy, "month": month.Format("2006-01"), "regions": data.Regions})
return markdown, seed, nil
}
@@ -127,6 +143,8 @@ Coverage Rate: {{COVERAGE_RATE}}
Accuracy Rate: {{ACCURACY_RATE}}
{{QUALITY_PERIOD_EN}}
## 3. {{MONTH_EN}} Regional Average Usage Ranking
{{AVERAGE_USAGE_RANKING_EN}}
@@ -157,6 +175,8 @@ Accuracy Rate: {{ACCURACY_RATE}}
正确率:{{ACCURACY_RATE}}
{{QUALITY_PERIOD_ZH}}
## 三、{{MONTH_ZH}}区域人均使用次数排名
{{AVERAGE_USAGE_RANKING_ZH}}
@@ -8,6 +8,34 @@ import (
"time"
)
func TestWeeklyTemplateCalendarMonthOverridesOnlyNewPrefillNotHistoricalEvidence(t *testing.T) {
now := monthlyTestTime(t, "2026-10-21T08:00:00+08:00")
start, end, e := weeklyDraftBounds("2026-W40", now)
if e != nil {
t.Fatal(e)
}
data := Dashboard{Start: start, End: end, MonthStart: monthlyTestTime(t, "2026-10-01T00:00:00+08:00"), ReportedWeeks: []DashboardReported{{Week: "2026WK40", WeekStart: start, WeekEnd: end, CoveragePercent: 57.23, CorrectnessPercent: 92.34, Source: "user_provided_history"}}, QualityPeriod: &DashboardQualityPeriod{Month: "2026-09", Start: monthlyTestTime(t, "2026-09-01T00:00:00+08:00"), CutoffAt: monthlyTestTime(t, "2026-10-01T00:00:00+08:00"), CalculatedAt: now, Source: dashboardMonthlySource, PolicyVersion: dashboardMonthlyPolicy}, MonthlyQuality: &DashboardStrictQuality{Records: 3, Coverage: dashboardRate(2, 3), Correctness: dashboardRate(1, 2)}}
md, seed, e := renderWeeklyTemplate("2026-W40", data, now)
if e != nil {
t.Fatal(e)
}
var meta map[string]any
_ = json.Unmarshal(seed, &meta)
if !strings.Contains(md, "Coverage Rate: 66.67%") || !strings.Contains(md, "Accuracy Rate: 50.00%") || !strings.Contains(md, "质量统计月:2026-09") || meta["quality_source"] != dashboardMonthlySource {
t.Fatal("new weekly prefill still uses historical/week quality instead of the selected calendar month", md)
}
if data.ReportedWeeks[0].CoveragePercent != 57.23 {
t.Fatal("historical reported evidence changed")
}
if strings.Count(md, "\n## ") != 12 {
t.Fatal("changed approved bilingual six-section template")
}
period, ok := meta["quality_period"].(map[string]any)
if !ok || period["month"] != "2026-09" {
t.Fatal("monthly prefill provenance missing")
}
}
func TestWeeklyTemplateHistoricalRatesKeepSourceWeekKeyAndUseMatchingBoundaries(t *testing.T) {
now := time.Date(2026, 10, 19, 12, 0, 0, 0, time.UTC)
start, end, e := weeklyDraftBounds("2026-W40", now)
+6 -1
View File
@@ -1,7 +1,7 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, it, expect, vi } from 'vitest'
import { qaDailySeries, qaCategorySeries } from './qaDashboard'
import { QADashboardView } from './QADashboard'
import { QADashboard, QADashboardView } from './QADashboard'
import { parseQADashboard } from './qaDashboardData'
import { dashboardFixture } from './qaDashboard.fixture'
import type { QARecord, QAQuery } from './qaOps'
@@ -11,6 +11,11 @@ const records = [
{ id: 'b', asked_at: '2026-10-12T16:01:00Z' },
] as QARecord[]
describe('question dashboard projections', () => {
it('does not render the personal monthly details entry on the statistics dashboard', () => {
const html = renderToStaticMarkup(<QADashboard query={query} error={null} revision={0} onRetry={vi.fn()} />)
expect(html).not.toContain('个人月明细')
expect(html).not.toContain('qa-monthly-disclosure')
})
it('groups by Beijing day and keeps zero days instead of using the browser timezone', () => {
expect(qaDailySeries(records, query)).toEqual([
{ label: '2026-10-12', count: 1 },
+1 -7
View File
@@ -5,7 +5,6 @@ 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 {
data: QADashboardData | null
@@ -90,8 +89,7 @@ export function QADashboard({
}) {
const [data, setData] = useState<QADashboardData | null>(null),
[failure, setFailure] = useState(''),
[loading, setLoading] = useState(false),
[monthly, setMonthly] = useState(false)
[loading, setLoading] = useState(false)
useEffect(() => {
setData(null)
setFailure('')
@@ -127,10 +125,6 @@ export function QADashboard({
return (
<div className="qa-dashboard-scroll">
<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}
</details>
</div>
)
}
+19
View File
@@ -2,7 +2,26 @@ import { renderToStaticMarkup } from 'react-dom/server'
import { it, expect } from 'vitest'
import { QADashboardDrawing } from './QADashboardDrawing'
import { dashboardFixture } from './qaDashboard.fixture'
import { calendarDashboardFixture } from './qaDashboardMonthly.fixture'
it('keeps the month identifiers intact on a narrow monthly-dashboard heading', () => {
const html = renderToStaticMarkup(
<QADashboardDrawing data={parseQADashboard(calendarDashboardFixture)} width={362} />
)
expect(html).toContain('区域统计 2026-10 月累计')
const accuracy = html.split('data-panel="accuracy-trend"')[1]
expect(accuracy).toMatch(/<text[^>]*>2026-09<\/text>/)
expect(accuracy).toMatch(/<text[^>]*>—<\/text>/)
})
import { parseQADashboard } from './qaDashboardData'
it('places a keyboard-accessible statistics definition in the upper-right of every card', () => {
const html = renderToStaticMarkup(<QADashboardDrawing data={parseQADashboard(dashboardFixture)} width={1280} />)
expect((html.match(/data-statistics-help=/g) || []).length).toBe(11)
expect((html.match(/统计口径<\/text>/g) || []).length).toBe(11)
expect((html.match(/aria-label="[^"]*统计口径[^"]*"/g) || []).length).toBe(11)
expect(html).toContain('tabindex="0"')
expect(html).toContain('原始提问时间')
expect(html).toContain('是÷(是+否)')
})
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)
+190 -86
View File
@@ -1,4 +1,6 @@
import { createContext, useContext, useState } from 'react'
import type { ReactNode, Ref } from 'react'
import { dashboardStatisticsHelp } from './qaDashboardStatistics'
import type { QADashboardData, DashboardCount, DashboardRegion } from './qaDashboardData'
import type { QualityRate } from './qaQuality'
import { currentQAWeek } from './qaWeeks'
@@ -10,6 +12,17 @@ interface Box {
w: number
h: number
}
interface StatisticsTip {
id: string
box: Box
baseline: number
}
const StatisticsContext = createContext<{
definitions: Record<string, string>
show: (tip: StatisticsTip) => void
hide: (id: string) => void
active: string | null
} | null>(null)
const blue = '#3274e6',
ink = '#23344d',
muted = '#7a8799',
@@ -79,6 +92,9 @@ function Panel({
children: ReactNode
tint?: string
}) {
const statistics = useContext(StatisticsContext),
hint = statistics?.definitions[id] ?? '',
baseline = box.w < 140 ? 59 : 25
return (
<g data-panel={id} transform={`translate(${box.x} ${box.y})`}>
<rect width={box.w} height={box.h} rx={7} fill={tint} />
@@ -89,6 +105,33 @@ function Panel({
{en}
</text>
{children}
<g
data-statistics-help={id}
role="button"
tabIndex={0}
aria-label={`${title}统计口径`}
aria-describedby={`qa-statistics-description-${id}`}
aria-expanded={statistics?.active === id}
style={{ cursor: 'help' }}
onMouseEnter={() => statistics?.show({ id, box, baseline })}
onMouseLeave={() => statistics?.hide(id)}
onFocus={() => statistics?.show({ id, box, baseline })}
onBlur={() => statistics?.hide(id)}
onClick={() => statistics?.show({ id, box, baseline })}
onKeyDown={(e) => {
if (e.key === 'Escape') statistics?.hide(id)
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
statistics?.show({ id, box, baseline })
}
}}
>
<desc id={`qa-statistics-description-${id}`}>{hint}</desc>
<rect x={box.w - 72} y={baseline - 17} width={62} height={24} rx={3} fill="transparent" />
<text x={box.w - 16} y={baseline} textAnchor="end" fontSize={10.5} fill={muted}>
统计口径
</text>
</g>
</g>
)
}
@@ -276,6 +319,7 @@ function Plot({
id,
points,
percent = false,
monthly = false,
}: {
box: Box
title: string
@@ -283,6 +327,7 @@ function Plot({
id: string
points: PlotPoint[]
percent?: boolean
monthly?: boolean
}) {
const left = 44,
right = box.w - 22,
@@ -293,7 +338,11 @@ function Plot({
points.length === 1 ? (left + right) / 2 : left + (i * (right - left)) / Math.max(1, points.length - 1),
y = (n: number) => bottom - (n / max) * (bottom - top)
const color = (source: PlotPoint['source']) =>
source === 'master_live_cumulative_v1' ? '#249c86' : source === 'system_frozen' ? '#8b68c7' : blue
source === 'master_live_cumulative_v1' || source === 'master_live_calendar_month_v1'
? '#249c86'
: source === 'system_frozen'
? '#8b68c7'
: blue
const paths = [...new Set(points.map((p) => p.source))].map((source) => {
let path = '',
open = false
@@ -311,7 +360,7 @@ function Plot({
const every = Math.max(1, Math.ceil(points.length / (box.w < 420 ? 5 : 8)))
const labelled = new Set<number>()
const label = (i: number) => {
if (points[i]?.value !== null && points[i] && [...labelled].every((k) => Math.abs(x(k) - x(i)) >= 52))
if ((monthly || points[i]?.value !== null) && points[i] && [...labelled].every((k) => Math.abs(x(k) - x(i)) >= 52))
labelled.add(i)
}
label(0)
@@ -355,6 +404,7 @@ function Plot({
key={point.label}
data-source={point.source}
data-week={point.week}
data-month={point.month}
data-value={point.value ?? undefined}
data-frozen={point.frozen === undefined ? undefined : point.frozen ? 'available' : 'missing'}
>
@@ -375,6 +425,11 @@ function Plot({
) : null}
</>
) : null}
{monthly && point.value === null ? (
<text x={x(i)} y={bottom - 9} textAnchor="middle" fill={muted} fontSize={11}>
—
</text>
) : null}
{labelled.has(i) ? (
<text x={x(i)} y={bottom + 22} textAnchor="middle" fill={muted} fontSize={10}>
{point.label}
@@ -384,11 +439,13 @@ function Plot({
))}
{percent ? (
<text x={16} y={box.h - 7} fontSize={9} fill={muted}>
{points.some((p) => p.source === 'master_live_cumulative_v1')
? '蓝:历史上报;紫:系统冻结;绿:总表累计'
: points.some((p) => p.source === 'user_provided_history')
? '蓝:用户提供(未提供分子/分母);紫:系统冻结'
: '缺失周留空;系统冻结与当前实时结果分开'}
{monthly
? '自然月独立计算 · 当前有效结论 · 空分母留空'
: points.some((p) => p.source === 'master_live_cumulative_v1')
? '蓝:历史上报;紫:系统冻结;绿:总表累计'
: points.some((p) => p.source === 'user_provided_history')
? '蓝:用户提供(未提供分子/分母);紫:系统冻结'
: '缺失周留空;系统冻结与当前实时结果分开'}
</text>
) : null}
{!points.some((p) => p.value !== null) ? (
@@ -477,15 +534,22 @@ export function QADashboardDrawing({
width: number
svgRef?: Ref<SVGSVGElement>
}) {
const [tip, setTip] = useState<StatisticsTip | null>(null)
const definitions = dashboardStatisticsHelp(data)
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,
mobile = w < 900,
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),
heading = `${data.week_start.slice(0, 10)} 起的自然周${data.quality_period ? ` · 质量 ${data.quality_period.month} 月内累计` : ''} · 区域统计 ${new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7)} 月累计`,
headingLines = (mobile ? [heading.split(' · ')[0], heading.split(' · ').slice(1).join(' · ')] : [heading]).flatMap(
(row) => wrap(row, inner - 16, 10.5)
),
filterY = 47 + headingLines.length * 14,
header = filterY + (data.keyword ? filterLines.length * 15 : 0) + 4,
metricH = mobile ? 154 : 166
const metrics: Box[] = Array.from({ length: 4 }, (_, i) =>
mobile
@@ -540,85 +604,125 @@ export function QADashboardDrawing({
height = mobile ? cursor + 540 + gap + pad : cursor + 270 + pad
const frozen = (correctness: boolean): PlotPoint[] => historicalTrend(data, correctness)
const month = new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7)
const tipWidth = Math.min(334, inner),
tipLines = wrap(tip ? definitions[tip.id] : '', tipWidth - 26, 11.5),
tipHeight = tipLines.length * 15.525 + 26,
tipX = tip ? Math.max(pad, Math.min(w - pad - tipWidth, tip.box.x + tip.box.w - tipWidth - 10)) : 0,
tipY = tip ? Math.max(pad, Math.min(height - pad - tipHeight, tip.box.y + tip.baseline + 10)) : 0
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',
<StatisticsContext.Provider
value={{
definitions,
show: setTip,
hide: (id) => setTip((current) => (current?.id === id ? null : current)),
active: tip?.id ?? null,
}}
>
<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>
<svg
ref={svgRef}
className="qa-dashboard-svg"
xmlns="http://www.w3.org/2000/svg"
width="100%"
viewBox={`0 0 ${w} ${height}`}
role="group"
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>
{headingLines.map((row, index) => (
<Text key={index} x={pad + 6} y={46 + index * 14} width={inner - 16} size={10.5} fill={muted} value={row} />
))}
{data.keyword ? (
<Text x={pad + 6} y={filterY} 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${data.quality_period ? ` · ${data.quality_period.month}` : ''}`}
id="coverage"
rate={data.monthly_quality?.coverage ?? data.quality.rates.coverage}
/>
<Gauge
box={metrics[3]}
title="正确率"
en={`Accuracy Rate${data.quality_period ? ` · ${data.quality_period.month}` : ''}`}
id="accuracy"
rate={data.monthly_quality?.correctness ?? 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)}
monthly={!!data.quality_period}
percent
/>
<Plot
box={accuracy}
title="正确率趋势"
en="Accuracy Rate Trend"
id="accuracy-trend"
points={frozen(true)}
monthly={!!data.quality_period}
percent
/>
{tip ? (
<g
role="tooltip"
data-statistics-tooltip={tip.id}
pointerEvents="none"
transform={`translate(${tipX} ${tipY})`}
>
<rect x={2} y={3} width={tipWidth} height={tipHeight} rx={5} fill="#dce4ee" opacity={0.65} />
<rect width={tipWidth} height={tipHeight} rx={5} fill="#fff" stroke="#ccd8e8" />
<Text x={13} y={22} width={tipWidth - 26} size={11.5} value={definitions[tip.id]} />
</g>
) : null}
</svg>
</StatisticsContext.Provider>
)
}
+2 -5
View File
@@ -4,7 +4,7 @@ import { fetchAllQARecords } from './qaOps'
import { currentQAWeekValue, qaDateTimeToISO, qaWeekQueryRange } from './qaWeeks'
import { WeeklyDraftEditorModel } from './qaWeeklyDrafts'
import { weeklyTransport } from './qaWeeklyDraftAPI'
import { buildQAWeeklyCSV, downloadQAWeekly } from './qaWeekly'
import { buildQAWeeklyCSV, downloadQAWeekly, weeklyQualitySourceLabel } from './qaWeekly'
import { QAAnswerMarkdown } from './QAAnswerMarkdown'
import { QAPeriodInput } from './QAPeriodInput'
import './qaWeeklyEditor.css'
@@ -258,10 +258,7 @@ export function QAWeekly({ onBeforeLeave }: Props) {
{typeof source.end === 'string'
? new Date(source.end).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
: '—'}{' '}
·{' '}
{{ 'live-week': '当周实时质量指标', 'frozen-week': '已冻结周指标', 'reported-history': '历史上报指标' }[
String(source.quality_source)
] ?? '指标来源未确认'}
· {weeklyQualitySourceLabel(source.quality_source)}
</p>
<p>
问题总数与新增是可编辑的系统统计建议;区域采用已保存配置及当前通讯录。未做新的FAQ调整,重点与英文文字请自行填写。草稿不会自动发送。
+3 -14
View File
@@ -24,20 +24,9 @@
width: 100%;
height: auto;
}
.qa-monthly-disclosure {
margin-top: 14px;
border-top: 1px solid var(--border-base);
padding: 14px 0;
}
.qa-monthly-disclosure > summary {
font-size: 13px;
cursor: pointer;
}
.qa-monthly-disclosure .qa-monthly {
min-height: 400px;
max-height: 650px;
margin-top: 12px;
overflow: auto;
.qa-dashboard-svg [data-statistics-help]:focus-visible {
outline: 2px solid #3274e6;
outline-offset: 2px;
}
.qa-weekly {
display: flex;
+145
View File
@@ -36,6 +36,28 @@ export interface DashboardCumulative {
source: 'master_live_cumulative_v1'
policy_version: 'weekly-strict-yes-over-yes-no-v1'
}
export interface DashboardStrictQuality {
records: number
coverage: QualityRate
correctness: QualityRate
}
export interface DashboardQualityPeriod {
month: string
start: string
cutoff_at: string
calculated_at: string
source: 'master_live_calendar_month_v1'
policy_version: 'calendar-month-strict-yes-over-yes-no-v1'
}
export interface DashboardMonth extends DashboardStrictQuality {
month: string
month_start: string
month_end: string
cutoff_at: string
calculated_at: string
source: 'master_live_calendar_month_v1'
policy_version: 'calendar-month-strict-yes-over-yes-no-v1'
}
export interface DashboardRegion {
id: string
name: string
@@ -64,6 +86,9 @@ export interface QADashboardData {
frozen_weeks: DashboardFrozen[]
reported_weeks: DashboardReported[]
cumulative_weeks?: DashboardCumulative[]
quality_period?: DashboardQualityPeriod
monthly_quality?: DashboardStrictQuality
calendar_months?: DashboardMonth[]
}
const bad = (): never => {
throw new Error('统计看板响应无效,未展示可能失真的指标')
@@ -305,7 +330,127 @@ export function parseQADashboard(value: unknown): QADashboardData {
}
}
)
let quality_period: DashboardQualityPeriod | undefined
let monthly_quality: DashboardStrictQuality | undefined
let calendar_months: DashboardMonth[] | undefined
const monthlySource = 'master_live_calendar_month_v1' as const,
monthlyPolicy = 'calendar-month-strict-yes-over-yes-no-v1' as const,
nextMonth = (at: number) => {
const d = new Date(at + offset)
return Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 1) - offset
},
monthLabel = (at: number) => new Date(at + offset).toISOString().slice(0, 7),
strictRates = (raw: Record<string, unknown>): DashboardStrictQuality => {
const records = count(raw.records),
coverage = parseQualityRate(raw.coverage),
correctness = parseQualityRate(raw.correctness)
if (records > total_issues || coverage.denominator > records || correctness.denominator > records) return bad()
return { records, coverage, correctness }
}
if (
v.quality_period !== undefined ||
v.monthly_quality !== undefined ||
(v.calendar_months !== undefined && list(v.calendar_months).length)
) {
const p = obj(v.quality_period),
begin = stamp(p.start),
cutoff = stamp(p.cutoff_at),
calculated = stamp(p.calculated_at),
expectedBegin = month(Date.parse(week_start))
if (
p.source !== monthlySource ||
p.policy_version !== monthlyPolicy ||
text(p.month) !== monthLabel(expectedBegin) ||
Date.parse(begin) !== expectedBegin ||
Date.parse(cutoff) <= expectedBegin ||
Date.parse(cutoff) !== Math.min(nextMonth(expectedBegin), Date.parse(end), Date.parse(calculated))
)
return bad()
if (
Object.keys(p).some(
(key) => !['month', 'start', 'cutoff_at', 'calculated_at', 'source', 'policy_version'].includes(key)
)
)
return bad()
const rawQuality = obj(v.monthly_quality)
if (Object.keys(rawQuality).some((key) => !['records', 'coverage', 'correctness'].includes(key))) return bad()
quality_period = {
month: text(p.month),
start: begin,
cutoff_at: cutoff,
calculated_at: calculated,
source: monthlySource,
policy_version: monthlyPolicy,
}
monthly_quality = strictRates(rawQuality)
const rawMonths = list(v.calendar_months)
calendar_months = rawMonths.map((raw, i): DashboardMonth => {
const point = obj(raw),
month_start = stamp(point.month_start),
month_end = stamp(point.month_end),
cutoff_at = stamp(point.cutoff_at),
calculated_at = stamp(point.calculated_at),
at = Date.parse(month_start),
rates = strictRates(point)
if (
at !== month(at) ||
text(point.month) !== monthLabel(at) ||
Date.parse(month_end) !== nextMonth(at) ||
Date.parse(cutoff_at) <= at ||
Date.parse(cutoff_at) !== Math.min(Date.parse(month_end), Date.parse(cutoff), Date.parse(calculated_at)) ||
calculated_at !== calculated ||
point.source !== monthlySource ||
point.policy_version !== monthlyPolicy ||
(i > 0 && at !== Date.parse(text(obj(rawMonths[i - 1]).month_end)))
)
return bad()
if (
Object.keys(point).some(
(key) =>
![
'month',
'month_start',
'month_end',
'cutoff_at',
'calculated_at',
'records',
'coverage',
'correctness',
'source',
'policy_version',
].includes(key)
)
)
return bad()
return {
month: text(point.month),
month_start,
month_end,
cutoff_at,
calculated_at,
...rates,
source: monthlySource,
policy_version: monthlyPolicy,
}
})
if (calendar_months.length > 1200 || calendar_months.reduce((n, point) => n + point.records, 0) > total_issues)
return bad()
const last = calendar_months.at(-1)
if (last) {
if (
last.month !== quality_period.month ||
last.cutoff_at !== quality_period.cutoff_at ||
last.records !== monthly_quality.records ||
JSON.stringify(last.coverage) !== JSON.stringify(monthly_quality.coverage) ||
JSON.stringify(last.correctness) !== JSON.stringify(monthly_quality.correctness)
)
return bad()
} else if (monthly_quality.records !== 0) return bad()
}
return {
quality_period,
monthly_quality,
calendar_months,
start,
end,
keyword,
+1
View File
@@ -13,6 +13,7 @@ export async function createDashboardPNG(svg: SVGSVGElement): Promise<Blob> {
copy.querySelector('foreignObject,image,script,iframe,use')
)
throw new Error('看板内容不完整,未生成图片')
copy.querySelectorAll('[data-statistics-tooltip]').forEach((popover) => popover.remove())
copy.setAttribute('width', String(box.width))
copy.setAttribute('height', String(box.height))
copy.style.width = `${box.width}px`
+43
View File
@@ -0,0 +1,43 @@
import { dashboardFixture } from './qaDashboard.fixture'
export const calendarDashboardFixture = {
...dashboardFixture,
quality_period: {
month: '2026-10',
start: '2026-10-01T00:00:00+08:00',
cutoff_at: dashboardFixture.end,
calculated_at: dashboardFixture.as_of,
source: 'master_live_calendar_month_v1',
policy_version: 'calendar-month-strict-yes-over-yes-no-v1',
},
monthly_quality: {
records: 3,
coverage: { numerator: 2, denominator: 3, percent: 200 / 3 },
correctness: { numerator: 1, denominator: 2, percent: 50 },
},
calendar_months: [
{
month: '2026-09',
month_start: '2026-09-01T00:00:00+08:00',
month_end: '2026-10-01T00:00:00+08:00',
cutoff_at: '2026-10-01T00:00:00+08:00',
calculated_at: dashboardFixture.as_of,
records: 1,
coverage: { numerator: 0, denominator: 1, percent: 0 },
correctness: { numerator: 0, denominator: 0, percent: null },
source: 'master_live_calendar_month_v1',
policy_version: 'calendar-month-strict-yes-over-yes-no-v1',
},
{
month: '2026-10',
month_start: '2026-10-01T00:00:00+08:00',
month_end: '2026-11-01T00:00:00+08:00',
cutoff_at: dashboardFixture.end,
calculated_at: dashboardFixture.as_of,
records: 3,
coverage: { numerator: 2, denominator: 3, percent: 200 / 3 },
correctness: { numerator: 1, denominator: 2, percent: 50 },
source: 'master_live_calendar_month_v1',
policy_version: 'calendar-month-strict-yes-over-yes-no-v1',
},
],
}
+31
View File
@@ -0,0 +1,31 @@
import { it, expect } from 'vitest'
import { parseQADashboard } from './qaDashboardData'
import { calendarDashboardFixture as fixture } from './qaDashboardMonthly.fixture'
import { historicalTrend } from './qaHistoricalTrend'
it('uses month-axis points and leaves unknown rates empty instead of reusing weekly snapshots', () => {
const data = parseQADashboard(fixture)
const coverage = historicalTrend(data, false),
accuracy = historicalTrend(data, true)
expect(coverage.map((p) => p.label)).toEqual(['2026-09', '2026-10'])
expect(accuracy.map((p) => p.value)).toEqual([null, 50])
expect(coverage.every((p) => p.source === 'master_live_calendar_month_v1')).toBe(true)
expect(coverage[1].hint).toContain('是÷(是+否)')
expect(accuracy[0].hint).toContain('月内 1 条')
})
it('rejects extra private payload fields in every calendar-month projection', () => {
for (const input of [
{ ...fixture, quality_period: { ...fixture.quality_period, answer: 'not part of statistics' } },
{ ...fixture, monthly_quality: { ...fixture.monthly_quality, staff_id: 'not part of statistics' } },
{
...fixture,
calendar_months: fixture.calendar_months.map((p, i) => (i ? p : { ...p, payload: 'not part of statistics' })),
},
])
expect(() => parseQADashboard(input)).toThrow()
})
it('parses independent calendar-month strict rates without restricting correctness to covered rows', () => {
const data = parseQADashboard(fixture)
expect(data).toHaveProperty('quality_period', fixture.quality_period)
expect(data).toHaveProperty('monthly_quality', fixture.monthly_quality)
expect(data).toHaveProperty('calendar_months', fixture.calendar_months)
})
+36
View File
@@ -0,0 +1,36 @@
import type { QADashboardData } from './qaDashboardData'
const beijing = (at: string) => new Date(Date.parse(at) + 8 * 3600000).toISOString().slice(0, 19).replace('T', ' ')
const windowText = (start: string, end: string) => `北京时间 ${beijing(start)} 至 ${beijing(end)}(终点不含)。`
export function dashboardStatisticsHelp(data: QADashboardData): Record<string, string> {
const filter = '沿用已执行关键词筛选。',
week = windowText(data.start, data.end),
regionMonth = windowText(data.month_start, data.end),
period = data.quality_period,
rates = data.monthly_quality,
qualityRange = period ? windowText(period.start, period.cutoff_at) : week,
qualityRecords = rates?.records ?? data.quality.total,
coverage = rates?.coverage ?? data.quality.rates.coverage,
correctness = rates?.correctness ?? data.quality.rates.correctness,
calendar =
'每月1日重新累计,不累计之前月份,不平均周百分比;按原始提问时间归月,使用当前有效结论及点踩否,空分母留空。',
qualityScope = period
? `统计月 ${period.month}。跨月周取周一所在月;当前未结束只截至实际时点。`
: '旧接口按所选查询范围统计。'
return {
total: `截至北京时间 ${beijing(data.end)}(不含),治理总表历史导入和2.0收录的去重问题记录数,共 ${data.total_issues} 条;不把当前页条数当总数,不因缺少分析字段排除。${filter}`,
'new-week': `${windowText(data.week_start, data.end)}本周新增=原始提问时间落在本自然周内的问题数,共 ${data.new_this_week} 条;当前周截至当前,不按导入时间算新增。${filter}`,
coverage: `${qualityScope}${qualityRange}${rates ? '覆盖率=覆盖是÷(是+否)×100%。部分覆盖、待确认、未知、空白、失效等不计分母。' : '旧覆盖率=覆盖是÷(覆盖是+覆盖否+部分覆盖)×100%。'}本范围 ${qualityRecords} 条;分子 ${coverage.numerator},分母 ${coverage.denominator},排除 ${qualityRecords - coverage.denominator} 条。${filter}`,
accuracy: `${qualityScope}${qualityRange}${rates ? '正确率=正确是÷(是+否)×100%;不限定仅已覆盖问题。' : '旧正确率=已覆盖样本内的正确是÷(是+否)×100%。'}本范围 ${qualityRecords} 条;分子 ${correctness.numerator},分母 ${correctness.denominator},排除 ${qualityRecords - correctness.denominator} 条。待确认、未知、空白、失效等排除;已判定样本正确率不代表全部问题已确认。${filter}`,
'issue-types': `${week}按本查询范围内每条问题的当前有效“问题类型”归组,每条计1次;缺失保留“未分类”。饼图占比=该类型条数÷范围内 ${data.quality.total} 条×100%。${filter}`,
products: `${week}按当前有效“产品分类”归组,每条问题计1次,数量降序;缺失保留“未分类”,不与问题类型混用。范围共 ${data.quality.total} 条。${filter}`,
'issue-trend': `${windowText(data.week_start, data.end)}按原始提问时间在北京时间逐日计数,零提问日保留;各日合计=本周新增 ${data.new_this_week} 条,不按导入日计算。${filter}`,
frequency: `${regionMonth}区域平均使用频率=能稳定关联该区域的月内提问条数÷当前配置通讯录去重人数。缺失/待核对身份不强行归属,零分母显示“—”;当前名册不是在职或绩效名单。${filter}`,
'usage-coverage': `${regionMonth}区域使用覆盖率=月内稳定身份去重使用人数÷同一区域当前配置通讯录去重人数×100%。零使用者保留在分母,无法关联者不凑人数;无名单或零分母显示“—”,不是绩效结论。${filter}`,
'coverage-trend': period
? `每个点是一个北京时间自然月,覆盖率=覆盖是÷(是+否)×100%。${calendar}最后截止北京时间 ${beijing(period.cutoff_at)}(不含)。旧周上报/冻结仅保留证据,不混入月曲线。${filter}`
: `旧接口逐自然周分别保留上报、冻结及总表累计来源;不把旧周百分比换算成月比例。${filter}`,
'accuracy-trend': period
? `每个点是一个北京时间自然月,正确率=正确是÷(是+否)×100%;待确认等排除,各点保留月内条数及分子/分母。${calendar}最后截止北京时间 ${beijing(period.cutoff_at)}(不含)。${filter}`
: `旧接口逐周保留来源;正确是÷(是+否),缺失留空,不复制当前比例凑历史曲线。${filter}`,
}
}
+14 -1
View File
@@ -5,11 +5,24 @@ export interface HistoricalPlotPoint {
value: number | null
hint: string
frozen?: boolean
source?: 'user_provided_history' | 'system_frozen' | 'master_live_cumulative_v1'
source?: 'user_provided_history' | 'system_frozen' | 'master_live_cumulative_v1' | 'master_live_calendar_month_v1'
month?: string
week?: string
}
// Never manufacture row counts or connect a line across missing weeks/policy changes.
export function historicalTrend(data: QADashboardData, correctness: boolean): HistoricalPlotPoint[] {
if (data.quality_period) {
return (data.calendar_months ?? []).map((point) => {
const rate = correctness ? point.correctness : point.coverage
return {
label: point.month,
month: point.month,
value: rate.percent,
source: point.source,
hint: `${point.month}:${rate.percent === null ? '—' : rate.percent.toFixed(2) + '%'};${rate.numerator}/${rate.denominator};月内 ${point.records} 条,排除 ${point.records - rate.denominator} 条;[${point.month_start}, ${point.cutoff_at});每月独立,是÷(是+否),当前有效字段动态重算,非历史冻结`,
}
})
}
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 cumulative = new Map((data.cumulative_weeks ?? []).map((p) => [Date.parse(p.week_start), p]))
+5 -1
View File
@@ -2,7 +2,11 @@ import { describe, it, expect } from 'vitest'
import { renderToStaticMarkup } from 'react-dom/server'
import { createElement } from 'react'
import { QAAnswerMarkdown } from './QAAnswerMarkdown'
import { buildQAWeeklyDraft } from './qaWeekly'
import { buildQAWeeklyDraft, weeklyQualitySourceLabel } from './qaWeekly'
it('identifies the calendar-month prefill policy rather than labelling it unknown or weekly', () => {
expect(weeklyQualitySourceLabel('master_live_calendar_month_v1')).toBe('自然月累计质量指标(跨月周按上月)')
expect(weeklyQualitySourceLabel('reported-history')).toBe('历史上报指标')
})
import type { QARecordPage, QAQuery } from './qaOps'
import type { QualitySummary } from './qaQuality'
const query: QAQuery = { start: '2026-10-11T16:00:00Z', end: '2026-10-18T10:00:00Z', keyword: '', cursor: '' }
+10
View File
@@ -2,6 +2,16 @@ import type { QARecordPage, QAQuery } from './qaOps'
import { qaCellValue, qaColumns } from './qaOps'
import type { QualitySummary, QualityRate } from './qaQuality'
import { qaDailySeries, qaCategorySeries } from './qaDashboard'
export function weeklyQualitySourceLabel(source: unknown): string {
return (
new Map([
['live-week', '当周实时质量指标'],
['frozen-week', '已冻结周指标'],
['reported-history', '历史上报指标'],
['master_live_calendar_month_v1', '自然月累计质量指标(跨月周按上月)'],
]).get(String(source)) ?? '指标来源未确认'
)
}
export interface QAWeeklyDraft {
markdown: string
csv: string