diff --git a/internal/dobotaiops/records.go b/internal/dobotaiops/records.go index 1d425ba..debbcfb 100644 --- a/internal/dobotaiops/records.go +++ b/internal/dobotaiops/records.go @@ -105,6 +105,10 @@ type RecordQuery struct { Keyword string Cursor string Limit int + // Granularity is only honoured by the statistics dashboard. Empty keeps the + // historical weekly board; "day"|"week"|"month"|"custom" makes every panel + // follow the selected Window alone. + Granularity string } type QualityKey struct { diff --git a/internal/httpapi/qa_dashboard.go b/internal/httpapi/qa_dashboard.go index 2792cff..09d7092 100644 --- a/internal/httpapi/qa_dashboard.go +++ b/internal/httpapi/qa_dashboard.go @@ -19,10 +19,11 @@ func qaOperationsDashboard(w http.ResponseWriter, r *http.Request, c Config) { return } var request struct { - Start string `json:"start"` - End string `json:"end"` - Keyword string `json:"keyword"` - Filters map[string]string `json:"filters,omitempty"` + Start string `json:"start"` + End string `json:"end"` + Keyword string `json:"keyword"` + Filters map[string]string `json:"filters,omitempty"` + Granularity string `json:"granularity,omitempty"` } if decodeQualityJSON(w, r, &request, "start", "end") != nil { qaOpsError(w, dobotaiops.ErrInvalidQuery) @@ -38,7 +39,7 @@ func qaOperationsDashboard(w http.ResponseWriter, r *http.Request, c Config) { qaOpsError(w, e) return } - dashboard, e := reader.ReadMasterDashboard(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword, Filters: request.Filters}) + dashboard, e := reader.ReadMasterDashboard(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword, Filters: request.Filters, Granularity: request.Granularity}) if e != nil { if errors.Is(e, qaopsquality.ErrConflict) { writeQualityError(w, e) diff --git a/internal/httpapi/qa_dashboard_test.go b/internal/httpapi/qa_dashboard_test.go index 256d379..ab6a9dc 100644 --- a/internal/httpapi/qa_dashboard_test.go +++ b/internal/httpapi/qa_dashboard_test.go @@ -29,6 +29,27 @@ func (s *dashboardReaderSpy) ReadMasterDashboard(ctx context.Context, q dobotaio s.masterCalls++ return s.ReadDashboard(ctx, q) } +func TestQADashboardForwardsGranularityToTheReader(t *testing.T) { + reader := &dashboardReaderSpy{} + auth := newFakeAuthStore() + auth.sessions["dash-admin"] = "usr-boss" + h, e := NewHandler(Config{Store: &fakeJobStore{}, QAOps: reader, QAOpsTenantKey: "fixed-dashboard-tenant", Now: func() time.Time { return time.Date(2026, 12, 3, 12, 0, 0, 0, time.UTC) }, Auth: &AuthConfig{Store: auth}}) + if e != nil { + t.Fatal(e) + } + body := `{"start":"2026-11-01T00:00:00+08:00","end":"2026-12-01T00:00:00+08:00","keyword":"","granularity":"month"}` + r := httptest.NewRequest(http.MethodPost, "/api/v1/qa-ops/dashboard", strings.NewReader(body)) + r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "dash-admin"}) + r.Header.Set("X-Governance-Action", "qa-dashboard") + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != http.StatusOK { + t.Fatalf("month dashboard status=%d want200", w.Code) + } + if reader.query.Granularity != "month" { + t.Fatalf("granularity = %q, want month", reader.query.Granularity) + } +} func TestQADashboardIsFixedTenantAdminAndReadOnly(t *testing.T) { reader := &dashboardReaderSpy{} auth := newFakeAuthStore() diff --git a/internal/qaopsmirror/dashboard.go b/internal/qaopsmirror/dashboard.go index 2b5d56b..aca550a 100644 --- a/internal/qaopsmirror/dashboard.go +++ b/internal/qaopsmirror/dashboard.go @@ -42,28 +42,33 @@ type DashboardRegion struct { UsageCoverage qaopsquality.Rate `json:"usage_coverage"` } type Dashboard struct { - Start time.Time `json:"start"` - End time.Time `json:"end"` - Keyword string `json:"keyword"` - Filters map[string]string `json:"filters,omitempty"` - AsOf time.Time `json:"as_of"` - LocalRevision int64 `json:"local_revision"` - Organization dobotaiops.OrganizationVersion `json:"organization"` - TotalIssues int `json:"total_issues"` - NewThisWeek int `json:"new_this_week"` - WeekStart time.Time `json:"week_start"` - MonthStart time.Time `json:"month_start"` - Quality qaopsquality.Summary `json:"quality"` - IssueTypes []DashboardCount `json:"issue_types"` - Products []DashboardCount `json:"products"` - Daily []DashboardDaily `json:"daily"` - Regions []DashboardRegion `json:"regions"` - 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"` + Start time.Time `json:"start"` + End time.Time `json:"end"` + Keyword string `json:"keyword"` + Filters map[string]string `json:"filters,omitempty"` + Granularity string `json:"granularity,omitempty"` + Period *DashboardPeriod `json:"period,omitempty"` + PeriodIssues *int `json:"period_issues,omitempty"` + PrevPeriodIssues *int `json:"prev_period_issues,omitempty"` + PeriodQuality *DashboardStrictQuality `json:"period_quality,omitempty"` + AsOf time.Time `json:"as_of"` + LocalRevision int64 `json:"local_revision"` + Organization dobotaiops.OrganizationVersion `json:"organization"` + TotalIssues int `json:"total_issues"` + NewThisWeek int `json:"new_this_week"` + WeekStart time.Time `json:"week_start"` + MonthStart time.Time `json:"month_start"` + Quality qaopsquality.Summary `json:"quality"` + IssueTypes []DashboardCount `json:"issue_types"` + Products []DashboardCount `json:"products"` + Daily []DashboardDaily `json:"daily"` + Regions []DashboardRegion `json:"regions"` + 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) diff --git a/internal/qaopsmirror/dashboard_period.go b/internal/qaopsmirror/dashboard_period.go new file mode 100644 index 0000000..34355ba --- /dev/null +++ b/internal/qaopsmirror/dashboard_period.go @@ -0,0 +1,85 @@ +package qaopsmirror + +import ( + "context" + "fmt" + "time" + + "github.com/jackc/pgx/v5" + "knowledge-governance/internal/dobotaiops" +) + +// The statistics board accepts an explicit granularity so every panel is cut +// from ONE selected range. Empty granularity keeps the historical weekly board +// (start/end derived from the selected week) byte-for-byte unchanged. +const ( + dashboardGranularityDay = "day" + dashboardGranularityWeek = "week" + dashboardGranularityMonth = "month" + dashboardGranularityCustom = "custom" +) + +func validDashboardGranularity(kind string) bool { + switch kind { + case "", dashboardGranularityDay, dashboardGranularityWeek, dashboardGranularityMonth, dashboardGranularityCustom: + return true + } + return false +} + +type DashboardPeriod struct { + Kind string `json:"kind"` + Label string `json:"label"` + Start time.Time `json:"start"` + End time.Time `json:"end"` + PrevStart time.Time `json:"prev_start"` + PrevEnd time.Time `json:"prev_end"` +} + +// dashboardPeriod describes the selected range in Beijing time and derives the +// immediately preceding range of the same length so the board can show a +// like-for-like comparison instead of a second, hidden time window. +func dashboardPeriod(kind string, start, end time.Time) DashboardPeriod { + local := start.In(dashboardLocation) + finishLocal := end.In(dashboardLocation) + out := DashboardPeriod{Kind: kind, Start: start, End: end, PrevEnd: start} + switch kind { + case dashboardGranularityDay: + out.Label = local.Format("2006-01-02") + out.PrevStart = start.AddDate(0, 0, -1) + case dashboardGranularityWeek: + first := local.AddDate(0, 0, -((int(local.Weekday()) + 6) % 7)) + year, week := first.ISOWeek() + out.Label = fmt.Sprintf("%d 第%d周", year, week) + out.PrevStart = start.AddDate(0, 0, -7) + case dashboardGranularityMonth: + out.Label = local.Format("2006-01") + out.PrevStart = start.AddDate(0, -1, 0) + default: + out.Label = fmt.Sprintf("%s 至 %s", local.Format("2006-01-02"), finishLocal.Format("2006-01-02")) + out.PrevStart = start.Add(-end.Sub(start)) + } + return out +} + +// dashboardPeriodIssues counts records whose original asked_at falls inside the +// selected range. The historical "total_issues" keeps counting everything up to +// the range end, so the two numbers stay distinguishable on the board. +func (s *Store) dashboardPeriodIssues(ctx context.Context, tx pgx.Tx, q dobotaiops.RecordQuery, master bool, start, end time.Time) (int, error) { + table, question := "qa_ops_mirror_records", "lower(question)" + if master { + table = "qa_ops_master_read_model" + question = "lower(question||E'\\n'||chinese_question||E'\\n'||COALESCE(ai_fields->>'question_chinese',''))" + } + sql := fmt.Sprintf(`SELECT count(*) FROM %s WHERE tenant_key=$1 AND asked_at>=$2 AND asked_at<$3 AND ($4='' OR position(%s IN %s)>0)`, table, question, question) + args := []any{s.tenant, start, end, q.Keyword} + if q.MatchIDs != nil { + sql += " AND id=ANY($5::text[])" + args = append(args, q.MatchIDs) + } + var n int + if err := tx.QueryRow(ctx, sql, args...).Scan(&n); err != nil { + return 0, dobotaiops.ErrUnavailable + } + return n, nil +} diff --git a/internal/qaopsmirror/dashboard_period_integration_test.go b/internal/qaopsmirror/dashboard_period_integration_test.go new file mode 100644 index 0000000..f1a81c9 --- /dev/null +++ b/internal/qaopsmirror/dashboard_period_integration_test.go @@ -0,0 +1,109 @@ +package qaopsmirror + +import ( + "context" + "encoding/json" + "testing" + "time" + + "knowledge-governance/internal/dobotaiops" + pg "knowledge-governance/internal/platform/postgres" +) + +// A monthly board must cut every panel from the selected range: the in-range +// count, the daily trend, the strict quality sample and the previous range. +func TestMonthlyGranularityCutsEveryPanelFromTheSelectedRange(t *testing.T) { + pool := mirrorFixture(t) + ctx := context.Background() + s := NewStore(pool, "fixture-monthly-period") + queue := pg.NewStore(pool) + rows := make([]dobotaiops.MirrorRecord, 0, 3) + for _, spec := range []struct{ id, askedAt string }{ + {"oct-record", "2026-10-15T08:00:00+08:00"}, + {"nov-early", "2026-11-02T08:00:00+08:00"}, + {"nov-late", "2026-11-30T08:00:00+08:00"}, + } { + entry := fixtureEntry(spec.id, "已有资料") + var wire map[string]any + if err := json.Unmarshal(entry.Payload, &wire); err != nil { + t.Fatal(err) + } + wire["asked_at"] = spec.askedAt + entry.Payload, _ = json.Marshal(wire) + rows = append(rows, entry) + } + job := claimMirrorJob(t, s, queue, "monthly-period-seed") + if err := s.HandleSync(ctx, *job, func(context.Context) (Source, error) { + return &fixtureSource{rows: rows}, nil + }); err != nil { + t.Fatal(err) + } + start, _ := time.Parse(time.RFC3339, "2026-11-01T00:00:00+08:00") + end, _ := time.Parse(time.RFC3339, "2026-12-01T00:00:00+08:00") + got, err := s.ReadMasterDashboard(ctx, dobotaiops.RecordQuery{ + Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}, + Granularity: dashboardGranularityMonth, + }) + if err != nil { + t.Fatal(err) + } + if got.Period == nil || got.Period.Kind != dashboardGranularityMonth || got.Period.Label != "2026-11" { + t.Fatalf("period = %+v", got.Period) + } + if !got.Period.PrevStart.Equal(start.AddDate(0, -1, 0)) || !got.Period.PrevEnd.Equal(start) { + t.Fatalf("previous range = %s..%s", got.Period.PrevStart, got.Period.PrevEnd) + } + if got.PeriodIssues == nil || *got.PeriodIssues != 2 { + t.Fatalf("period issues = %v, want 2", got.PeriodIssues) + } + if got.PrevPeriodIssues == nil || *got.PrevPeriodIssues != 1 { + t.Fatalf("previous period issues = %v, want 1", got.PrevPeriodIssues) + } + if got.TotalIssues != 3 { + t.Fatalf("cumulative total = %d, want 3 (everything before the range end)", got.TotalIssues) + } + if len(got.Daily) != 30 || got.Daily[0].Date != "2026-11-01" || got.Daily[29].Date != "2026-11-30" { + t.Fatalf("daily trend does not cover the whole month: %d points, first=%v", len(got.Daily), got.Daily[0]) + } + sum := 0 + for _, point := range got.Daily { + sum += point.Count + } + if sum != *got.PeriodIssues || got.NewThisWeek != *got.PeriodIssues { + t.Fatalf("daily sum=%d, new_this_week=%d, period=%d", sum, got.NewThisWeek, *got.PeriodIssues) + } + if got.PeriodQuality == nil || got.PeriodQuality.Records != got.Quality.Total { + t.Fatalf("period quality = %+v, quality total = %d", got.PeriodQuality, got.Quality.Total) + } +} + +// Omitting granularity must keep the weekly board exactly as before. +func TestWeeklyBoardKeepsLegacyPanelsWithoutGranularity(t *testing.T) { + pool := mirrorFixture(t) + ctx := context.Background() + s := NewStore(pool, "fixture-weekly-legacy") + queue := pg.NewStore(pool) + entry := fixtureEntry("legacy-week", "已有资料") + var wire map[string]any + _ = json.Unmarshal(entry.Payload, &wire) + wire["asked_at"] = "2026-11-30T08:00:00+08:00" + entry.Payload, _ = json.Marshal(wire) + job := claimMirrorJob(t, s, queue, "legacy-week-seed") + if err := s.HandleSync(ctx, *job, func(context.Context) (Source, error) { + return &fixtureSource{rows: []dobotaiops.MirrorRecord{entry}}, nil + }); err != nil { + t.Fatal(err) + } + start, _ := time.Parse(time.RFC3339, "2026-11-30T00:00:00+08:00") + end, _ := time.Parse(time.RFC3339, "2026-12-03T00:00:00+08:00") + got, err := s.ReadMasterDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}}) + if err != nil { + t.Fatal(err) + } + if got.Period != nil || got.PeriodIssues != nil || got.PeriodQuality != nil || got.Granularity != "" { + t.Fatalf("granularity leaked into the legacy board: %+v", got.Period) + } + if got.NewThisWeek != 1 || len(got.Daily) != 3 { + t.Fatalf("legacy weekly panels changed: new=%d daily=%d", got.NewThisWeek, len(got.Daily)) + } +} diff --git a/internal/qaopsmirror/dashboard_period_test.go b/internal/qaopsmirror/dashboard_period_test.go new file mode 100644 index 0000000..57a1c57 --- /dev/null +++ b/internal/qaopsmirror/dashboard_period_test.go @@ -0,0 +1,60 @@ +package qaopsmirror + +import ( + "testing" + "time" +) + +func mustShanghai(t *testing.T, value string) time.Time { + t.Helper() + parsed, err := time.Parse(time.RFC3339, value) + if err != nil { + t.Fatalf("parse %s: %v", value, err) + } + return parsed +} + +func TestDashboardPeriodResolution(t *testing.T) { + monthStart := mustShanghai(t, "2026-11-01T00:00:00+08:00") + monthEnd := mustShanghai(t, "2026-12-01T00:00:00+08:00") + month := dashboardPeriod(dashboardGranularityMonth, monthStart, monthEnd) + if month.Label != "2026-11" { + t.Fatalf("month label = %q, want 2026-11", month.Label) + } + if !month.PrevStart.Equal(mustShanghai(t, "2026-10-01T00:00:00+08:00")) || !month.PrevEnd.Equal(monthStart) { + t.Fatalf("month prev range = %s..%s", month.PrevStart, month.PrevEnd) + } + + weekStart := mustShanghai(t, "2026-11-30T00:00:00+08:00") + week := dashboardPeriod(dashboardGranularityWeek, weekStart, mustShanghai(t, "2026-12-07T00:00:00+08:00")) + if week.Label != "2026 第49周" { + t.Fatalf("week label = %q", week.Label) + } + if !week.PrevStart.Equal(mustShanghai(t, "2026-11-23T00:00:00+08:00")) { + t.Fatalf("week prev start = %s", week.PrevStart) + } + + day := dashboardPeriod(dashboardGranularityDay, weekStart, weekStart.AddDate(0, 0, 1)) + if day.Label != "2026-11-30" || !day.PrevStart.Equal(weekStart.AddDate(0, 0, -1)) { + t.Fatalf("day period = %+v", day) + } + + customEnd := mustShanghai(t, "2026-11-05T00:00:00+08:00") + custom := dashboardPeriod(dashboardGranularityCustom, monthStart, customEnd) + if !custom.PrevStart.Equal(mustShanghai(t, "2026-10-28T00:00:00+08:00")) || !custom.PrevEnd.Equal(monthStart) { + t.Fatalf("custom prev range = %s..%s", custom.PrevStart, custom.PrevEnd) + } +} + +func TestDashboardGranularityValidation(t *testing.T) { + for _, kind := range []string{"", "day", "week", "month", "custom"} { + if !validDashboardGranularity(kind) { + t.Fatalf("expected %q to be valid", kind) + } + } + for _, kind := range []string{"year", "Week", "quarter"} { + if validDashboardGranularity(kind) { + t.Fatalf("expected %q to be rejected", kind) + } + } +} diff --git a/internal/qaopsmirror/dashboard_store.go b/internal/qaopsmirror/dashboard_store.go index a1dfe1b..2b2d622 100644 --- a/internal/qaopsmirror/dashboard_store.go +++ b/internal/qaopsmirror/dashboard_store.go @@ -61,6 +61,9 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas if !s.valid() { return out, dobotaiops.ErrUnavailable } + if !validDashboardGranularity(q.Granularity) { + return out, dobotaiops.ErrInvalidQuery + } if q.Window.TenantKey != s.tenant || !utf8.ValidString(q.Keyword) || utf8.RuneCountInString(q.Keyword) > 200 || strings.ContainsRune(q.Keyword, 0) { return out, dobotaiops.ErrInvalidQuery } @@ -221,7 +224,11 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas } out.Quality = qaopsquality.Summarize(views) products, types, daily := map[string]int{}, map[string]int{}, map[string]int{} - for day := out.WeekStart; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) { + dailyFrom := out.WeekStart + if q.Granularity != "" { + dailyFrom = q.Window.Start + } + for day := dailyFrom; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) { daily[day.Format("2006-01-02")] = 0 } regionIndex := map[string]int{} @@ -237,10 +244,18 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas users[region.Name] = map[string]bool{} out.Regions = append(out.Regions, r) } + inPeriod := 0 for _, r := range records { - if !r.at.Before(out.WeekStart) { - out.NewThisWeek++ - daily[r.at.In(dashboardLocation).Format("2006-01-02")]++ + if q.Granularity == "" { + if !r.at.Before(out.WeekStart) { + out.NewThisWeek++ + daily[r.at.In(dashboardLocation).Format("2006-01-02")]++ + } + } else if !r.at.Before(q.Window.Start) { + inPeriod++ + if _, ok := daily[r.at.In(dashboardLocation).Format("2006-01-02")]; ok { + daily[r.at.In(dashboardLocation).Format("2006-01-02")]++ + } } if !r.at.Before(q.Window.Start) { v, ok := views[r.id] @@ -260,10 +275,24 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas } out.Products = dashboardCategories(products) out.IssueTypes = dashboardCategories(types) - for day := out.WeekStart; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) { + for day := dailyFrom; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) { date := day.Format("2006-01-02") out.Daily = append(out.Daily, DashboardDaily{Date: date, Count: daily[date]}) } + if q.Granularity != "" { + period := dashboardPeriod(q.Granularity, q.Window.Start, q.Window.End) + out.Granularity = q.Granularity + out.Period = &period + out.PeriodIssues = &inPeriod + // Keep the historical invariant "daily sums up to new_this_week" so old + // clients that only know this field still agree with the trend panel. + out.NewThisWeek = inPeriod + prev, err := s.dashboardPeriodIssues(ctx, tx, q, master, period.PrevStart, period.PrevEnd) + if err != nil { + return out, err + } + out.PrevPeriodIssues = &prev + } for i := range out.Regions { r := &out.Regions[i] if r.Users != nil { @@ -307,6 +336,10 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas 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 + if q.Granularity != "" { + periodRates := dashboardStrictQuality(timeline, q.Window.Start, q.Window.End) + out.PeriodQuality = &periodRates + } out.CalendarMonths = dashboardCalendarMonths(timeline, cutoff, calculated) } else { out.CumulativeWeeks = []DashboardCumulative{} diff --git a/web/src/QADashboard.test.tsx b/web/src/QADashboard.test.tsx index a71a4cc..cf70e17 100644 --- a/web/src/QADashboard.test.tsx +++ b/web/src/QADashboard.test.tsx @@ -33,7 +33,7 @@ describe('question dashboard projections', () => { const html = renderToStaticMarkup( ) - for (const title of ['问题总数', '本周新增', '覆盖率趋势', '正确率趋势', '产品问题排行', '导出看板图片']) + for (const title of ['累计总量', '本周新增', '覆盖率趋势', '正确率趋势', '产品问题排行', '导出看板图片']) expect(html).toContain(title) expect(html).not.toContain(' void + granularity?: DashboardGranularity }) { const [data, setData] = useState(null), [failure, setFailure] = useState(''), @@ -102,7 +108,11 @@ export function QADashboard({ setLoading(true) const refresh = async () => { try { - const next = await fetchQADashboard(liveDashboardQuery(query, new Date()), abort.signal) + const next = await fetchQADashboard( + liveDashboardQuery(query, new Date(), granularity), + abort.signal, + granularity + ) if (!abort.signal.aborted) { setData(next) setFailure('') @@ -121,7 +131,7 @@ export function QADashboard({ abort.abort() if (timer !== undefined) clearTimeout(timer) } - }, [query, revision]) + }, [query, revision, granularity]) return (
diff --git a/web/src/QADashboardDrawing.test.tsx b/web/src/QADashboardDrawing.test.tsx index a987d42..60d6d78 100644 --- a/web/src/QADashboardDrawing.test.tsx +++ b/web/src/QADashboardDrawing.test.tsx @@ -26,7 +26,7 @@ it('draws all eleven panels as a self-contained exportable SVG without HTML exec const html = renderToStaticMarkup() expect((html.match(/data-panel=/g) || []).length).toBe(11) for (const title of [ - '问题总数', + '累计总量', '本周新增', '覆盖率', '正确率', diff --git a/web/src/QADashboardDrawing.tsx b/web/src/QADashboardDrawing.tsx index 0500315..5ad03bf 100644 --- a/web/src/QADashboardDrawing.tsx +++ b/web/src/QADashboardDrawing.tsx @@ -544,7 +544,9 @@ export function QADashboardDrawing({ unit = (inner - gap * 3) / 4, week = currentQAWeek(new Date(data.week_start)), filterLines = wrap(data.keyword ? `关键词:${data.keyword}` : '', inner - 16, 11), - 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)} 月累计`, + heading = data.period + ? `${data.period.label} · 全部指标按所选范围统计 · 区域统计 ${new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7)} 月累计` + : `${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) ), @@ -633,13 +635,13 @@ export function QADashboardDrawing({ background: '#fff', }} > - {`问题统计看板 · ${week.year}年第${week.week}周`} + {`问题统计看板 · ${data.period ? data.period.label : `${week.year}年第${week.week}周`}`} 问题统计看板 - {week.year} · W{String(week.week).padStart(2, '0')} + {data.period ? data.period.label : `${week.year} · W${String(week.week).padStart(2, '0')}`} {headingLines.map((row, index) => ( @@ -649,37 +651,45 @@ export function QADashboardDrawing({ ) : null} diff --git a/web/src/QAOperations.tsx b/web/src/QAOperations.tsx index eb45b6c..4fb59ba 100644 --- a/web/src/QAOperations.tsx +++ b/web/src/QAOperations.tsx @@ -7,6 +7,7 @@ import './qaOps.css' import { ledgerWindow, ledgerCellPreview } from './qaLedgerRendering' import { QARegionalStatistics } from './QADepartmentStatistics' import { QADashboard } from './QADashboard' +import type { DashboardGranularity } from './qaDashboardData' import { QAWeekly } from './QAWeekly' import { QAInlineFields } from './QAInlineFields' import { QAHeaderFieldFilter, useQAFieldFilterOptions } from './QAFieldFilters' @@ -410,10 +411,37 @@ export function QAOperationsView(props: ViewProps) { ) } +type QARangeKind = 'week' | 'month' | 'custom' +const beijingInput = (now = new Date()) => new Date(now.getTime() + 8 * 3_600_000).toISOString().slice(0, 16) +function monthInputValue(now = new Date()) { + return beijingInput(now).slice(0, 7) +} +function monthQueryRange(month: string, now = new Date()) { + const [year, monthNumber] = month.split('-').map(Number) + if (!Number.isInteger(year) || !Number.isInteger(monthNumber) || monthNumber < 1 || monthNumber > 12) + throw new Error('月份无效') + const start = `${month}-01T00:00` + const nextYear = monthNumber === 12 ? year + 1 : year + const nextMonth = monthNumber === 12 ? 1 : monthNumber + 1 + const end = `${nextYear}-${String(nextMonth).padStart(2, '0')}-01T00:00` + const current = beijingInput(now) + const bounded = end > current ? current : end + if (bounded <= start) throw new Error('该月份尚未开始,请选择已开始的时间范围') + return { start, end: bounded } +} + function initialDraft() { const current = currentQAWeek() const { year, week, start, end } = qaWeekQueryRange(current.year, current.week) - return { year, week: week as number | null, start, end, keyword: '' } + return { + kind: 'week' as QARangeKind, + year, + week: week as number | null, + month: monthInputValue(), + start, + end, + keyword: '', + } } export function QAOperations() { @@ -425,6 +453,7 @@ export function QAOperations() { const auth = useOptionalAuth() const canRead = auth?.identity?.role === 'admin' const [draft, setDraft] = useState(initialDraft) + const [granularity, setGranularity] = useState('week') const [filters, setFilters] = useState>({}) const [exporting, setExporting] = useState(false), [exportError, setExportError] = useState('') @@ -452,6 +481,7 @@ export function QAOperations() { useEffect(() => { if (!canRead || query) return + setGranularity(draft.kind) setQuery({ start: qaDateTimeToISO(draft.start), end: qaDateTimeToISO(draft.end), @@ -551,6 +581,7 @@ export function QAOperations() { end = qaDateTimeToISO(draft.end) if (!(Date.parse(start) < Date.parse(end))) throw new Error('开始时间必须早于结束时间') if (Date.parse(start) >= Date.now()) throw new Error('所选周或时间尚未开始,请选择已开始的时间范围') + setGranularity(draft.kind) setQuery({ start, end, keyword: draft.keyword, cursor: '', filters: { ...filters } }) } catch (reason) { setError(reason instanceof Error ? reason.message : '时间格式无效') @@ -633,33 +664,83 @@ export function QAOperations() { <> {mirrorChanged ?

数据已更新,关闭详情后刷新。

: null}
- { - const current = initialDraft() - setDraft({ ...current, keyword: draft.keyword }) - setQuery({ - start: qaDateTimeToISO(current.start), - end: qaDateTimeToISO(current.end), - keyword: draft.keyword, - cursor: '', - filters: { ...filters }, - }) - }} - onChange={(year, week) => - setDraft((old) => - week === null ? { ...old, year, week } : { ...old, ...qaWeekQueryRange(year, week) } - ) - } - /> + + {draft.kind === 'week' ? ( + { + const current = initialDraft() + setDraft({ ...current, keyword: draft.keyword }) + setQuery({ + start: qaDateTimeToISO(current.start), + end: qaDateTimeToISO(current.end), + keyword: draft.keyword, + cursor: '', + filters: { ...filters }, + }) + }} + onChange={(year, week) => + setDraft((old) => + week === null ? { ...old, year, week } : { ...old, ...qaWeekQueryRange(year, week) } + ) + } + /> + ) : null} + {draft.kind === 'month' ? ( + + ) : null}