From 56b8cabed9213911b6beb4aeaac9baa22e872a00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Sat, 17 Oct 2026 19:02:13 +0800 Subject: [PATCH] =?UTF-8?q?feat(qaops):=20=E6=8E=A5=E5=85=A5=E9=97=AE?= =?UTF-8?q?=E7=AD=94=E7=BB=84=E7=BB=87=E8=A1=A5=E5=85=A8=E4=B8=8E=E5=8C=BA?= =?UTF-8?q?=E5=9F=9F=E4=BD=BF=E7=94=A8=E7=BB=9F=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 7 +- api/openapi.yaml | 1 + internal/dobotaiops/organization_records.go | 102 ++++++++++ .../organization_records_integration_test.go | 71 +++++++ internal/dobotaiops/records.go | 88 +++++---- .../dobotaiops/records_integration_test.go | 1 + .../dobotaiops/repository_integration_test.go | 2 +- internal/dobotaiops/safety.go | 2 +- internal/httpapi/qa_attribution.go | 185 ++++++++++++++++++ internal/httpapi/qa_attribution_test.go | 130 ++++++++++++ internal/httpapi/qa_ops.go | 16 ++ internal/httpapi/server.go | 1 + internal/qaopsorg/attribution.go | 109 +++++++++++ internal/qaopsorg/attribution_test.go | 46 +++++ internal/qaopsorg/store_integration_test.go | 4 + scripts/test-scope.json | 2 + web/src/QAOperations.tsx | 109 ++++++++--- web/src/QAUsage.test.tsx | 36 ++++ web/src/QAUsage.tsx | 105 ++++++++++ web/src/qaAttribution.test.ts | 50 +++++ web/src/qaOps.css | 6 + web/src/qaOps.ts | 95 ++++++++- web/src/qaUsage.ts | 85 ++++++++ 23 files changed, 1182 insertions(+), 71 deletions(-) create mode 100644 internal/dobotaiops/organization_records.go create mode 100644 internal/dobotaiops/organization_records_integration_test.go create mode 100644 internal/httpapi/qa_attribution.go create mode 100644 internal/httpapi/qa_attribution_test.go create mode 100644 internal/qaopsorg/attribution.go create mode 100644 internal/qaopsorg/attribution_test.go create mode 100644 web/src/QAUsage.test.tsx create mode 100644 web/src/QAUsage.tsx create mode 100644 web/src/qaAttribution.test.ts create mode 100644 web/src/qaUsage.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f4eb152..bc10ccb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,12 +4,13 @@ ### Added +- 问答运营按稳定身份关联当前治理通讯录,缺失部门/区域补全并保留源快照及目录/区域版本;空列判断包含完整筛选结果,不混合配置已变化的分页。新增完整时间/关键词范围的使用统计,问答计次、名册内人员去重,跨区/未匹配/身份缺失分列,不输出绩效结论;不回写 DobotAI 原表。 - 「问答运营 → 区域使用」支持管理员从网页发起持久化通讯录同步,重复请求重放、进行中操作合并;按服务器固定范围注册后台执行器,未接线或未检测到心跳时不创建新任务。界面显示真实任务状态、不编造百分比;失败保留旧快照与区域规则,同步完成不覆盖未保存草稿。旧执行器丢失租约后不能激活结果,重启接管和已提交快照的续跑使用原任务。 -- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件;问答组织关联尚未接入。同步默认关闭,容器启用仍需批准的既有周报 SDK/配置及兼容 Python 运行时挂载。 +- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件。同步默认关闭,容器启用仍需批准的既有周报 SDK/配置及兼容 Python 运行时挂载。 - 区域归属表支持长部门路径换行,避免继承全局不换行规则后将生效区域与归属依据列挤出桌面面板。 -- **「问答运营 → 区域使用」区域归属配置切片**:按稳定部门 ID 搜索和勾选完整路径,预览去重归属人数,保存版本后重新读取;父部门包含子部门、子部门显式配置优先,多部门跨区域人员单独待核对。预览不写入,过期版本和不完整部门树被阻断。当前不是使用/绩效统计验收,翻译及 AI 评估模型接入按用户要求暂缓。 +- **「问答运营 → 区域使用」区域归属配置切片**:按稳定部门 ID 搜索和勾选完整路径,预览去重归属人数,保存版本后重新读取;父部门包含子部门、子部门显式配置优先,多部门跨区域人员单独待核对。预览不写入,过期版本和不完整部门树被阻断。基础使用统计见本期新增,不代表绩效验收;翻译及 AI 评估模型接入按用户要求暂缓。 - 新增治理侧组织快照与区域修订迁移、受确认保护的后台导入命令;不修改 DobotAI 原表或钉钉组织结构。 -- **「问答运营 → 问答记录」首个开发切片**:在现有导航中查看 DobotAI 2.0 钉钉问答,支持半开时间范围、原问题关键词、稳定游标分页和完整详情;按整个筛选结果隐藏空列,反馈聚合不放大问答条数。外语翻译、AI 评估、人员区域映射尚未接入,不标为第一阶段完成。 +- **「问答运营 → 问答记录」首个开发切片**:在现有导航中查看 DobotAI 2.0 钉钉问答,支持半开时间范围、原问题关键词、稳定游标分页和完整详情;按整个筛选结果隐藏空列,反馈聚合不放大问答条数。外语翻译、AI 评估尚未接入,不标为第一阶段完成。 - 治理侧重新检查答案:包含 `暂无已发布` 即未覆盖,引用和源端 covered 不能抵消;未命中仍待评估,源端规则单独保留作对照。独立只读源默认关闭、租户后端固定、管理员会话鉴权,源故障不回退治理主库;安全告警明确保留 TEMP/TLS 尚未整改状态。 - **「版本记录」页**(一级入口):只读时间线追踪**远端 main 可达的全部提交**(含合并提交与已并入 main 的侧分支提交),按提交时间倒序显示标题/正文、`[正式版本] / [开发版本] / [历史提交]` 徽标、短 SHA、提交内变更记录与 `[查看提交]`/`[查看 tag]`;支持「全部 / 正式 / 开发 / 历史」筛选与游标翻页,窄屏单列。 - 新增只读接口 `GET /api/v1/build-info`(当前运行产物的构建身份)、`GET /api/v1/version-history`(快照游标分页,不返回伪造的 total)、`POST /api/v1/version-history/sync`(仅管理员手动同步,并发同步复用同一作业)。 diff --git a/api/openapi.yaml b/api/openapi.yaml index b858e90..3e806e9 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -99,6 +99,7 @@ } } }, + "/api/v1/qa-ops/usage": {"get": {"tags": ["QA operations"], "operationId": "getQAOperationsUsage", "summary": "完整筛选范围内按当前通讯录和区域版本回看2.0问答使用;固定租户、管理员访问,不输出绩效结论", "parameters": [{"name": "start", "in": "query", "required": true, "schema": {"type": "string", "format": "date-time"}}, {"name": "end", "in": "query", "required": true, "schema": {"type": "string", "format": "date-time"}}, {"name": "keyword", "in": "query", "schema": {"type": "string", "maxLength": 200}}], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/v1/qa-ops/status": { "get": { "tags": ["QA operations"], diff --git a/internal/dobotaiops/organization_records.go b/internal/dobotaiops/organization_records.go new file mode 100644 index 0000000..aecb026 --- /dev/null +++ b/internal/dobotaiops/organization_records.go @@ -0,0 +1,102 @@ +package dobotaiops + +import ( + "context" + "encoding/json" + "time" +) + +// Actor keys are internal join material, never fields of the browser response. +type ActorIdentity struct { + ActorID string `json:"actor_id"` + StaffID string `json:"staff_id"` + UnionID string `json:"union_id"` +} +type OrganizationVersion struct { + State string `json:"state"` + DirectoryID string `json:"directory_id"` + DirectorySource string `json:"directory_source"` + SyncedAt *time.Time `json:"synced_at"` + RevisionID string `json:"revision_id"` + Basis string `json:"basis"` +} +type RecordOrganization struct { + Version OrganizationVersion `json:"version"` + State string `json:"state"` + Departments []string `json:"departments"` + Region string `json:"region"` + SourceDepartment string `json:"source_department"` + SourceRegion string `json:"source_region"` + DepartmentOrigin string `json:"department_origin"` + RegionOrigin string `json:"region_origin"` +} +type UsageGroup struct { + Identity ActorIdentity `json:"-"` + Total int64 + Succeeded int64 + Failed int64 +} +type UsageGroups struct { + Groups []UsageGroup `json:"-"` + AsOf time.Time +} + +func decodeRecord(raw string) (Record, error) { + var wire struct { + Record + Identity ActorIdentity `json:"_identity"` + } + if err := json.Unmarshal([]byte(raw), &wire); err != nil { + return Record{}, err + } + wire.Record.Identity = wire.Identity + wire.Record.Coverage = CheckAnswerCoverage(wire.Record.Answer) + return wire.Record, nil +} +func (c *Client) ReadUsageGroups(ctx context.Context, query RecordQuery) (UsageGroups, error) { + if err := c.validateQueryWindow(query.Window); err != nil { + return UsageGroups{}, err + } + if query.Cursor != "" { + return UsageGroups{}, ErrInvalidQuery + } + pattern, patternErr := recordKeywordPattern(query.Keyword) + if patternErr != nil { + return UsageGroups{}, patternErr + } + result := UsageGroups{Groups: []UsageGroup{}} + err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error { + if q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&result.AsOf) != nil { + return ErrUnavailable + } + rows, err := q.Query(ctx, recordsBaseSQL+` SELECT identity::text,count(*),count(*) FILTER(WHERE status='succeeded'),count(*) FILTER(WHERE status='failed') FROM records WHERE `+recordFilterSQL+` GROUP BY identity`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern) + if err != nil { + return ErrUnavailable + } + defer rows.Close() + for rows.Next() { + var raw string + var group UsageGroup + if rows.Scan(&raw, &group.Total, &group.Succeeded, &group.Failed) != nil || json.Unmarshal([]byte(raw), &group.Identity) != nil { + return ErrUnavailable + } + result.Groups = append(result.Groups, group) + } + return rows.Err() + }) + return result, err +} + +// Keep the agreed field ordering after governance enriches an initially empty column. +func AddRecordColumns(page *RecordPage, extra ...string) { + all := map[string]bool{} + for _, col := range append(page.Columns, extra...) { + all[col] = true + } + page.Columns = []string{} + for _, col := range recordColumnOrder { + if all[col] { + page.Columns = append(page.Columns, col) + } + } +} diff --git a/internal/dobotaiops/organization_records_integration_test.go b/internal/dobotaiops/organization_records_integration_test.go new file mode 100644 index 0000000..fd339d9 --- /dev/null +++ b/internal/dobotaiops/organization_records_integration_test.go @@ -0,0 +1,71 @@ +package dobotaiops + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" +) + +func TestQARecordInternalIdentityAndWholeFilterKeys(t *testing.T) { + pool := fixturePool(t) + dsn := qaRecordsFixture(t, pool) + execFixture(t, pool, `UPDATE messages SET actor_union_id_snapshot='fixture-union' WHERE id='msg-req-3'`, `UPDATE messages SET actor_id=NULL WHERE id='msg-req-4'`) + client := buildReadOnlyClient(t, dsn) + query := RecordQuery{Window: Window{TenantKey: "default", Start: time.Date(2026, 10, 14, 0, 0, 0, 0, time.UTC), End: time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC)}, Limit: 1} + page, err := client.ListRecords(context.Background(), query) + if err != nil { + t.Fatal(err) + } + if page.Total != 4 || len(page.Items) != 1 || page.Items[0].Identity.StaffID != "" { + t.Fatal("fixture first page should be anonymous") + } + found := false + for _, actor := range page.ScopeActors { + if actor.StaffID == "ext-actor-1" && actor.UnionID == "fixture-union" { + found = true + } + } + if !found { + t.Fatal("whole-filter keys missing; later-page department would be hidden") + } + item, err := client.GetRecord(context.Background(), "default", "turn-3") + if err != nil || item.Identity.StaffID != "ext-actor-1" || item.Identity.UnionID != "fixture-union" { + t.Fatalf("stable identity not read from inbound actor/message: %v", err) + } + raw, _ := json.Marshal(page) + detail, _ := json.Marshal(item) + for _, s := range []string{string(raw), string(detail)} { + for _, private := range []string{"ext-actor-1", "fixture-union", "actor-row-1", "_identity", "scope_actors"} { + if strings.Contains(s, private) { + t.Fatal("internal roster key leaked into API JSON") + } + } + } +} +func TestQAUsageGroupsCountEventsOnceOverTheFullFilter(t *testing.T) { + pool := fixturePool(t) + dsn := qaRecordsFixture(t, pool) + + client := buildReadOnlyClient(t, dsn) + query := RecordQuery{Window: Window{TenantKey: "default", Start: time.Date(2026, 10, 14, 0, 0, 0, 0, time.UTC), End: time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC)}} + result, err := client.ReadUsageGroups(context.Background(), query) + if err != nil { + t.Fatal(err) + } + var total, success, failed int64 + for _, g := range result.Groups { + total += g.Total + success += g.Succeeded + failed += g.Failed + } + if total != 4 || success != 3 || failed != 1 || result.AsOf.IsZero() { + t.Fatalf("events multiplied/foreign tenant included: %d %d %d", total, success, failed) + } + query.Keyword = "%" + result, err = client.ReadUsageGroups(context.Background(), query) + if err != nil || len(result.Groups) != 0 { + t.Fatal("usage keyword wildcard not literal") + } +} diff --git a/internal/dobotaiops/records.go b/internal/dobotaiops/records.go index ed494ff..71fef89 100644 --- a/internal/dobotaiops/records.go +++ b/internal/dobotaiops/records.go @@ -51,21 +51,23 @@ type RecordFeedback struct { } type Record struct { - ID string `json:"id"` - Status string `json:"status"` - Question string `json:"question"` - Answer string `json:"answer"` - AskedAt time.Time `json:"asked_at"` - TimeSource string `json:"time_source"` - Asker string `json:"asker"` - TriggerPerson string `json:"trigger_person"` - Department string `json:"department"` - Region string `json:"region"` - References json.RawMessage `json:"references"` - Media json.RawMessage `json:"media"` - SourceCoverage SourceCoverage `json:"source_coverage"` - Feedback RecordFeedback `json:"feedback"` - Coverage CoverageCheck `json:"coverage"` + Identity ActorIdentity `json:"-"` + Organization *RecordOrganization `json:"organization,omitempty"` + ID string `json:"id"` + Status string `json:"status"` + Question string `json:"question"` + Answer string `json:"answer"` + AskedAt time.Time `json:"asked_at"` + TimeSource string `json:"time_source"` + Asker string `json:"asker"` + TriggerPerson string `json:"trigger_person"` + Department string `json:"department"` + Region string `json:"region"` + References json.RawMessage `json:"references"` + Media json.RawMessage `json:"media"` + SourceCoverage SourceCoverage `json:"source_coverage"` + Feedback RecordFeedback `json:"feedback"` + Coverage CoverageCheck `json:"coverage"` } type RecordQuery struct { @@ -76,12 +78,14 @@ type RecordQuery struct { } type RecordPage struct { - Items []Record `json:"items"` - Columns []string `json:"columns"` - Total int64 `json:"total"` - HasMore bool `json:"has_more"` - NextCursor string `json:"next_cursor"` - AsOf time.Time `json:"as_of"` + ScopeActors []ActorIdentity `json:"-"` + Organization *OrganizationVersion `json:"organization,omitempty"` + Items []Record `json:"items"` + Columns []string `json:"columns"` + Total int64 `json:"total"` + HasMore bool `json:"has_more"` + NextCursor string `json:"next_cursor"` + AsOf time.Time `json:"as_of"` } type recordCursor struct { @@ -92,10 +96,12 @@ type recordCursor struct { // A single inbound-message join controls names/time. Feedback is preaggregated; // joining each feedback row directly would multiply the business event count. +const actorIdentitySQL = `jsonb_build_object('actor_id',COALESCE(a.id,''),'staff_id',COALESCE(a.external_actor_id,''),'union_id',COALESCE(m.actor_union_id_snapshot,''))` const recordsBaseSQL = ` WITH records AS ( - SELECT t.id,COALESCE(m.created_at,t.created_at) AS asked_at,t.question, + SELECT t.id,COALESCE(m.created_at,t.created_at) AS asked_at,t.question,t.status,` + actorIdentitySQL + ` AS identity, jsonb_build_object( + '_identity',` + actorIdentitySQL + `, 'id',t.id,'status',t.status,'question',t.question,'answer',t.answer, 'asked_at',COALESCE(m.created_at,t.created_at), 'time_source',CASE WHEN m.id IS NULL THEN 'turn.created_at' ELSE 'request_message.created_at' END, @@ -137,15 +143,25 @@ const recordColumnsSQL = `SELECT count(*),jsonb_build_object( 'region',COALESCE(bool_or(payload->>'region'<>''),false), 'feedback',COALESCE(bool_or(payload->'feedback'->>'asker_value'<>'' OR (payload->'feedback'->>'up')::bigint>0 OR (payload->'feedback'->>'down')::bigint>0),false) - )::text FROM records WHERE ` + )::text,COALESCE(jsonb_agg(DISTINCT identity),'[]'::jsonb)::text FROM records WHERE ` var recordColumnOrder = []string{"question_chinese", "answer", "coverage", "is_correct", "product_category", "problem_type", "root_cause", "asked_at", "asker", "question", "language", "trigger_person", "department", "region", "feedback"} +func recordKeywordPattern(keyword string) (string, error) { + if !utf8.ValidString(keyword) || utf8.RuneCountInString(keyword) > 200 || strings.ContainsRune(keyword, 0) { + return "", ErrInvalidQuery + } + if keyword == "" { + return "", nil + } + return "%" + strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(keyword) + "%", nil +} + func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage, error) { if err := c.validateQueryWindow(query.Window); err != nil { return RecordPage{}, err } - if query.Limit < 1 || query.Limit > 100 || !utf8.ValidString(query.Keyword) || utf8.RuneCountInString(query.Keyword) > 200 || strings.ContainsRune(query.Keyword, 0) || len(query.Cursor) > 2048 { + if query.Limit < 1 || query.Limit > 100 || len(query.Cursor) > 2048 { return RecordPage{}, fmt.Errorf("%w: invalid record filters", ErrInvalidQuery) } scopeBytes, _ := json.Marshal([]string{query.Window.TenantKey, query.Window.Start.UTC().Format(time.RFC3339Nano), query.Window.End.UTC().Format(time.RFC3339Nano), query.Keyword}) @@ -160,9 +176,9 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage } before = cursor.AskedAt } - pattern := "" - if query.Keyword != "" { - pattern = "%" + strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(query.Keyword) + "%" + pattern, patternErr := recordKeywordPattern(query.Keyword) + if patternErr != nil { + return RecordPage{}, patternErr } args := []any{query.Window.TenantKey, query.Window.Start, query.Window.End, pattern} page := RecordPage{Items: make([]Record, 0), Columns: make([]string, 0)} @@ -170,11 +186,14 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage if err := q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&page.AsOf); err != nil { return ErrUnavailable } - var rawColumns string - if err := q.QueryRow(ctx, recordsBaseSQL+recordColumnsSQL+recordFilterSQL, append(args, noPublishedMarker)...).Scan(&page.Total, &rawColumns); err != nil { + var rawColumns, rawActors string + if err := q.QueryRow(ctx, recordsBaseSQL+recordColumnsSQL+recordFilterSQL, append(args, noPublishedMarker)...).Scan(&page.Total, &rawColumns, &rawActors); err != nil { return fmt.Errorf("%w: record count failed", ErrUnavailable) } var available map[string]bool + if json.Unmarshal([]byte(rawActors), &page.ScopeActors) != nil { + return ErrUnavailable + } if err := json.Unmarshal([]byte(rawColumns), &available); err != nil { return ErrUnavailable } @@ -194,11 +213,11 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage if err := rows.Scan(&raw); err != nil { return ErrUnavailable } - var item Record - if err := json.Unmarshal([]byte(raw), &item); err != nil { + item, err := decodeRecord(raw) + if err != nil { return ErrUnavailable } - item.Coverage = CheckAnswerCoverage(item.Answer) + page.Items = append(page.Items, item) } return rows.Err() @@ -233,10 +252,11 @@ func (c *Client) GetRecord(ctx context.Context, tenantKey, id string) (Record, e if err != nil { return ErrUnavailable } - if err := json.Unmarshal([]byte(raw), &item); err != nil { + item, err = decodeRecord(raw) + if err != nil { return ErrUnavailable } - item.Coverage = CheckAnswerCoverage(item.Answer) + return nil }) return item, err diff --git a/internal/dobotaiops/records_integration_test.go b/internal/dobotaiops/records_integration_test.go index 3056fd7..4e15daa 100644 --- a/internal/dobotaiops/records_integration_test.go +++ b/internal/dobotaiops/records_integration_test.go @@ -14,6 +14,7 @@ func qaRecordsFixture(t *testing.T, pool *pgxpool.Pool) string { dsn := buildFixture(t, pool) execFixture(t, pool, `ALTER TABLE messages ADD COLUMN actor_name_snapshot text NOT NULL DEFAULT '', ADD COLUMN trigger_person_snapshot text NOT NULL DEFAULT '', ADD COLUMN media_json jsonb NOT NULL DEFAULT '[]'`, + `DROP TABLE IF EXISTS answer_feedback`, `CREATE TABLE answer_feedback(id text PRIMARY KEY,tenant_key text,channel text,turn_id text,answer_message_id text,actor_id text,value text)`, `GRANT SELECT ON answer_feedback TO kg_ro_fixture`, `UPDATE messages SET actor_name_snapshot='测试人员',trigger_person_snapshot='回调昵称' WHERE id='msg-req-3'`, diff --git a/internal/dobotaiops/repository_integration_test.go b/internal/dobotaiops/repository_integration_test.go index 36669d5..3edaee6 100644 --- a/internal/dobotaiops/repository_integration_test.go +++ b/internal/dobotaiops/repository_integration_test.go @@ -84,7 +84,7 @@ func buildFixture(t *testing.T, pool *pgxpool.Pool) string { question text NOT NULL DEFAULT '', answer text NOT NULL DEFAULT '', error_message text NOT NULL DEFAULT '', created_at timestamptz NOT NULL)`, `CREATE TABLE messages (id text PRIMARY KEY, tenant_key text NOT NULL, channel text NOT NULL, actor_id text, - department_snapshot text NOT NULL DEFAULT '', region_snapshot text NOT NULL DEFAULT '', + department_snapshot text NOT NULL DEFAULT '', region_snapshot text NOT NULL DEFAULT '', actor_union_id_snapshot text NOT NULL DEFAULT '', direction text NOT NULL DEFAULT '', role text NOT NULL DEFAULT '', message_type text NOT NULL DEFAULT '', status text NOT NULL DEFAULT '', text_content text NOT NULL DEFAULT '', created_at timestamptz NOT NULL)`, `CREATE TABLE coverage_decisions (id text PRIMARY KEY, tenant_key text NOT NULL, channel text NOT NULL, diff --git a/internal/dobotaiops/safety.go b/internal/dobotaiops/safety.go index 416b760..3ac652a 100644 --- a/internal/dobotaiops/safety.go +++ b/internal/dobotaiops/safety.go @@ -31,7 +31,7 @@ WITH relations AS ( ('turns','references_json','jsonb'),('turns','knowledge_searched','bool'), ('turns','request_message_id','text'),('turns','answer_message_id','text'), ('messages','id','text'),('messages','actor_id','text'),('messages','department_snapshot','text'), - ('messages','region_snapshot','text'),('channel_actors','id','text'),('channel_actors','external_actor_id','text'), + ('messages','region_snapshot','text'),('messages','actor_union_id_snapshot','text'),('channel_actors','id','text'),('channel_actors','external_actor_id','text'), ('coverage_decisions','turn_id','text'),('coverage_decisions','verdict','text') ) SELECT jsonb_build_object( diff --git a/internal/httpapi/qa_attribution.go b/internal/httpapi/qa_attribution.go new file mode 100644 index 0000000..7aa967b --- /dev/null +++ b/internal/httpapi/qa_attribution.go @@ -0,0 +1,185 @@ +package httpapi + +import ( + "context" + "errors" + "knowledge-governance/internal/dobotaiops" + "knowledge-governance/internal/qaopsorg" + "net/http" + "strings" + "time" +) + +var errQAOrganization = errors.New("organization attribution unavailable") + +type qaAttributionProvider interface { + GetAttribution(context.Context) (*qaopsorg.Attribution, error) +} + +func recordAttribution(ctx context.Context, config Config) (*qaopsorg.Attribution, error) { + if config.QAOrg == nil { + return qaopsorg.BuildAttribution(qaopsorg.State{State: "empty"}, qaopsorg.Directory{}) + } + provider, ok := config.QAOrg.(qaAttributionProvider) + if !ok { + return nil, errQAOrganization + } + p, err := provider.GetAttribution(ctx) + if err != nil || p == nil { + return nil, errQAOrganization + } + return p, nil +} +func attributionVersion(p *qaopsorg.Attribution) dobotaiops.OrganizationVersion { + return 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"} +} +func enrichQARecord(item *dobotaiops.Record, p *qaopsorg.Attribution) { + person := p.Resolve(item.Identity.StaffID, item.Identity.UnionID) + o := &dobotaiops.RecordOrganization{Version: attributionVersion(p), State: person.State, Departments: person.Departments, Region: person.Region, SourceDepartment: item.Department, SourceRegion: item.Region, DepartmentOrigin: "unavailable", RegionOrigin: "unavailable"} + if item.Department != "" { + o.DepartmentOrigin = "source_snapshot" + } else if len(person.Departments) > 0 { + item.Department = strings.Join(person.Departments, ";") + o.DepartmentOrigin = "current_directory" + } + if item.Region != "" { + o.RegionOrigin = "source_snapshot" + } else if person.Region != "" { + item.Region = person.Region + o.RegionOrigin = "current_directory" + } + item.Organization = o +} +func enrichQAPage(page *dobotaiops.RecordPage, p *qaopsorg.Attribution) { + version := attributionVersion(p) + page.Organization = &version + for i := range page.Items { + enrichQARecord(&page.Items[i], p) + } + for _, actor := range page.ScopeActors { + person := p.Resolve(actor.StaffID, actor.UnionID) + if len(person.Departments) > 0 { + dobotaiops.AddRecordColumns(page, "department") + } + if person.Region != "" { + dobotaiops.AddRecordColumns(page, "region") + } + } +} + +type qaUsageReader interface { + ReadUsageGroups(context.Context, dobotaiops.RecordQuery) (dobotaiops.UsageGroups, error) +} +type qaUsageRow struct { + Key string `json:"key"` + Questions int64 `json:"questions"` + Succeeded int64 `json:"succeeded"` + Failed int64 `json:"failed"` + Other int64 `json:"other"` + Users *int `json:"users"` + RosterPeople *int `json:"roster_people"` +} +type qaUsage struct { + Organization dobotaiops.OrganizationVersion `json:"organization"` + AsOf time.Time `json:"as_of"` + Start time.Time `json:"start"` + End time.Time `json:"end"` + Keyword string `json:"keyword"` + Questions int64 `json:"questions"` + IdentifiedUsers int `json:"identified_users"` + Rows []qaUsageRow `json:"rows"` +} + +func summarizeQAUsage(groups dobotaiops.UsageGroups, p *qaopsorg.Attribution, query dobotaiops.RecordQuery) qaUsage { + result := qaUsage{Organization: attributionVersion(p), AsOf: groups.AsOf, Start: query.Window.Start, End: query.Window.End, Keyword: query.Keyword, Rows: []qaUsageRow{}} + keys := append(append([]string{}, qaopsorg.RegionNames...), "unassigned", "cross_region", "unmatched", "identity_conflict", "no_identity", "directory_missing") + rows := map[string]*qaUsageRow{} + members := map[string]map[string]bool{} + all := map[string]bool{} + for _, key := range keys { + row := &qaUsageRow{Key: key} + if p.Metadata.State == "ready" { + var n int + valid := true + switch key { + case "unassigned": + n = p.Metadata.View.UnassignedPeople + case "cross_region": + n = p.Metadata.View.ConflictingPeople + default: + var ok bool + n, ok = p.Metadata.View.Regions[key] + valid = ok + } + if valid { + row.RosterPeople = &n + row.Users = new(int) + } + } + rows[key] = row + members[key] = map[string]bool{} + } + for _, group := range groups.Groups { + person := p.Resolve(group.Identity.StaffID, group.Identity.UnionID) + key := person.State + if person.Region != "" { + key = person.Region + } + row := rows[key] + if row == nil { + continue + } + row.Questions += group.Total + row.Succeeded += group.Succeeded + row.Failed += group.Failed + row.Other += group.Total - group.Succeeded - group.Failed + result.Questions += group.Total + if person.PersonID != "" { + members[key][person.PersonID] = true + all[person.PersonID] = true + } + } + for _, key := range keys { + row := rows[key] + if row.Users != nil { + *row.Users = len(members[key]) + } + result.Rows = append(result.Rows, *row) + } + result.IdentifiedUsers = len(all) + return result +} +func qaOpsUsage(w http.ResponseWriter, r *http.Request, config Config) { + if !authorizeQAOps(w, r) { + return + } + reader, ok := config.QAOps.(qaUsageReader) + if !ok || config.QAOpsTenantKey == "" { + qaOpsError(w, dobotaiops.ErrUnavailable) + return + } + values := r.URL.Query() + for key, items := range values { + if (key != "start" && key != "end" && key != "keyword") || len(items) != 1 { + qaOpsError(w, dobotaiops.ErrInvalidQuery) + return + } + } + window, err := dobotaiops.NewWindow(config.QAOpsTenantKey, values.Get("start"), values.Get("end"), 90*24*time.Hour, config.Now()) + if err != nil { + qaOpsError(w, err) + return + } + p, err := recordAttribution(r.Context(), config) + if err != nil { + qaOpsError(w, err) + return + } + query := dobotaiops.RecordQuery{Window: window, Keyword: values.Get("keyword")} + groups, err := reader.ReadUsageGroups(r.Context(), query) + if err != nil { + qaOpsError(w, err) + return + } + writeJSON(w, 200, map[string]any{"data": summarizeQAUsage(groups, p, query)}) +} diff --git a/internal/httpapi/qa_attribution_test.go b/internal/httpapi/qa_attribution_test.go new file mode 100644 index 0000000..082cb26 --- /dev/null +++ b/internal/httpapi/qa_attribution_test.go @@ -0,0 +1,130 @@ +package httpapi + +import ( + "context" + "encoding/json" + "knowledge-governance/internal/dobotaiops" + "knowledge-governance/internal/qaopsorg" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +type attributionOrgSpy struct { + orgSpy + projection *qaopsorg.Attribution +} + +func (s *attributionOrgSpy) GetAttribution(context.Context) (*qaopsorg.Attribution, error) { + return s.projection, s.err +} + +type attributedReader struct{} + +func (*attributedReader) Available(context.Context) error { return nil } +func (*attributedReader) Safety() dobotaiops.SourceSafety { return dobotaiops.SourceSafety{SSL: true} } +func (*attributedReader) ListRecords(context.Context, dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) { + return dobotaiops.RecordPage{Items: []dobotaiops.Record{{ID: "anonymous"}}, ScopeActors: []dobotaiops.ActorIdentity{{StaffID: "fixture-private-staff"}}, Columns: []string{"question"}, Total: 3}, nil +} +func (*attributedReader) GetRecord(context.Context, string, string) (dobotaiops.Record, error) { + return dobotaiops.Record{ID: "one", Department: "历史部门", Region: "历史区域", Identity: dobotaiops.ActorIdentity{StaffID: "fixture-private-staff"}}, nil +} +func (*attributedReader) ReadUsageGroups(context.Context, dobotaiops.RecordQuery) (dobotaiops.UsageGroups, error) { + return dobotaiops.UsageGroups{AsOf: time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC), Groups: []dobotaiops.UsageGroup{{Identity: dobotaiops.ActorIdentity{StaffID: "fixture-private-staff"}, Total: 3, Succeeded: 2, Failed: 1}, {Identity: dobotaiops.ActorIdentity{UnionID: "fixture-private-union"}, Total: 2, Succeeded: 2}, {Identity: dobotaiops.ActorIdentity{StaffID: "unmatched"}, Total: 2}}}, nil +} +func attributionHandler(t *testing.T) (http.Handler, *attributionOrgSpy) { + t.Helper() + projection, err := qaopsorg.BuildAttribution(qaopsorg.State{State: "ready", DirectoryID: "directory-v1", RevisionID: "region-v1", Rules: []qaopsorg.Rule{{DepartmentID: "root", Region: "APAC"}}}, qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "root", Name: "测试公司"}}, People: []qaopsorg.Person{{ID: "fixture-private-staff", UnionID: "fixture-private-union", DepartmentIDs: []string{"root"}}}}) + if err != nil { + t.Fatal(err) + } + org := &attributionOrgSpy{projection: projection} + auth := newFakeAuthStore() + auth.sessions["attribution-admin"] = "usr-boss" + auth.sessions["attribution-viewer"] = "usr-eye" + h, err := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: &attributedReader{}, QAOpsTenantKey: "fixed", QAOrg: org, Now: func() time.Time { return time.Date(2026, 10, 17, 0, 0, 0, 0, time.UTC) }}) + if err != nil { + t.Fatal(err) + } + return h, org +} +func attributionRequest(h http.Handler, path, token string) *httptest.ResponseRecorder { + r := httptest.NewRequest("GET", path, nil) + r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token}) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w +} + +const attributionFilter = "?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z" + +func TestQAAttributionUsesWholeFilterAndPreservesHistoricalSnapshots(t *testing.T) { + h, org := attributionHandler(t) + w := attributionRequest(h, "/api/v1/qa-ops/records"+attributionFilter, "attribution-admin") + if w.Code != 200 { + t.Fatal(w.Code, w.Body.String()) + } + var page struct{ Data dobotaiops.RecordPage } + _ = json.Unmarshal(w.Body.Bytes(), &page) + if !strings.Contains(strings.Join(page.Data.Columns, ","), "department,region") { + t.Fatal("organization column hidden because first page is anonymous", w.Body.String()) + } + w = attributionRequest(h, "/api/v1/qa-ops/records/one", "attribution-admin") + var detail struct{ Data dobotaiops.Record } + _ = json.Unmarshal(w.Body.Bytes(), &detail) + if detail.Data.Department != "历史部门" || detail.Data.Region != "历史区域" || detail.Data.Organization == nil || detail.Data.Organization.Region != "APAC" { + t.Fatal("source snapshot overwritten or current attribution missing", w.Body.String()) + } + if strings.Contains(w.Body.String(), "fixture-private") { + t.Fatal("identity keys exposed") + } + org.err = qaopsorg.ErrUnavailable + w = attributionRequest(h, "/api/v1/qa-ops/records"+attributionFilter, "attribution-admin") + if w.Code != 503 || !strings.Contains(w.Body.String(), "organization_unavailable") { + t.Fatal("permission/storage failure hidden as empty", w.Body.String()) + } +} +func TestQAUsageIsAdminScopedDeduplicatedAndNotPerformance(t *testing.T) { + h, _ := attributionHandler(t) + path := "/api/v1/qa-ops/usage" + attributionFilter + for _, tc := range []struct { + token string + status int + }{{"", 401}, {"attribution-viewer", 403}, {"attribution-admin", 200}} { + w := attributionRequest(h, path, tc.token) + if w.Code != tc.status { + t.Fatalf("usage guard got %d: %s", w.Code, w.Body.String()) + } + if tc.status == 200 { + var result struct { + Data struct { + Questions int64 `json:"questions"` + IdentifiedUsers int `json:"identified_users"` + Rows []struct { + Key string + Questions int64 + Users *int + } + } + } + if json.Unmarshal(w.Body.Bytes(), &result) != nil || result.Data.Questions != 7 || result.Data.IdentifiedUsers != 1 { + t.Fatal("events/people not deduplicated", w.Body.String()) + } + for _, row := range result.Data.Rows { + if row.Key == "APAC" && (row.Questions != 5 || row.Users == nil || *row.Users != 1) { + t.Fatal("regional user double-counted") + } + } + if strings.Contains(w.Body.String(), "fixture-private") || strings.Contains(w.Body.String(), "performance") { + t.Fatal("private identity or performance verdict leaked") + } + } + } + for _, extra := range []string{"&tenant=forged", "&limit=1", "&cursor=forged", "&start=duplicate"} { + if w := attributionRequest(h, path+extra, "attribution-admin"); w.Code != 400 { + t.Fatal("usage accepted client scope or pagination") + } + } +} diff --git a/internal/httpapi/qa_ops.go b/internal/httpapi/qa_ops.go index 402841b..9fb8ac7 100644 --- a/internal/httpapi/qa_ops.go +++ b/internal/httpapi/qa_ops.go @@ -93,11 +93,17 @@ func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) { return } } + projection, err := recordAttribution(r.Context(), config) + if err != nil { + qaOpsError(w, err) + return + } page, err := config.QAOps.ListRecords(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: values.Get("keyword"), Cursor: values.Get("cursor"), Limit: limit}) if err != nil { qaOpsError(w, err) return } + enrichQAPage(&page, projection) writeJSON(w, http.StatusOK, map[string]any{"data": page}) } @@ -113,11 +119,17 @@ func getQAOpsRecord(w http.ResponseWriter, r *http.Request, config Config) { qaOpsError(w, dobotaiops.ErrInvalidQuery) return } + projection, err := recordAttribution(r.Context(), config) + if err != nil { + qaOpsError(w, err) + return + } item, err := config.QAOps.GetRecord(r.Context(), config.QAOpsTenantKey, r.PathValue("id")) if err != nil { qaOpsError(w, err) return } + enrichQARecord(&item, projection) writeJSON(w, http.StatusOK, map[string]any{"data": item}) } @@ -125,6 +137,10 @@ func qaOpsError(w http.ResponseWriter, err error) { status := http.StatusServiceUnavailable code := "source_unavailable" message := "问答数据源不可用,请检查独立只读连接;原有知识治理功能不受影响" + if errors.Is(err, errQAOrganization) { + code = "organization_unavailable" + message = "通讯录或区域配置读取失败,未将不可用数据伪装成空列,请重试" + } if errors.Is(err, dobotaiops.ErrInvalidQuery) { status = http.StatusBadRequest code = "invalid_query" diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index ba009af..5aca0a9 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -175,6 +175,7 @@ func NewHandler(config Config) (http.Handler, error) { config.NewID = newID } mux := http.NewServeMux() + mux.HandleFunc("GET /api/v1/qa-ops/usage", func(w http.ResponseWriter, r *http.Request) { qaOpsUsage(w, r, config) }) mux.HandleFunc("GET /api/v1/qa-ops/organization/sync", func(w http.ResponseWriter, r *http.Request) { qaOrganizationSync(w, r, config) }) mux.HandleFunc("POST /api/v1/qa-ops/organization/sync", func(w http.ResponseWriter, r *http.Request) { qaOrganizationSync(w, r, config) }) mux.HandleFunc("GET /api/v1/qa-ops/organization", func(w http.ResponseWriter, r *http.Request) { qaOrganization(w, r, config) }) diff --git a/internal/qaopsorg/attribution.go b/internal/qaopsorg/attribution.go new file mode 100644 index 0000000..bba1850 --- /dev/null +++ b/internal/qaopsorg/attribution.go @@ -0,0 +1,109 @@ +package qaopsorg + +import ( + "context" + "sort" +) + +type PersonAttribution struct { + State string `json:"state"` + PersonID string `json:"-"` + Departments []string `json:"departments"` + Region string `json:"region"` +} +type Attribution struct { + Metadata State + people map[string]PersonAttribution + unions map[string]string +} + +func BuildAttribution(state State, directory Directory) (*Attribution, error) { + p := &Attribution{Metadata: state, people: map[string]PersonAttribution{}, unions: map[string]string{}} + if state.State == "empty" { + return p, nil + } + if state.State != "ready" || state.DirectoryID == "" { + return nil, ErrUnavailable + } + view, err := Preview(directory, state.Rules) + if err != nil { + return nil, ErrUnavailable + } + p.Metadata.View = view + departments := map[string]DepartmentView{} + for _, d := range view.Departments { + departments[d.ID] = d + } + for _, person := range directory.People { + paths, regions := map[string]bool{}, map[string]bool{} + for _, id := range person.DepartmentIDs { + d := departments[id] + paths[d.Path] = true + if d.Region != "" { + regions[d.Region] = true + } + } + item := PersonAttribution{State: "unassigned", PersonID: person.ID, Departments: []string{}} + for path := range paths { + item.Departments = append(item.Departments, path) + } + sort.Strings(item.Departments) + if len(regions) == 1 { + item.State = "matched" + for region := range regions { + item.Region = region + } + } else if len(regions) > 1 { + item.State = "cross_region" + } + p.people[person.ID] = item + if person.UnionID != "" { + if !validID(person.UnionID) { + return nil, ErrUnavailable + } + if _, ok := p.unions[person.UnionID]; ok { + p.unions[person.UnionID] = "" + } else { + p.unions[person.UnionID] = person.ID + } + } + } + return p, nil +} +func (p *Attribution) Resolve(staff, union string) PersonAttribution { + none := PersonAttribution{State: "unmatched", Departments: []string{}} + if p == nil || p.Metadata.State != "ready" { + none.State = "directory_missing" + return none + } + if staff == "" && union == "" { + none.State = "no_identity" + return none + } + byUnion, unionKnown := p.unions[union] + if person, ok := p.people[staff]; ok { + if unionKnown && (byUnion == "" || byUnion != staff) { + none.State = "identity_conflict" + return none + } + return person + } + if unionKnown { + if byUnion == "" { + none.State = "identity_conflict" + return none + } + return p.people[byUnion] + } + return none +} +func (s *Store) GetAttribution(ctx context.Context) (*Attribution, error) { + if !s.available() { + return nil, ErrUnavailable + } + state, directory, err := s.read(ctx, s.pool, false) + if err != nil { + return nil, err + } + return BuildAttribution(state, directory) +} diff --git a/internal/qaopsorg/attribution_test.go b/internal/qaopsorg/attribution_test.go new file mode 100644 index 0000000..bf61b1c --- /dev/null +++ b/internal/qaopsorg/attribution_test.go @@ -0,0 +1,46 @@ +package qaopsorg + +import ( + "context" + "errors" + "testing" +) + +func TestAttributionUsesStableIdentityAndKeepsAmbiguitiesExplicit(t *testing.T) { + d := Directory{Departments: []Department{{ID: "root", Name: "fixture"}, {ID: "a", ParentID: "root", Name: "one"}, {ID: "b", ParentID: "root", Name: "two"}}, People: []Person{{ID: "staff-a", UnionID: "union-a", DepartmentIDs: []string{"a", "a"}}, {ID: "staff-cross", UnionID: "union-cross", DepartmentIDs: []string{"a", "b"}}, {ID: "duplicate-one", UnionID: "duplicate", DepartmentIDs: []string{"a"}}, {ID: "duplicate-two", UnionID: "duplicate", DepartmentIDs: []string{"b"}}}} + p, err := BuildAttribution(State{State: "ready", DirectoryID: "d", RevisionID: "r", Rules: []Rule{{DepartmentID: "root", Region: "国内工业"}, {DepartmentID: "b", Region: "APAC"}}}, d) + if err != nil { + t.Fatal(err) + } + for _, key := range [][2]string{{"staff-a", ""}, {"", "union-a"}} { + got := p.Resolve(key[0], key[1]) + if got.State != "matched" || got.Region != "国内工业" || len(got.Departments) != 1 || got.PersonID != "staff-a" { + t.Fatalf("stable identity not resolved/deduplicated: %+v", got) + } + } + if got := p.Resolve("staff-cross", ""); got.State != "cross_region" || got.Region != "" || len(got.Departments) != 2 { + t.Fatalf("invented primary region: %+v", got) + } + if got := p.Resolve("", "duplicate"); got.State != "identity_conflict" { + t.Fatalf("duplicate union selected first person: %+v", got) + } + if got := p.Resolve("staff-a", "union-cross"); got.State != "identity_conflict" { + t.Fatalf("contradictory identifiers silently preferred: %+v", got) + } + if got := p.Resolve("absent", ""); got.State != "unmatched" { + t.Fatalf("unknown identity inferred: %+v", got) + } + if got := p.Resolve("", ""); got.State != "no_identity" { + t.Fatalf("anonymous identity inferred: %+v", got) + } +} +func TestAttributionDoesNotTreatMissingDirectoryAsPermissionSuccess(t *testing.T) { + p, err := BuildAttribution(State{State: "empty"}, Directory{}) + if err != nil || p.Resolve("staff", "").State != "directory_missing" { + t.Fatal("missing directory not explicit") + } + var store *Store + if _, err = store.GetAttribution(context.Background()); !errors.Is(err, ErrUnavailable) { + t.Fatal("unavailable store returned an empty directory") + } +} diff --git a/internal/qaopsorg/store_integration_test.go b/internal/qaopsorg/store_integration_test.go index 6af53ac..8882a92 100644 --- a/internal/qaopsorg/store_integration_test.go +++ b/internal/qaopsorg/store_integration_test.go @@ -62,6 +62,10 @@ func TestOrganizationStoreRoundTripAndOptimisticConflict(t *testing.T) { if err != nil || read.RevisionID != saved.RevisionID || read.View.Regions["国内工业"] != 1 { t.Fatal("saved rules not consumed by read path") } + projection, projectionErr := store.GetAttribution(ctx) + if projectionErr != nil || projection.Metadata.DirectoryID != read.DirectoryID || projection.Metadata.RevisionID != read.RevisionID || projection.Resolve("u2", "").Region != "APAC" { + t.Fatal("attribution did not consume the saved directory/region revision") + } if _, err = store.SaveRules(ctx, request, "stale-admin"); !errors.Is(err, qaopsorg.ErrConflict) { t.Fatalf("stale update overwrote newer rules: %v", err) } diff --git a/scripts/test-scope.json b/scripts/test-scope.json index 7105950..9fbb0f8 100644 --- a/scripts/test-scope.json +++ b/scripts/test-scope.json @@ -9,6 +9,8 @@ "⚠️ 文件缺失或解析不了 ⇒ 门禁红:范围声明不出来时,不许默认放行。" ], "optional": [ + {"package": "knowledge-governance/internal/dobotaiops", "test": "TestQARecordInternalIdentityAndWholeFilterKeys", "reason": "必须显式一次性隔离PG;验证真实只读SQL身份关联/计数及隐私,不连接生产;默认无库时明确跳过,另行本地补验"}, + {"package": "knowledge-governance/internal/dobotaiops", "test": "TestQAUsageGroupsCountEventsOnceOverTheFullFilter", "reason": "必须显式一次性隔离PG;验证真实只读SQL身份关联/计数及隐私,不连接生产;默认无库时明确跳过,另行本地补验"}, { "package": "knowledge-governance/internal/qaopsorg", "test": "TestDirectorySyncQueueDurableReplayAndLeaseFencing", diff --git a/web/src/QAOperations.tsx b/web/src/QAOperations.tsx index 134a26d..bf8a080 100644 --- a/web/src/QAOperations.tsx +++ b/web/src/QAOperations.tsx @@ -1,10 +1,12 @@ import { useEffect, useRef, useState } from 'react' import type { FormEvent } from 'react' import { useOptionalAuth } from './auth' -import { fetchQARecord, fetchQARecords, fetchQAStatus, qaCellValue, qaColumns } from './qaOps' +import { fetchQARecord, fetchQARecords, fetchQAStatus, mergeQAPages, qaCellValue, qaColumns } from './qaOps' import type { QAQuery, QARecord, QARecordPage, QAStatus } from './qaOps' import './qaOps.css' import { QARegions } from './QARegions' +import { QAUsage } from './QAUsage' +import { usageLabels } from './qaUsage' interface ViewProps { page: QARecordPage | null @@ -48,6 +50,13 @@ export function QAOperationsView(props: ViewProps) { DobotAI 2.0 / 钉钉 · 独立只读连接{props.status ? ` · ${stateLabels[props.status.state]}` : ''} + {page?.organization ? ( +

+ {page.organization.state === 'ready' + ? `缺失组织信息按当前通讯录补全(${stamp(page.organization.synced_at!)}),不代表提问时归属。目录:${page.organization.directory_id};区域版本:${page.organization.revision_id || '未保存'}` + : '尚无完整通讯录,仅展示源端已有组织快照,不根据姓名推断。'} +

+ ) : null} {props.status?.warnings.map((warning) => (

{warningLabels[warning] ?? '数据源有待审核的安全告警'} @@ -79,7 +88,9 @@ export function QAOperationsView(props: ViewProps) {

提问人
{detail.asker || '未关联'}
+
部门
+
+ {detail.department || '未匹配'} + {detail.organization?.department_origin === 'current_directory' ? '(当前通讯录补全)' : ''} +
+
区域
+
+ {detail.region || '未配置/待核对'} + {detail.organization?.region_origin === 'current_directory' ? '(当前配置补全)' : ''} +
+ {detail.organization ? ( + <> +
当前组织关联
+
+ {detail.organization.state === 'matched' + ? '已关联' + : (usageLabels[detail.organization.state] ?? detail.organization.state)} +
+
当前通讯录部门/区域
+
+ {detail.organization.departments.join(';') || '未匹配'} /{' '} + {detail.organization.region || '未配置或待核对'} +
+
组织版本
+
+ {detail.organization.version.directory_id || '无完整目录'} /{' '} + {detail.organization.version.revision_id || '未保存区域配置'} +
+
源端组织快照
+
+ {detail.organization.source_department || '空'} / {detail.organization.source_region || '空'} +
+ + ) : null}
问答状态
{statusLabels[detail.status] ?? detail.status}
流程触发人员信息
@@ -230,7 +275,7 @@ function initialDraft() { } export function QAOperations() { - const [view, setView] = useState<'records' | 'regions'>('records') + const [view, setView] = useState<'records' | 'regions' | 'usage'>('records') const auth = useOptionalAuth() const canRead = auth?.identity?.role === 'admin' const [draft, setDraft] = useState(initialDraft) @@ -260,6 +305,13 @@ export function QAOperations() { useEffect(() => { if (!query || !canRead) return + if (view !== 'records') { + setLoading(false) + moreRequest.current?.abort() + detailRequest.current?.abort() + setDetail(null) + return + } const controller = new AbortController() generation.current += 1 moreRequest.current?.abort() @@ -286,7 +338,7 @@ export function QAOperations() { if (!controller.signal.aborted) setLoading(false) }) return () => controller.abort() - }, [query, canRead, revision]) + }, [query, canRead, revision, view]) useEffect( () => () => { @@ -341,17 +393,7 @@ export function QAOperations() { try { const result = await fetchQARecords({ ...query, cursor: page.next_cursor }, controller.signal) if (!controller.signal.aborted && currentGeneration === generation.current) { - setPage((current) => - current - ? { - ...result, - items: [ - ...current.items, - ...result.items.filter((item) => !current.items.some(({ id }) => id === item.id)), - ], - } - : result - ) + setPage(mergeQAPages(page, result)) } } catch (reason) { if (!controller.signal.aborted && currentGeneration === generation.current) @@ -364,7 +406,7 @@ export function QAOperations() {

- 问答运营 / {view === 'regions' ? '区域归属' : '问答记录'} + 问答运营 / {view === 'regions' ? '区域归属' : view === 'usage' ? '使用统计' : '问答记录'}

真实问答只读查询;原始记录、源端判断与治理复检分开保留。

@@ -378,6 +420,9 @@ export function QAOperations() { + @@ -420,21 +465,25 @@ export function QAOperations() {

- 当前切片:问答查询与覆盖复检。外语翻译、AI评估及人员映射尚未接入;空值不默认填“否”。 + 部门/区域保留源快照,缺失时按当前通讯录补全;使用统计不是绩效结论。外语翻译与AI评估仍暂缓,空值不默认填“否”。

- void select(id)} - onCloseDetail={close} - onLoadMore={() => void loadMore()} - onRetry={() => setRevision((value) => value + 1)} - /> + {view === 'usage' ? ( + + ) : ( + void select(id)} + onCloseDetail={close} + onLoadMore={() => void loadMore()} + onRetry={() => setRevision((value) => value + 1)} + /> + )} )} diff --git a/web/src/QAUsage.test.tsx b/web/src/QAUsage.test.tsx new file mode 100644 index 0000000..294f53c --- /dev/null +++ b/web/src/QAUsage.test.tsx @@ -0,0 +1,36 @@ +import { renderToStaticMarkup } from 'react-dom/server' +import { describe, expect, it } from 'vitest' +import { QAUsageView } from './QAUsage' +import { parseQAUsage } from './qaUsage' +const usage = parseQAUsage({ + organization: { + state: 'ready', + directory_id: 'd', + directory_source: 'weekly_report_live', + synced_at: '2026-10-17T07:59:50Z', + revision_id: 'r', + basis: 'current_directory', + }, + as_of: '2026-10-17T08:00:00Z', + start: '2026-10-14T00:00:00Z', + end: '2026-10-15T00:00:00Z', + keyword: '', + questions: 2, + identified_users: 0, + rows: [{ key: 'unmatched', questions: 2, succeeded: 1, failed: 1, other: 0, users: null, roster_people: null }], +}) +describe('usage statistics evidence', () => { + it('shows a current-roster basis and unknown counts without performance claims', () => { + const html = renderToStaticMarkup( {}} />) + expect(html).toContain('按当前通讯录回看') + expect(html).toContain('名册未匹配') + expect(html).toContain('不可确定') + expect(html).not.toContain('达标率') + expect(html).not.toContain('绩效合格') + }) + it('keeps unavailable data an error, not a zero-result report', () => { + const html = renderToStaticMarkup( {}} />) + expect(html).toContain('上游不可用') + expect(html).not.toContain('共 0 条') + }) +}) diff --git a/web/src/QAUsage.tsx b/web/src/QAUsage.tsx new file mode 100644 index 0000000..9dc0d9d --- /dev/null +++ b/web/src/QAUsage.tsx @@ -0,0 +1,105 @@ +import { useEffect, useState } from 'react' +import type { QAQuery } from './qaOps' +import { fetchQAUsage, usageLabels } from './qaUsage' +import type { QAUsage as Usage } from './qaUsage' +interface Props { + data: Usage | null + loading: boolean + error: string + onRetry: () => void +} +const stamp = (v: string) => new Date(v).toLocaleString('zh-CN', { hour12: false }) +export function QAUsageView({ data, loading, error, onRetry }: Props) { + return ( +
+

+ 按当前通讯录回看历史问答,不代表提问时的组织归属。成功/失败是源端运行状态,不等于答案正确;不输出绩效结论。 +

+ {loading ?

正在读取完整筛选范围的使用统计…

: null} + {error ? ( +

+ {error}{' '} + +

+ ) : null} + {data && !error ? ( + <> +
+ + 共 {data.questions} 条问答 · 已关联提问人数 {data.identified_users} + + 统计截止读取时间:{stamp(data.as_of)} +
+

+ 范围:{stamp(data.start)} 至 {stamp(data.end)}(不含结束时刻) + {data.keyword ? ` · 原问题包含:${data.keyword}` : ''} +

+

+ {data.organization.state === 'ready' + ? `通讯录同步:${stamp(data.organization.synced_at!)} · 目录 ${data.organization.directory_id} · 区域配置 ${data.organization.revision_id || '尚未保存'}` + : '尚无完整通讯录,当前不能确定部门区域或去重人数。'} +

+
+ + + + + + + + + + + + + + {data.rows.map((row) => ( + + + + + + + + + + ))} + +
区域/待核对状态问答条数成功失败其他状态已关联提问人数通讯录归属人数
{usageLabels[row.key]}{row.questions}{row.succeeded}{row.failed}{row.other}{row.users ?? '不可确定'}{row.roster_people ?? '不适用'}
+
+

+ 按问答唯一 ID 计次;同一名册人员的多部门、多个身份记录只计 1 + 人。未匹配或身份冲突不编造人数;通讯录人数不是在职或考核人数。 +

+ + ) : null} +
+ ) +} +export function QAUsage({ query }: { query: QAQuery | null }) { + const [data, setData] = useState(null), + [loading, setLoading] = useState(false), + [error, setError] = useState(''), + [revision, setRevision] = useState(0) + useEffect(() => { + if (!query) return + const c = new AbortController() + setLoading(true) + setData(null) + setError('') + void fetchQAUsage(query, c.signal) + .then((value) => { + if (!c.signal.aborted) setData(value) + }) + .catch((e: unknown) => { + if (!c.signal.aborted) setError(e instanceof Error ? e.message : '统计读取失败') + }) + .finally(() => { + if (!c.signal.aborted) setLoading(false) + }) + return () => c.abort() + }, [query, revision]) + return setRevision((v) => v + 1)} /> +} diff --git a/web/src/qaAttribution.test.ts b/web/src/qaAttribution.test.ts new file mode 100644 index 0000000..50af14a --- /dev/null +++ b/web/src/qaAttribution.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from 'vitest' +import { parseQAOrganizationVersion, mergeQAPages, parseQARecordPage } from './qaOps' +import { parseQAUsage } from './qaUsage' +const version = { + state: 'ready', + directory_id: 'd', + directory_source: 'weekly_report_live', + synced_at: '2026-10-17T07:59:50Z', + revision_id: 'r', + basis: 'current_directory', +} +const row = { key: 'APAC', questions: 5, succeeded: 3, failed: 1, other: 1, users: 1, roster_people: 4 } +const usage = { + organization: version, + as_of: '2026-10-17T08:00:00Z', + start: '2026-10-14T00:00:00Z', + end: '2026-10-15T00:00:00Z', + keyword: '', + questions: 5, + identified_users: 1, + rows: [row], +} +describe('organization evidence and usage contracts', () => { + it('keeps a valid current-roster version and rejects contradictory metadata', () => { + expect(parseQAOrganizationVersion(version).directory_id).toBe('d') + expect(() => parseQAOrganizationVersion({ ...version, directory_id: '' })).toThrow() + }) + it('does not append pages across directory or regional revisions', () => { + const page = parseQARecordPage({ + items: [], + columns: [], + total: 0, + has_more: false, + next_cursor: '', + as_of: usage.as_of, + organization: version, + }) + expect(() => + mergeQAPages(page, { ...page, organization: { ...page.organization!, revision_id: 'changed' } }) + ).toThrow(/配置已变化/) + expect(mergeQAPages(page, page).total).toBe(0) + }) + it('validates event conservation and unknown participant counts instead of inventing zeros', () => { + expect(parseQAUsage(usage).identified_users).toBe(1) + expect(parseQAUsage({ ...usage, rows: [{ ...row, users: null, roster_people: null }] }).rows[0].users).toBeNull() + expect(() => parseQAUsage({ ...usage, questions: 6 })).toThrow() + expect(() => parseQAUsage({ ...usage, rows: [{ ...row, other: 0 }] })).toThrow() + expect(() => parseQAUsage({ ...usage, rows: [{ ...row, questions: -1 }] })).toThrow() + }) +}) diff --git a/web/src/qaOps.css b/web/src/qaOps.css index 1985b0b..48dda03 100644 --- a/web/src/qaOps.css +++ b/web/src/qaOps.css @@ -66,6 +66,12 @@ outline: 2px solid var(--c-run); outline-offset: 2px; } +.qa-ops-organization { + margin: 8px 14px; + overflow-wrap: anywhere; + font-size: 12px; + line-height: 1.5; +} .qa-ops-results { display: flex; flex-direction: column; diff --git a/web/src/qaOps.ts b/web/src/qaOps.ts index bf534c1..561d1b6 100644 --- a/web/src/qaOps.ts +++ b/web/src/qaOps.ts @@ -17,7 +17,59 @@ export const qaColumns = [ ] as const export type QAColumn = (typeof qaColumns)[number]['key'] +export interface QAOrganizationVersion { + state: 'ready' | 'empty' + directory_id: string + directory_source: string + synced_at: string | null + revision_id: string + basis: 'current_directory' +} +export interface QARecordOrganization { + version: QAOrganizationVersion + state: string + departments: string[] + region: string + source_department: string + source_region: string + department_origin: string + region_origin: string +} +export function parseQAOrganizationVersion(value: unknown): QAOrganizationVersion { + const v = object(value) + if (!['ready', 'empty'].includes(text(v.state)) || v.basis !== 'current_directory') return invalid() + const result = { + state: v.state as QAOrganizationVersion['state'], + directory_id: text(v.directory_id), + directory_source: text(v.directory_source), + synced_at: v.synced_at === null ? null : instant(v.synced_at), + revision_id: text(v.revision_id), + basis: 'current_directory' as const, + } + if ( + result.state === 'ready' && + (!result.directory_id || + !result.synced_at || + !['weekly_report_live', 'weekly_report_snapshot'].includes(result.directory_source)) + ) + return invalid() + if (result.state === 'empty' && (result.directory_id || result.revision_id || result.synced_at !== null)) + return invalid() + return result +} +export function mergeQAPages(current: QARecordPage, next: QARecordPage): QARecordPage { + if ( + current.organization?.directory_id !== next.organization?.directory_id || + current.organization?.revision_id !== next.organization?.revision_id + ) + throw new Error('通讯录或区域配置已变化,请重新查询,不能混合不同版本的分页结果') + return { + ...next, + items: [...current.items, ...next.items.filter((item) => !current.items.some((old) => old.id === item.id))], + } +} export interface QARecord { + organization?: QARecordOrganization id: string status: string question: string @@ -41,6 +93,7 @@ export interface QARecord { language?: string } export interface QARecordPage { + organization?: QAOrganizationVersion items: QARecord[] columns: QAColumn[] total: number @@ -121,6 +174,36 @@ export function parseQARecord(value: unknown): QARecord { if (typeof row.is_correct !== 'boolean' && row.is_correct !== null) return invalid() item.is_correct = row.is_correct } + if (row.organization !== undefined) { + const o = object(row.organization) + if ( + !Array.isArray(o.departments) || + ![ + 'matched', + 'unassigned', + 'cross_region', + 'unmatched', + 'identity_conflict', + 'no_identity', + 'directory_missing', + ].includes(text(o.state)) + ) + return invalid() + const origin = (v: unknown) => { + const s = text(v) + return ['source_snapshot', 'current_directory', 'unavailable'].includes(s) ? s : invalid() + } + item.organization = { + version: parseQAOrganizationVersion(o.version), + state: text(o.state), + departments: o.departments.map(text), + region: text(o.region), + source_department: text(o.source_department), + source_region: text(o.source_region), + department_origin: origin(o.department_origin), + region_origin: origin(o.region_origin), + } + } return item } @@ -137,10 +220,18 @@ export function parseQARecordPage(value: unknown): QARecordPage { return invalid() if (new Set(items.map(({ id }) => id)).size !== items.length || new Set(columns).size !== columns.length) return invalid() - return { items, columns, total, has_more: page.has_more, next_cursor: nextCursor, as_of: instant(page.as_of) } + return { + items, + columns, + total, + has_more: page.has_more, + next_cursor: nextCursor, + as_of: instant(page.as_of), + ...(page.organization === undefined ? {} : { organization: parseQAOrganizationVersion(page.organization) }), + } } -async function getPayload(path: string, signal?: AbortSignal): Promise { +export async function getPayload(path: string, signal?: AbortSignal): Promise { const response = await fetch(path, { credentials: 'same-origin', cache: 'no-store', signal }) const raw: unknown = await response.json().catch(() => null) if (!response.ok) { diff --git a/web/src/qaUsage.ts b/web/src/qaUsage.ts new file mode 100644 index 0000000..c16b9fa --- /dev/null +++ b/web/src/qaUsage.ts @@ -0,0 +1,85 @@ +import type { QAOrganizationVersion, QAQuery } from './qaOps' +import { getPayload, parseQAOrganizationVersion } from './qaOps' +export interface QAUsageRow { + key: string + questions: number + succeeded: number + failed: number + other: number + users: number | null + roster_people: number | null +} +export interface QAUsage { + organization: QAOrganizationVersion + as_of: string + start: string + end: string + keyword: string + questions: number + identified_users: number + rows: QAUsageRow[] +} +const bad = (): never => { + throw new Error('使用统计响应无效,请检查完整性及接口契约') +} +const obj = (v: unknown): Record => + v && typeof v === 'object' && !Array.isArray(v) ? (v as Record) : bad() +const text = (v: unknown) => (typeof v === 'string' ? v : bad()) +const count = (v: unknown) => (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? v : bad()) +const stamp = (v: unknown) => { + const s = text(v) + return !Number.isNaN(Date.parse(s)) ? s : bad() +} +export const usageLabels: Record = { + 国内工业: '国内工业', + APAC: 'APAC', + EMEA: 'EMEA', + America: 'America', + unassigned: '未配置区域', + cross_region: '跨区域待核对', + unmatched: '名册未匹配', + identity_conflict: '身份冲突', + no_identity: '身份信息缺失', + directory_missing: '尚无完整通讯录', +} +export function parseQAUsage(value: unknown): QAUsage { + const v = obj(value) + if (!Array.isArray(v.rows)) return bad() + const rows = v.rows.map((raw) => { + const r = obj(raw) + const key = text(r.key) + if (!Object.hasOwn(usageLabels, key)) return bad() + const row = { + key, + questions: count(r.questions), + succeeded: count(r.succeeded), + failed: count(r.failed), + other: count(r.other), + users: r.users === null ? null : count(r.users), + roster_people: r.roster_people === null ? null : count(r.roster_people), + } + if (row.questions !== row.succeeded + row.failed + row.other) return bad() + return row + }) + const result = { + organization: parseQAOrganizationVersion(v.organization), + as_of: stamp(v.as_of), + start: stamp(v.start), + end: stamp(v.end), + keyword: text(v.keyword), + questions: count(v.questions), + identified_users: count(v.identified_users), + rows, + } + if ( + result.questions !== rows.reduce((n, r) => n + r.questions, 0) || + new Set(rows.map((r) => r.key)).size !== rows.length || + !(new Date(result.start) < new Date(result.end)) + ) + return bad() + return result +} +export async function fetchQAUsage(query: QAQuery, signal?: AbortSignal): Promise { + const params = new URLSearchParams({ start: query.start, end: query.end, keyword: query.keyword }) + return parseQAUsage(await getPayload(`/api/v1/qa-ops/usage?${params}`, signal)) +}