- 请求新增 granularity,看板所有区块统一按所选区间统计(累计量单独保留) - 覆盖率/正确率新增区间严格口径 period_quality,趋势图覆盖整个区间 - 新增环比上一区间条数;卡片标题与统计口径随区间自动生成 - 未传 granularity 时保持原周看板行为不变 (cherry picked from commit fbb1d1d819e7b85ef849e3a1e4ef209707a67b22)
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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{}
|
||||
|
||||
Reference in New Issue
Block a user