feat(qaops): 增加部门树区域统计与父子联选
build / build (push) Successful in 1m5s

区域配置入口改为区域统计,五列表按当前通讯录整支人员去重;调岗依当前归属、零分母未知、最近真实提问时间和父行收起不重算。仅读治理正式总表,后台单并发/请求合并/60秒缓存,目录与配置版本隔离,客户端失败不伪零。

保留区域自定义目录与预览/双版本锁保存,父部门勾选联选全后代,取消子支清除祖先整支选择,避免隐式覆盖未选子级;允许删除无引用区域,已有引用不静默孤立。统计页与设置共享选择,统计支持累计与北京时间自然月;不新增迁移,不改DobotAI生产、代理、原问答、历史趋势或已有AI任务。

验证已执行:完整make verify退出0,705 Go/340前端通过、120项声明的可选集成跳过且必需0跳过;镜像全量隔离PG race退出0;新增去重/调岗/空分母、后台缓存/并发、HTTP授权/严格请求、真PG目录与配置失效、树选择/收起、五列与删除保护均先红后绿。旧导航测试按新名称更新后全量通过。上线前治理库备份与真实恢复72表/29张QA内容哈希一致,匹配独立主密钥受限备份。

当前尚待精确SHA CI、同镜像真实数据浏览器与正式读回,不把源码验证称为已上线。公司真实区域映射不在本轮擅改;只在隔离库验证保存。
This commit is contained in:
姚章浩
2026-10-19 19:01:36 +08:00
parent a9870beade
commit 4a2b2b7d84
25 changed files with 1642 additions and 20 deletions
@@ -0,0 +1,99 @@
package qaopsmirror
import (
"context"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qaopsorg"
"sync"
"time"
)
type DepartmentStatisticsQuery struct {
Period string `json:"period"`
Month string `json:"month,omitempty"`
}
type DepartmentStatisticsSnapshot struct {
Regions []qaopsorg.RegionDefinition `json:"regions"`
qaopsorg.DepartmentStatistics
Organization dobotaiops.OrganizationVersion `json:"organization"`
Period string `json:"period"`
Month string `json:"month"`
Start *time.Time `json:"start"`
End time.Time `json:"end"`
GeneratedAt time.Time `json:"generated_at"`
ExpiresAt time.Time `json:"expires_at"`
}
type DepartmentStatisticsResult struct {
CacheKey string `json:"cache_key"`
State string `json:"state"`
CacheHit bool `json:"cache_hit"`
RetryAfter int `json:"retry_after"`
Snapshot *DepartmentStatisticsSnapshot `json:"snapshot"`
}
type departmentStatisticsEntry struct {
snapshot *DepartmentStatisticsSnapshot
err error
done bool
expires time.Time
}
type departmentStatisticsCache struct {
mu sync.Mutex
entries map[string]*departmentStatisticsEntry
slots chan struct{}
}
func (c *departmentStatisticsCache) get(key string, now time.Time, load func(context.Context) (DepartmentStatisticsSnapshot, error)) (DepartmentStatisticsResult, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.entries == nil {
c.entries = map[string]*departmentStatisticsEntry{}
c.slots = make(chan struct{}, 1)
}
if entry := c.entries[key]; entry != nil && (!entry.done || now.Before(entry.expires)) {
if entry.err != nil {
return DepartmentStatisticsResult{}, dobotaiops.ErrUnavailable
}
if entry.done {
return DepartmentStatisticsResult{State: "ready", CacheKey: key, CacheHit: true, Snapshot: entry.snapshot}, nil
}
return DepartmentStatisticsResult{State: "pending", CacheKey: key, RetryAfter: 1}, nil
}
for k, v := range c.entries {
if v.done && !now.Before(v.expires) {
delete(c.entries, k)
}
}
if len(c.entries) >= 32 {
return DepartmentStatisticsResult{}, dobotaiops.ErrUnavailable
}
entry := &departmentStatisticsEntry{}
c.entries[key] = entry
go func() {
started := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
var data DepartmentStatisticsSnapshot
var err error
select {
case c.slots <- struct{}{}:
data, err = load(ctx)
<-c.slots
case <-ctx.Done():
err = ctx.Err()
}
finished := now.Add(time.Since(started))
data.GeneratedAt = finished
data.ExpiresAt = finished.Add(time.Minute)
c.mu.Lock()
defer c.mu.Unlock()
entry.done = true
entry.err = err
entry.expires = data.ExpiresAt
if err != nil {
entry.expires = finished.Add(5 * time.Second)
} else {
entry.snapshot = &data
}
}()
return DepartmentStatisticsResult{State: "pending", CacheKey: key, RetryAfter: 1}, nil
}
@@ -0,0 +1,71 @@
package qaopsmirror
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestDepartmentStatisticsCacheIsBackgroundSingleFlightAndExpires(t *testing.T) {
cache := &departmentStatisticsCache{}
started := make(chan struct{})
release := make(chan struct{})
var calls atomic.Int64
now := time.Now()
load := func(ctx context.Context) (DepartmentStatisticsSnapshot, error) {
if calls.Add(1) == 1 {
close(started)
}
select {
case <-release:
case <-ctx.Done():
return DepartmentStatisticsSnapshot{}, ctx.Err()
}
return DepartmentStatisticsSnapshot{Period: "all"}, nil
}
begin := time.Now()
r, e := cache.get("tenant/directory-v1/revision-v1/all", now, load)
if e != nil || r.State != "pending" || time.Since(begin) > 100*time.Millisecond {
t.Fatal("first view performed/blocked aggregation instead of scheduling it", e, r.State)
}
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("background aggregator did not run")
}
var wg sync.WaitGroup
for i := 0; i < 32; i++ {
wg.Add(1)
go func() {
defer wg.Done()
r, e := cache.get("tenant/directory-v1/revision-v1/all", now, load)
if e != nil || r.State != "pending" {
t.Error("concurrent read did not join background work")
}
}()
}
wg.Wait()
if calls.Load() != 1 {
t.Fatal("identical requests spawned duplicate aggregation")
}
close(release)
for deadline := time.Now().Add(time.Second); ; {
r, e = cache.get("tenant/directory-v1/revision-v1/all", now, load)
if r.State == "ready" {
break
}
if time.Now().After(deadline) {
t.Fatal("background result never published")
}
time.Sleep(time.Millisecond)
}
if e != nil || !r.CacheHit || r.Snapshot == nil || calls.Load() != 1 {
t.Fatal("result cache was not reused")
}
r, e = cache.get("tenant/directory-v1/revision-v1/all", now.Add(61*time.Second), load)
if e != nil || r.State != "pending" {
t.Fatal("expired result was served as fresh")
}
}
@@ -0,0 +1,100 @@
package qaopsmirror
import (
"context"
"encoding/json"
"knowledge-governance/internal/qaopsorg"
"testing"
"time"
)
func TestDepartmentStatisticsReadsMasterAndInvalidatesCurrentDirectory(t *testing.T) {
p := mirrorFixture(t)
s := NewStore(p, "fixture-department-statistics")
reader, ok := any(s).(interface {
ReadDepartmentStatistics(context.Context, DepartmentStatisticsQuery, time.Time) (DepartmentStatisticsResult, error)
})
if !ok {
t.Fatal("master-backed asynchronous department statistics reader is missing")
}
ctx := context.Background()
org := qaopsorg.NewStore(p, s.tenant)
directory := qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "root", Name: "Fixture Root"}, {ID: "child", ParentID: "root", Name: "Fixture Child"}, {ID: "other", ParentID: "root", Name: "Fixture Other"}, {ID: "empty", ParentID: "root", Name: "Fixture Empty"}}, People: []qaopsorg.Person{{ID: "person", UnionID: "union-person", DepartmentIDs: []string{"root", "child"}}, {ID: "second", DepartmentIDs: []string{"other"}}}}
state, e := org.ReplaceDirectory(ctx, qaopsorg.Import{Source: "weekly_report_snapshot", SyncedAt: time.Now(), Complete: true, Directory: directory})
if e != nil {
t.Fatal(e)
}
for i, identity := range []map[string]string{{"staff_id": "person"}, {"union_id": "union-person"}, {"staff_id": "second"}} {
id := []string{"one", "two", "three"}[i]
at := "2026-10-05T01:00:00+08:00"
wire := map[string]any{"id": id, "asked_at": at, "question": "Fixture question " + id, "answer": "Fixture nonbusiness answer", "status": "succeeded", "asker": "Fixture display", "trigger_person": "", "department": "Former department must not decide current attribution", "references": []any{}, "media": []any{}}
raw, _ := json.Marshal(wire)
actor, _ := json.Marshal(identity)
_, e = 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,'fixture','succeeded',$4,repeat('b',64),$5)`, s.tenant, id, at, string(actor), string(raw))
if e != nil {
t.Fatal(e)
}
}
now := time.Now()
query := DepartmentStatisticsQuery{Period: "all"}
wait := func() DepartmentStatisticsResult {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
for {
r, e := reader.ReadDepartmentStatistics(ctx, query, now)
if e != nil {
t.Fatal(e)
}
if r.State == "ready" {
return r
}
if time.Now().After(deadline) {
t.Fatal("statistics did not finish in the background")
}
time.Sleep(5 * time.Millisecond)
}
}
cctx, cancel := context.WithCancel(ctx)
first, e := reader.ReadDepartmentStatistics(cctx, query, now)
cancel()
if e != nil || first.State != "pending" {
t.Fatal("first request must enqueue background aggregation", e)
}
ready := wait()
if ready.Snapshot.TotalVisits != 3 || ready.Snapshot.TotalPeople != 2 || ready.Snapshot.Organization.DirectoryID != state.DirectoryID {
t.Fatal("statistics used mirror-only records or wrong roster")
}
rows := map[string]qaopsorg.DepartmentStatistic{}
for _, r := range ready.Snapshot.Rows {
rows[r.ID] = r
}
if rows["root"].Visitors != 2 || rows["root"].Visits != 3 || rows["child"].Visitors != 1 || rows["child"].Visits != 2 || rows["empty"].Ratio != nil {
t.Fatal("subtree/alias/empty-denominator contract lost")
}
again, e := reader.ReadDepartmentStatistics(ctx, query, now.Add(time.Second))
if e != nil || !again.CacheHit || again.Snapshot.GeneratedAt != ready.Snapshot.GeneratedAt {
t.Fatal("same condition was recomputed within 60 seconds")
}
directory.People[0].DepartmentIDs = []string{"other"}
state, e = org.ReplaceDirectory(ctx, qaopsorg.Import{Source: "weekly_report_snapshot", SyncedAt: time.Now(), Complete: true, Directory: directory})
if e != nil {
t.Fatal(e)
}
moved := wait()
if moved.CacheKey == ready.CacheKey || moved.Snapshot.Organization.DirectoryID != state.DirectoryID {
t.Fatal("directory changes did not invalidate cache")
}
for _, r := range moved.Snapshot.Rows {
if r.ID == "child" && (r.TotalPeople != 0 || r.Visitors != 0 || r.Ratio != nil) {
t.Fatal("transferred person remained in former department")
}
}
_, e = org.SaveRules(ctx, qaopsorg.SaveRequest{DirectoryID: state.DirectoryID, BaseRevision: state.RevisionID, Rules: []qaopsorg.Rule{{DepartmentID: "other", Region: "APAC"}}}, "fixture-admin")
if e != nil {
t.Fatal(e)
}
updated := wait()
if updated.CacheKey == moved.CacheKey {
t.Fatal("saved regional configuration was hidden behind stale cached results")
}
}
@@ -0,0 +1,107 @@
package qaopsmirror
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qaopsorg"
"time"
)
func (q DepartmentStatisticsQuery) Bounds(now time.Time) (*time.Time, time.Time, error) {
if q.Period == "all" && q.Month == "" {
return nil, now, nil
}
if q.Period != "month" {
return nil, time.Time{}, dobotaiops.ErrInvalidQuery
}
zone := time.FixedZone("Asia/Shanghai", 8*3600)
start, err := time.ParseInLocation("2006-01", q.Month, zone)
if err != nil || start.Year() < 2000 || start.After(now) {
return nil, time.Time{}, dobotaiops.ErrInvalidQuery
}
end := start.AddDate(0, 1, 0)
if end.After(now) {
end = now
}
return &start, end, nil
}
func (s *Store) ReadDepartmentStatistics(ctx context.Context, q DepartmentStatisticsQuery, now time.Time) (DepartmentStatisticsResult, error) {
if !s.valid() {
return DepartmentStatisticsResult{}, dobotaiops.ErrUnavailable
}
start, end, err := q.Bounds(now)
if err != nil {
return DepartmentStatisticsResult{}, err
}
var directory, revision string
err = s.pool.QueryRow(ctx, `SELECT directory_id,COALESCE(revision_id,'')FROM qa_ops_organization_state WHERE tenant_key=$1`, s.tenant).Scan(&directory, &revision)
if err != nil || directory == "" {
return DepartmentStatisticsResult{}, dobotaiops.ErrUnavailable
}
raw, _ := json.Marshal([]string{s.tenant, directory, revision, q.Period, q.Month})
digest := sha256.Sum256(raw)
key := hex.EncodeToString(digest[:])
return s.departmentStats.get(key, now, func(background context.Context) (DepartmentStatisticsSnapshot, error) {
return s.loadDepartmentStatistics(background, q, start, end, directory, revision)
})
}
func (s *Store) loadDepartmentStatistics(ctx context.Context, q DepartmentStatisticsQuery, start *time.Time, end time.Time, directory, revision string) (DepartmentStatisticsSnapshot, error) {
out := DepartmentStatisticsSnapshot{Period: q.Period, Month: q.Month, Start: start, End: end}
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
if err != nil {
return out, dobotaiops.ErrUnavailable
}
defer tx.Rollback(context.Background())
if _, err = tx.Exec(ctx, `SET LOCAL statement_timeout='15s'`); err != nil {
return out, dobotaiops.ErrUnavailable
}
p, err := qaopsorg.NewStore(s.pool, s.tenant).GetAttributionInTx(ctx, tx)
if err != nil || p.Metadata.State != "ready" || p.Metadata.DirectoryID != directory || p.Metadata.RevisionID != revision {
return out, dobotaiops.ErrUnavailable
}
out.Regions = p.Metadata.RegionDefinitions()
out.Organization = dobotaiops.OrganizationVersion{State: p.Metadata.State, DirectoryID: p.Metadata.DirectoryID, DirectorySource: p.Metadata.DirectorySource, SyncedAt: p.Metadata.DirectorySyncedAt, RevisionID: p.Metadata.RevisionID, Basis: "current_directory", RegionNames: p.Metadata.RegionLabels()}
rows, err := tx.Query(ctx, `SELECT identity::text,COALESCE(payload->>'asker',''),COALESCE(NULLIF(local_fields->>'trigger_person',''),payload->>'trigger_person',''),count(*),max(asked_at),min(asked_at) FROM qa_ops_master_records WHERE tenant_key=$1 AND($2::timestamptz IS NULL OR asked_at>=$2)AND asked_at<$3 GROUP BY identity,COALESCE(payload->>'asker',''),COALESCE(NULLIF(local_fields->>'trigger_person',''),payload->>'trigger_person','') LIMIT 100001`, s.tenant, start, end)
if err != nil {
return out, dobotaiops.ErrUnavailable
}
activity := []qaopsorg.DepartmentActivity{}
var earliest *time.Time
for rows.Next() {
var a qaopsorg.DepartmentActivity
var raw string
var identity dobotaiops.ActorIdentity
var first time.Time
if rows.Scan(&raw, &a.Asker, &a.Trigger, &a.Visits, &a.LastAskedAt, &first) != nil || json.Unmarshal([]byte(raw), &identity) != nil {
rows.Close()
return out, dobotaiops.ErrUnavailable
}
a.StaffID = identity.StaffID
a.UnionID = identity.UnionID
activity = append(activity, a)
if earliest == nil || first.Before(*earliest) {
at := first
earliest = &at
}
}
err = rows.Err()
rows.Close()
if err != nil || len(activity) > 100000 {
return out, dobotaiops.ErrUnavailable
}
out.DepartmentStatistics, err = qaopsorg.AggregateDepartmentStatistics(p, activity)
if err != nil {
return out, dobotaiops.ErrUnavailable
}
if q.Period == "all" {
out.Start = earliest
}
if tx.Commit(ctx) != nil {
return out, dobotaiops.ErrUnavailable
}
return out, nil
}
+5 -4
View File
@@ -17,10 +17,11 @@ const Interval = 5 * time.Minute
const localBaseSQL = `WITH records AS (SELECT id,asked_at,question,status,identity,quality_hash,payload FROM qa_ops_mirror_records WHERE tenant_key=$1)`
type Store struct {
pool *pgxpool.Pool
tenant string
mu sync.RWMutex
safety dobotaiops.SourceSafety
pool *pgxpool.Pool
tenant string
mu sync.RWMutex
safety dobotaiops.SourceSafety
departmentStats departmentStatisticsCache
}
func NewStore(pool *pgxpool.Pool, tenant string) *Store { return &Store{pool: pool, tenant: tenant} }