package qaopsmirror import ( "context" "encoding/json" "knowledge-governance/internal/qaopsorg" "testing" "time" ) func TestDepartmentStatisticsNaturalWeekBoundaryAndCacheIsolation(t *testing.T) { p := mirrorFixture(t) s := NewStore(p, "fixture-department-natural-week") now, _ := time.Parse(time.RFC3339, "2026-10-21T11:00:00+08:00") ctx := context.Background() dir := qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "root", Name: "Fixture center"}, {ID: "child", ParentID: "root", Name: "Fixture department"}}, People: []qaopsorg.Person{{ID: "p1", Name: "Fixture person", DepartmentIDs: []string{"root", "child"}}}} if _, err := qaopsorg.NewStore(p, s.tenant).ReplaceDirectory(ctx, qaopsorg.Import{Source: "weekly_report_snapshot", SyncedAt: time.Now(), Complete: true, Directory: dir}); err != nil { t.Fatal(err) } for i, stamp := range []string{"2026-10-11T23:59:59+08:00", "2026-10-12T00:00:00+08:00", "2026-10-18T23:59:59+08:00", "2026-10-19T00:00:00+08:00"} { _, err := p.Exec(ctx, `INSERT INTO qa_ops_master_records(tenant_key,id,event_key,origin,asked_at,question,status,identity,quality_hash,payload)VALUES($1,$2,repeat('a',64),'dobotai_2_0',$3,'non-business boundary fixture','succeeded','{"staff_id":"p1"}',repeat('b',64),jsonb_build_object('id',$2::text))`, s.tenant, "boundary-"+time.Date(2000, 1, i+1, 0, 0, 0, 0, time.UTC).Format("02"), stamp) if err != nil { t.Fatal(err) } } read := func(week string) DepartmentStatisticsResult { var q DepartmentStatisticsQuery raw, _ := json.Marshal(map[string]string{"period": "week", "week": week}) _ = json.Unmarshal(raw, &q) deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { r, err := s.ReadDepartmentStatistics(ctx, q, now) if err != nil { t.Fatal(err) } if r.State == "ready" { return r } time.Sleep(time.Millisecond) } t.Fatal("background natural week did not finish") return DepartmentStatisticsResult{} } first, second := read("2026-W42"), read("2026-W43") if first.CacheKey == second.CacheKey || first.Snapshot.TotalVisits != 2 || second.Snapshot.TotalVisits != 1 { t.Fatalf("week boundaries/cache contaminated: first=%+v second=%+v", first, second) } for _, r := range first.Snapshot.Rows { if r.Visits != 2 || r.Visitors != 1 || r.TotalPeople != 1 { t.Fatalf("current branch person was double-counted: %+v", r) } } if repeated := read("2026-W42"); !repeated.CacheHit || repeated.Snapshot.GeneratedAt != first.Snapshot.GeneratedAt { t.Fatal("same natural week was not cached") } }