diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9c46734..fdc45ad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -76,6 +76,18 @@
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯,
> 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。
+## 开发快照 snapshot/v0.1.38 - 2026-10-19
+
+### Added
+
+- 区域统计新增可展开部门树:部门、访问人数、访问比例、访问次数、最近提问时间五列,访问人数附当前通讯录总人数;整支含自身和全部子部门,按稳定人员身份去重,调岗依当前归属,零分母显示“—”,收起不重算数字。
+- 统计仅读独立治理总表中的提问事件,支持累计与北京时间自然月;单并发后台聚合、请求合并和60秒缓存,目录或区域配置版本变化立即隔离旧缓存;加载/失败不伪装零数据,不占用代理转发链路。
+
+### Changed
+
+- 原“区域配置”入口改为“区域统计”,区域设置保留自定义区域新增/改名、未使用区域删除、部门映射预览与双版本锁保存;勾选父部门联选全部后代,取消子支时解除祖先整支选中,防止未选部门被父级新规则误覆盖。
+- 统计与区域设置共享选择;搜索、按区域查看及展开收起只改变可见行,既有总表、原始问答、历史趋势、模型任务与生产数据不修改。
+
## 开发快照 snapshot/v0.1.37 - 2026-10-19
### Added
diff --git a/api/openapi.yaml b/api/openapi.yaml
index 75844cd..8eae267 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -44,6 +44,66 @@
}
],
"paths": {
+ "/api/v1/qa-ops/departments/statistics": {
+ "post": {
+ "operationId": "qaDepartmentStatistics",
+ "summary": "部门树访问统计,当前通讯录整支人员去重",
+ "description": "仅独立治理总表,不读取生产或更改原问答;后台单聚合并发,响应202或60秒缓存结果。当前目录和区域配置版本加入缓存键;父行包含自身及全部后代,人员按当前稳定身份去重,调岗归当前部门;零分母比例为null,最近提问时间来自真实事件。访问指已入总表的提问事件,不含未记录的网页浏览。管理员同源只读POST,操作头qa-department-statistics。",
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "period"
+ ],
+ "properties": {
+ "period": {
+ "type": "string",
+ "enum": [
+ "all",
+ "month"
+ ]
+ },
+ "month": {
+ "type": "string",
+ "pattern": "^[0-9]{4}-[0-9]{2}$"
+ }
+ }
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "$ref": "#/components/responses/Envelope"
+ },
+ "400": {
+ "$ref": "#/components/responses/BadRequest"
+ },
+ "401": {
+ "description": "需要登录"
+ },
+ "403": {
+ "description": "仅管理员同源读取"
+ },
+ "409": {
+ "description": "质量输入指纹变化,拒绝混合数据"
+ },
+ "500": {
+ "$ref": "#/components/responses/InternalError"
+ },
+ "503": {
+ "description": "本地副本或一致性投影不可用,不返回伪零"
+ },
+ "202": {
+ "description": "后台聚合中;同条件合并单次执行,请按Retry-After轮询,不返回虚构零数据"
+ }
+ }
+ }
+ },
"/api/v1/qa-ops/ai/settings": {"get": {"operationId": "getQAAISettings", "tags": ["QA operations"], "summary": "读取独立模型配置的安全状态,不返回密钥", "description": "管理员会话限定、固定治理租户、禁止共享缓存;不修改DobotAI源数据库。", "responses": {"200": {"description": "成功;返回实际持久化状态,不将进度100%当成全成功", "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"data": {"$ref": "#/components/schemas/QAAISafeSettings"}}, "required": ["data"]}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员;写操作要求同源与明确意图"}, "409": {"description": "版本、范围或操作收据冲突,未覆盖现有结论"}, "422": {"description": "供应商明确拒绝或结构不合格,不伪造结果"}, "500": {"$ref": "#/components/responses/InternalError"}, "503": {"description": "存储、密钥或执行配置不可用;不返回伪零"}}}, "post": {"operationId": "saveQAAISettings", "tags": ["QA operations"], "summary": "验证并加密保存独立模型配置;不启动历史或自动任务", "description": "管理员会话限定、固定治理租户、禁止共享缓存;不修改DobotAI源数据库。", "responses": {"200": {"description": "成功;返回实际持久化状态,不将进度100%当成全成功", "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"data": {"$ref": "#/components/schemas/QAAISafeSettings"}}, "required": ["data"]}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员;写操作要求同源与明确意图"}, "409": {"description": "版本、范围或操作收据冲突,未覆盖现有结论"}, "422": {"description": "供应商明确拒绝或结构不合格,不伪造结果"}, "500": {"$ref": "#/components/responses/InternalError"}, "503": {"description": "存储、密钥或执行配置不可用;不返回伪零"}}, "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"const": "qa-ai"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/QAAISaveSettings"}}}}}},
"/api/v1/qa-ops/ai/settings/test": {"post": {"operationId": "testQAAISettings", "tags": ["QA operations"], "summary": "发送最小非公司数据真实模型探测;不保存配置", "description": "管理员会话限定、固定治理租户、禁止共享缓存;不修改DobotAI源数据库。", "responses": {"200": {"description": "成功;返回实际持久化状态,不将进度100%当成全成功", "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"data": {"$ref": "#/components/schemas/QAAISafeSettings"}}, "required": ["data"]}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员;写操作要求同源与明确意图"}, "409": {"description": "版本、范围或操作收据冲突,未覆盖现有结论"}, "422": {"description": "供应商明确拒绝或结构不合格,不伪造结果"}, "500": {"$ref": "#/components/responses/InternalError"}, "503": {"description": "存储、密钥或执行配置不可用;不返回伪零"}}, "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"const": "qa-ai"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/QAAISaveSettings"}}}}}},
"/api/v1/qa-ops/ai/automation": {"post": {"operationId": "setQAAIAutomation", "tags": ["QA operations"], "summary": "按任务启停增量;首次排除历史,关闭停止新增与未开始任务", "description": "管理员会话限定、固定治理租户、禁止共享缓存;不修改DobotAI源数据库。", "responses": {"200": {"description": "成功;返回实际持久化状态,不将进度100%当成全成功", "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"data": {"$ref": "#/components/schemas/QAAISafeSettings"}}, "required": ["data"]}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员;写操作要求同源与明确意图"}, "409": {"description": "版本、范围或操作收据冲突,未覆盖现有结论"}, "422": {"description": "供应商明确拒绝或结构不合格,不伪造结果"}, "500": {"$ref": "#/components/responses/InternalError"}, "503": {"description": "存储、密钥或执行配置不可用;不返回伪零"}}, "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"const": "qa-ai"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"kind": {"type": "string", "enum": ["evaluation", "translation"]}, "enabled": {"type": "boolean"}}, "required": ["kind", "enabled"]}}}}}},
diff --git a/internal/httpapi/qa_department_statistics.go b/internal/httpapi/qa_department_statistics.go
new file mode 100644
index 0000000..7dd0a20
--- /dev/null
+++ b/internal/httpapi/qa_department_statistics.go
@@ -0,0 +1,45 @@
+package httpapi
+
+import (
+ "context"
+ "knowledge-governance/internal/dobotaiops"
+ "knowledge-governance/internal/qaopsmirror"
+ "net/http"
+ "time"
+)
+
+type departmentStatisticsReader interface {
+ ReadDepartmentStatistics(context.Context, qaopsmirror.DepartmentStatisticsQuery, time.Time) (qaopsmirror.DepartmentStatisticsResult, error)
+}
+
+func qaDepartmentStatistics(w http.ResponseWriter, r *http.Request, c Config) {
+ if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-department-statistics") {
+ return
+ }
+ var q qaopsmirror.DepartmentStatisticsQuery
+ if r.URL.RawQuery != "" || decodeQualityJSON(w, r, &q, "period") != nil {
+ qaOpsError(w, dobotaiops.ErrInvalidQuery)
+ return
+ }
+ now := c.Now()
+ if _, _, e := q.Bounds(now); e != nil {
+ qaOpsError(w, e)
+ return
+ }
+ reader, ok := c.QAOps.(departmentStatisticsReader)
+ if !ok || c.QAOpsTenantKey == "" {
+ qaOpsError(w, dobotaiops.ErrUnavailable)
+ return
+ }
+ data, e := reader.ReadDepartmentStatistics(r.Context(), q, now)
+ if e != nil {
+ qaOpsError(w, e)
+ return
+ }
+ status := http.StatusOK
+ if data.State == "pending" {
+ status = http.StatusAccepted
+ w.Header().Set("Retry-After", "1")
+ }
+ writeJSON(w, status, map[string]any{"data": data})
+}
diff --git a/internal/httpapi/qa_department_statistics_test.go b/internal/httpapi/qa_department_statistics_test.go
new file mode 100644
index 0000000..6a7a794
--- /dev/null
+++ b/internal/httpapi/qa_department_statistics_test.go
@@ -0,0 +1,69 @@
+package httpapi
+
+import (
+ "context"
+ "knowledge-governance/internal/qaopsmirror"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+type departmentStatisticsFixture struct {
+ masterFixtureReader
+ reads int
+}
+
+func (f *departmentStatisticsFixture) ReadDepartmentStatistics(context.Context, qaopsmirror.DepartmentStatisticsQuery, time.Time) (qaopsmirror.DepartmentStatisticsResult, error) {
+ f.reads++
+ return qaopsmirror.DepartmentStatisticsResult{State: "pending", RetryAfter: 1}, nil
+}
+func TestDepartmentStatisticsRouteIsAsynchronousStrictAndAdminOnly(t *testing.T) {
+ auth := newFakeAuthStore()
+ auth.sessions["dept-fixture-admin"] = "usr-boss"
+ auth.sessions["dept-fixture-viewer"] = "usr-eye"
+ reader := &departmentStatisticsFixture{}
+ h, e := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: reader, QAOpsTenantKey: "fixture-tenant", Now: func() time.Time { return time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC) }})
+ if e != nil {
+ t.Fatal(e)
+ }
+ for _, c := range []struct {
+ body, token, intent, site string
+ want int
+ }{
+ {`{"period":"all"}`, "dept-fixture-admin", "qa-department-statistics", "", 202},
+ {`{"period":"month","month":"2026-10"}`, "dept-fixture-admin", "qa-department-statistics", "same-origin", 202},
+ {`{"period":"all"}`, "", "qa-department-statistics", "", 401},
+ {`{"period":"all"}`, "dept-fixture-viewer", "qa-department-statistics", "", 403},
+ {`{"period":"all"}`, "dept-fixture-admin", "", "", 403},
+ {`{"period":"all"}`, "dept-fixture-admin", "qa-department-statistics", "cross-site", 403},
+ {`{"period":"all","tenant":"other"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
+ {`{"period":"all","period":"all"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
+ {`null`, "dept-fixture-admin", "qa-department-statistics", "", 400},
+ {`{"period":"month","month":"2027-01"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
+ {`{"period":"all","month":"2026-10"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
+ } {
+ r := httptest.NewRequest("POST", "/api/v1/qa-ops/departments/statistics", strings.NewReader(c.body))
+ if c.token != "" {
+ r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: c.token})
+ }
+ if c.intent != "" {
+ r.Header.Set("X-Governance-Action", c.intent)
+ }
+ if c.site != "" {
+ r.Header.Set("Sec-Fetch-Site", c.site)
+ }
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, r)
+ if w.Code != c.want {
+ t.Fatalf("department statistics got %d want %d", w.Code, c.want)
+ }
+ if w.Header().Get("Cache-Control") != "no-store" {
+ t.Fatal("employee department stats became publicly cacheable")
+ }
+ }
+ if reader.reads != 2 {
+ t.Fatal("malformed or unauthorized request reached aggregation", reader.reads)
+ }
+}
diff --git a/internal/httpapi/qa_master.go b/internal/httpapi/qa_master.go
index 471edb2..357b787 100644
--- a/internal/httpapi/qa_master.go
+++ b/internal/httpapi/qa_master.go
@@ -10,7 +10,7 @@ import (
func masterNoStore(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if strings.HasPrefix(r.URL.Path, "/api/v1/qa-ops/master/") {
+ if strings.HasPrefix(r.URL.Path, "/api/v1/qa-ops/master/") || strings.HasPrefix(r.URL.Path, "/api/v1/qa-ops/departments/") {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Pragma", "no-cache")
}
diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go
index b50c909..af728fa 100644
--- a/internal/httpapi/server.go
+++ b/internal/httpapi/server.go
@@ -181,6 +181,7 @@ func NewHandler(config Config) (http.Handler, error) {
}
mux := http.NewServeMux()
registerQAAIRoutes(mux, config)
+ mux.HandleFunc("POST /api/v1/qa-ops/departments/statistics", func(w http.ResponseWriter, r *http.Request) { qaDepartmentStatistics(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/dashboard", func(w http.ResponseWriter, r *http.Request) { qaOperationsDashboard(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/quality/query", func(w http.ResponseWriter, r *http.Request) { qaQualityQuery(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/records/{id}/reviews", func(w http.ResponseWriter, r *http.Request) { qaQualityReview(w, r, config) })
diff --git a/internal/qaopsmirror/department_statistics_cache.go b/internal/qaopsmirror/department_statistics_cache.go
new file mode 100644
index 0000000..f7fc3f2
--- /dev/null
+++ b/internal/qaopsmirror/department_statistics_cache.go
@@ -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
+}
diff --git a/internal/qaopsmirror/department_statistics_cache_test.go b/internal/qaopsmirror/department_statistics_cache_test.go
new file mode 100644
index 0000000..b18cdc1
--- /dev/null
+++ b/internal/qaopsmirror/department_statistics_cache_test.go
@@ -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")
+ }
+}
diff --git a/internal/qaopsmirror/department_statistics_integration_test.go b/internal/qaopsmirror/department_statistics_integration_test.go
new file mode 100644
index 0000000..999c66d
--- /dev/null
+++ b/internal/qaopsmirror/department_statistics_integration_test.go
@@ -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")
+ }
+}
diff --git a/internal/qaopsmirror/department_statistics_store.go b/internal/qaopsmirror/department_statistics_store.go
new file mode 100644
index 0000000..7022b82
--- /dev/null
+++ b/internal/qaopsmirror/department_statistics_store.go
@@ -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
+}
diff --git a/internal/qaopsmirror/store.go b/internal/qaopsmirror/store.go
index 5c04526..9dfd367 100644
--- a/internal/qaopsmirror/store.go
+++ b/internal/qaopsmirror/store.go
@@ -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} }
diff --git a/internal/qaopsorg/department_statistics.go b/internal/qaopsorg/department_statistics.go
new file mode 100644
index 0000000..1c5b39e
--- /dev/null
+++ b/internal/qaopsorg/department_statistics.go
@@ -0,0 +1,90 @@
+package qaopsorg
+
+import "time"
+
+type DepartmentActivity struct {
+ StaffID, UnionID, Asker, Trigger string
+ Visits int64
+ LastAskedAt time.Time
+}
+type DepartmentStatistic struct {
+ ID string `json:"id"`
+ ParentID string `json:"parent_id"`
+ Name string `json:"name"`
+ Region string `json:"region"`
+ Visitors int `json:"visitors"`
+ TotalPeople int `json:"total_people"`
+ Ratio *float64 `json:"ratio"`
+ Visits int64 `json:"visits"`
+ LastAskedAt *time.Time `json:"last_asked_at"`
+}
+type DepartmentStatistics struct {
+ Rows []DepartmentStatistic `json:"rows"`
+ TotalVisits int64 `json:"total_visits"`
+ UnmappedVisits int64 `json:"unmapped_visits"`
+ TotalPeople int `json:"total_people"`
+}
+
+func AggregateDepartmentStatistics(p *Attribution, activity []DepartmentActivity) (DepartmentStatistics, error) {
+ out := DepartmentStatistics{Rows: []DepartmentStatistic{}}
+ if p == nil || p.Metadata.State != "ready" {
+ return out, ErrUnavailable
+ }
+ indices := map[string]int{}
+ nodes := map[string]DepartmentView{}
+ visitors := map[string]map[string]bool{}
+ for _, d := range p.Metadata.View.Departments {
+ indices[d.ID] = len(out.Rows)
+ nodes[d.ID] = d
+ visitors[d.ID] = map[string]bool{}
+ out.Rows = append(out.Rows, DepartmentStatistic{ID: d.ID, ParentID: d.ParentID, Name: d.Name, Region: d.Region})
+ }
+ branches := map[string][]string{}
+ for _, person := range p.Members() {
+ seen := map[string]bool{}
+ for _, id := range person.DepartmentIDs {
+ for id != "" && !seen[id] {
+ node, ok := nodes[id]
+ if !ok {
+ return out, ErrUnavailable
+ }
+ seen[id] = true
+ id = node.ParentID
+ }
+ }
+ for id := range seen {
+ out.Rows[indices[id]].TotalPeople++
+ branches[person.PersonID] = append(branches[person.PersonID], id)
+ }
+ out.TotalPeople++
+ }
+ for _, a := range activity {
+ if a.Visits <= 0 || a.LastAskedAt.IsZero() {
+ return out, ErrInvalid
+ }
+ out.TotalVisits += a.Visits
+ person := p.Resolve(a.StaffID, a.UnionID, a.Asker, a.Trigger)
+ if len(branches[person.PersonID]) == 0 {
+ out.UnmappedVisits += a.Visits
+ continue
+ }
+ for _, id := range branches[person.PersonID] {
+ row := &out.Rows[indices[id]]
+ visitors[id][person.PersonID] = true
+ row.Visits += a.Visits
+ if row.LastAskedAt == nil || a.LastAskedAt.After(*row.LastAskedAt) {
+ at := a.LastAskedAt
+ row.LastAskedAt = &at
+ }
+ }
+ }
+ for i := range out.Rows {
+ row := &out.Rows[i]
+ row.Visitors = len(visitors[row.ID])
+ if row.TotalPeople > 0 {
+ percent := 100.0 * float64(row.Visitors) / float64(row.TotalPeople)
+ row.Ratio = &percent
+ }
+ }
+ return out, nil
+}
diff --git a/internal/qaopsorg/department_statistics_test.go b/internal/qaopsorg/department_statistics_test.go
new file mode 100644
index 0000000..a09bb6c
--- /dev/null
+++ b/internal/qaopsorg/department_statistics_test.go
@@ -0,0 +1,40 @@
+package qaopsorg
+
+import (
+ "testing"
+ "time"
+)
+
+func TestDepartmentStatisticsDeduplicateSubtreePeopleAndUseCurrentMembership(t *testing.T) {
+ directory := Directory{Departments: []Department{{ID: "root", Name: "Root"}, {ID: "child", ParentID: "root", Name: "Child"}, {ID: "former", ParentID: "root", Name: "Former"}, {ID: "current", ParentID: "root", Name: "Current"}, {ID: "empty", ParentID: "root", Name: "Empty"}}, People: []Person{{ID: "one", UnionID: "union-one", Name: "Fixture One", DepartmentIDs: []string{"root", "child"}}, {ID: "moved", Name: "Moved Fixture", DepartmentIDs: []string{"current"}}, {ID: "never", DepartmentIDs: []string{"child"}}}}
+ p, err := BuildAttribution(State{State: "ready", DirectoryID: "fixture"}, directory)
+ if err != nil {
+ t.Fatal(err)
+ }
+ earlier := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
+ later := earlier.Add(time.Hour)
+ out, err := AggregateDepartmentStatistics(p, []DepartmentActivity{{StaffID: "one", Visits: 2, LastAskedAt: earlier}, {UnionID: "union-one", Visits: 1, LastAskedAt: later}, {Asker: "Moved Fixture", Visits: 4, LastAskedAt: earlier}, {StaffID: "not-in-current-directory", Visits: 5, LastAskedAt: later}})
+ if err != nil {
+ t.Fatal("current-roster subtree aggregation is missing", err)
+ }
+ rows := map[string]DepartmentStatistic{}
+ for _, row := range out.Rows {
+ rows[row.ID] = row
+ }
+ root, child, current, former, empty := rows["root"], rows["child"], rows["current"], rows["former"], rows["empty"]
+ if root.TotalPeople != 3 || root.Visitors != 2 || root.Visits != 7 || root.Ratio == nil || *root.Ratio != 100.0*2/3 || root.LastAskedAt == nil || !root.LastAskedAt.Equal(later) {
+ t.Fatalf("subtree parent duplicated or event counts lost: %+v", root)
+ }
+ if child.TotalPeople != 2 || child.Visitors != 1 || child.Visits != 3 || child.Ratio == nil || *child.Ratio != 50 {
+ t.Fatalf("parent/child alias not deduplicated: %+v", child)
+ }
+ if current.Visitors != 1 || current.Visits != 4 || former.Visitors != 0 || former.Visits != 0 {
+ t.Fatal("historical events were attributed to an old department")
+ }
+ if empty.TotalPeople != 0 || empty.Ratio != nil || empty.LastAskedAt != nil {
+ t.Fatal("zero denominator fabricated a percentage/time")
+ }
+ if out.TotalVisits != 12 || out.UnmappedVisits != 5 || out.TotalPeople != 3 {
+ t.Fatalf("unmatched events hidden or fake membership: %+v", out)
+ }
+}
diff --git a/web/src/QADepartmentStatistics.test.tsx b/web/src/QADepartmentStatistics.test.tsx
new file mode 100644
index 0000000..f72f70f
--- /dev/null
+++ b/web/src/QADepartmentStatistics.test.tsx
@@ -0,0 +1,25 @@
+import { it, expect } from 'vitest'
+import { renderToStaticMarkup } from 'react-dom/server'
+import { DepartmentStatisticsView } from './QADepartmentStatistics'
+import { parseDepartmentStatistics } from './qaDepartmentStatistics'
+import { departmentStatisticsFixture } from './qaDepartmentStatistics.fixture'
+it('renders exactly five requested columns, a denominator and no fabricated zero ratio', () => {
+ const data = parseDepartmentStatistics(departmentStatisticsFixture, { period: 'all' }).snapshot!
+ const html = renderToStaticMarkup(
| 部门 | +访问人数 | +访问比例 | +访问次数 | +最近提问时间 | +
|---|---|---|---|---|
|
+
+ {
+ if (node) node.indeterminate = partial
+ }}
+ onChange={(e) =>
+ p.onSelect?.(selectDepartmentBranch(p.data.rows, selected, d.id, e.target.checked))
+ }
+ />
+ {hasChildren ? (
+
+ ) : (
+
+ )}
+
+ {d.name}
+ {label ? {label} : null}
+
+
+ |
+ + {d.visitors.toLocaleString('zh-CN')} + 总人数 {d.total_people.toLocaleString('zh-CN')} + | ++ {d.ratio === null ? '—' : `${d.ratio.toFixed(1)}%`} + | +{d.visits.toLocaleString('zh-CN')} | +{d.last_asked_at === null ? '—' : departmentTime(d.last_asked_at)} | +
没有匹配的部门
: null} ++ 每行含本部门及全部子部门,按当前通讯录人员去重;收起不改变统计。访问为已入总表的提问事件,区域筛选只改变可见部门。 +
+ {data.unmapped_visits > 0 ? ( ++ 另有 {data.unmapped_visits.toLocaleString('zh-CN')} 次提问未能归入当前通讯录部门,未虚构归属。 +
+ ) : null} + > + ) : !busy && !error ? ( +尚无统计结果,请重新读取。
+ ) : null} +