Compare commits

..

2 Commits

Author SHA1 Message Date
姚章浩 9556db1ef0 feat(qaops): 增加个人自然月用量与零记录人员明细 2026-10-17 19:59:33 +08:00
姚章浩 56b8cabed9 feat(qaops): 接入问答组织补全与区域使用统计 2026-10-17 19:02:13 +08:00
34 changed files with 2424 additions and 75 deletions
+6 -3
View File
@@ -4,12 +4,15 @@
### Added
- 「使用统计 → 个人月明细」按北京时间自然月及截止时点展示当前应用可见名册的人员用量(包含本源零记录),支持部门含子部门、区域/待核对状态、姓名/完整部门路径和已有提问/零记录筛选。稳定身份关联去重、不可关联问答单列、过期组织版本阻断翻页;源端姓名可缺失并提示重新同步,不按姓名匹配身份。姓名筛选通过有界只读 POST 请求体传递、不进入 URL,原始员工标识不返回浏览器;名册不作为在职/考核分母,当月进度不作为绩效结论。
- 问答运营按稳定身份关联当前治理通讯录,缺失部门/区域补全并保留源快照及目录/区域版本;空列判断包含完整筛选结果,不混合配置已变化的分页。新增完整时间/关键词范围的使用统计,问答计次、名册内人员去重,跨区/未匹配/身份缺失分列,不输出绩效结论;不回写 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`(仅管理员手动同步,并发同步复用同一作业)。
+2
View File
@@ -99,6 +99,8 @@
}
}
},
"/api/v1/qa-ops/usage/people": {"post": {"tags": ["QA operations"], "operationId": "queryQAOperationsMonthlyPeople", "summary": "按北京时间自然月列出当前名册人员的2.0用量(含零记录),仅管理员,不返回原始员工标识,不作为在职/考核名单", "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "完整名册缺失或目录/区域版本变化,请同步/重新查询,不返回伪零"}}, "description": "只读查询,不写治理库或生产库;姓名筛选置于 JSON 请求体,不进入 URL;整名册指标不随人员筛选变化。第2页起须带首页目录、区域版本及 end 截止。", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "required": ["month"], "properties": {"month": {"type": "string", "pattern": "^(?!0000)[0-9]{4}-(0[1-9]|1[0-2])$"}, "cutoff": {"type": "string", "format": "date-time"}, "region": {"type": "string", "enum": ["国内工业", "APAC", "EMEA", "America", "unassigned", "cross_region"]}, "department_id": {"type": "string"}, "activity": {"type": "string", "enum": ["all", "used", "zero"]}, "search": {"type": "string", "maxLength": 100}, "page": {"type": "integer", "minimum": 1, "maximum": 100000, "default": 1}, "limit": {"type": "integer", "minimum": 1, "maximum": 100, "default": 30}, "directory_id": {"type": "string"}, "revision_id": {"type": "string"}}}}}}, "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-usage-read"]}}]}},
"/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"],
+102
View File
@@ -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)
}
}
}
@@ -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")
}
}
+54 -34
View File
@@ -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
@@ -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'`,
@@ -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,
+1 -1
View File
@@ -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(
+185
View File
@@ -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)})
}
+130
View File
@@ -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")
}
}
}
+312
View File
@@ -0,0 +1,312 @@
package httpapi
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qaopsorg"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
_ "time/tzdata"
"unicode/utf8"
)
type monthlyFilter struct {
Month, Region, Department, Activity, Search string
Start, End, MonthEnd time.Time
Page, Limit int
}
type monthlyPerson struct {
Key string `json:"key"`
Name string `json:"name"`
State string `json:"state"`
Region string `json:"region"`
Departments []string `json:"departments"`
Questions int64 `json:"questions"`
Succeeded int64 `json:"succeeded"`
Failed int64 `json:"failed"`
Other int64 `json:"other"`
}
type monthlyDepartment struct {
ID string `json:"id"`
Path string `json:"path"`
}
type monthlyPeople struct {
Organization dobotaiops.OrganizationVersion `json:"organization"`
Source string `json:"source"`
Timezone string `json:"timezone"`
Month string `json:"month"`
Start time.Time `json:"start"`
End time.Time `json:"end"`
MonthEnd time.Time `json:"month_end"`
AsOf time.Time `json:"as_of"`
Partial bool `json:"partial"`
Questions int64 `json:"questions"`
LinkedQuestions int64 `json:"linked_questions"`
UnresolvedQuestions int64 `json:"unresolved_questions"`
RosterPeople int `json:"roster_people"`
UsedPeople int `json:"used_people"`
ZeroPeople int `json:"zero_people"`
MissingNames int `json:"missing_names"`
Total int `json:"total"`
Page int `json:"page"`
Limit int `json:"limit"`
HasMore bool `json:"has_more"`
Rows []monthlyPerson `json:"rows"`
DepartmentOptions []monthlyDepartment `json:"department_options"`
}
func parseMonthlyFilter(values url.Values, now time.Time) (monthlyFilter, error) {
f := monthlyFilter{Month: values.Get("month"), Region: values.Get("region"), Department: values.Get("department_id"), Activity: values.Get("activity"), Search: values.Get("search"), Page: 1, Limit: 30}
allowed := map[string]bool{"month": true, "cutoff": true, "region": true, "department_id": true, "activity": true, "search": true, "page": true, "limit": true, "directory_id": true, "revision_id": true}
for key, v := range values {
if !allowed[key] || len(v) != 1 {
return f, dobotaiops.ErrInvalidQuery
}
}
loc, err := time.LoadLocation("Asia/Shanghai")
if err != nil {
return f, dobotaiops.ErrUnavailable
}
f.Start, err = time.ParseInLocation("2006-01", f.Month, loc)
if err != nil || len(f.Month) != 7 || f.Start.Year() < 1 || f.Start.Format("2006-01") != f.Month || !f.Start.Before(now) {
return f, dobotaiops.ErrInvalidQuery
}
f.MonthEnd = f.Start.AddDate(0, 1, 0)
f.End = f.MonthEnd
if now.Before(f.End) {
f.End = now.In(loc)
}
if raw := values.Get("cutoff"); raw != "" {
cutoff, e := time.Parse(time.RFC3339Nano, raw)
if e != nil || !cutoff.After(f.Start) || cutoff.After(f.MonthEnd) || cutoff.After(now) {
return f, dobotaiops.ErrInvalidQuery
}
f.End = cutoff.In(loc)
}
if f.Activity == "" {
f.Activity = "all"
}
if f.Activity != "all" && f.Activity != "used" && f.Activity != "zero" {
return f, dobotaiops.ErrInvalidQuery
}
validRegion := f.Region == "" || f.Region == "unassigned" || f.Region == "cross_region"
for _, r := range qaopsorg.RegionNames {
validRegion = validRegion || f.Region == r
}
if !validRegion {
return f, dobotaiops.ErrInvalidQuery
}
if !utf8.ValidString(f.Search) || utf8.RuneCountInString(f.Search) > 100 || strings.ContainsRune(f.Search, 0) {
return f, dobotaiops.ErrInvalidQuery
}
for key, target := range map[string]*int{"page": &f.Page, "limit": &f.Limit} {
if raw := values.Get(key); raw != "" {
n, e := strconv.Atoi(raw)
if e != nil || n < 1 || n > 100000 {
return f, dobotaiops.ErrInvalidQuery
}
*target = n
}
}
if f.Limit > 100 || f.Page > 1 && (!values.Has("directory_id") || !values.Has("revision_id")) {
return f, dobotaiops.ErrInvalidQuery
}
return f, nil
}
func monthlyHasDepartment(person qaopsorg.PersonAttribution, department string, parents map[string]string) bool {
if department == "" {
return true
}
for _, id := range person.DepartmentIDs {
for cur := id; cur != ""; cur = parents[cur] {
if cur == department {
return true
}
}
}
return false
}
func monthlyResult(groups dobotaiops.UsageGroups, p *qaopsorg.Attribution, f monthlyFilter) monthlyPeople {
result := monthlyPeople{Organization: attributionVersion(p), Source: "2.0", Timezone: "Asia/Shanghai", Month: f.Month, Start: f.Start, End: f.End, MonthEnd: f.MonthEnd, AsOf: groups.AsOf, Partial: f.End.Before(f.MonthEnd), Page: f.Page, Limit: f.Limit, Rows: []monthlyPerson{}, DepartmentOptions: []monthlyDepartment{}}
totals := map[string]dobotaiops.UsageGroup{}
for _, group := range groups.Groups {
result.Questions += group.Total
person := p.Resolve(group.Identity.StaffID, group.Identity.UnionID)
if person.PersonID == "" {
result.UnresolvedQuestions += group.Total
continue
}
n := totals[person.PersonID]
n.Total += group.Total
n.Succeeded += group.Succeeded
n.Failed += group.Failed
totals[person.PersonID] = n
result.LinkedQuestions += group.Total
}
parents := map[string]string{}
for _, d := range p.Metadata.View.Departments {
parents[d.ID] = d.ParentID
result.DepartmentOptions = append(result.DepartmentOptions, monthlyDepartment{ID: d.ID, Path: d.Path})
}
rows := []monthlyPerson{}
people := p.Members()
result.RosterPeople = len(people)
search := strings.ToLower(f.Search)
for _, person := range people {
n := totals[person.PersonID]
if n.Total > 0 {
result.UsedPeople++
} else {
result.ZeroPeople++
}
if person.Name == "" {
result.MissingNames++
}
if f.Region != "" && f.Region != person.Region && f.Region != person.State {
continue
}
if !monthlyHasDepartment(person, f.Department, parents) {
continue
}
if f.Activity == "used" && n.Total == 0 || f.Activity == "zero" && n.Total > 0 {
continue
}
if search != "" && !strings.Contains(strings.ToLower(person.Name), search) && !strings.Contains(strings.ToLower(strings.Join(person.Departments, ";")), search) {
continue
}
// This is a stable row key, not an anonymisation claim or a new user identifier.
sum := sha256.Sum256([]byte(p.Metadata.DirectoryID + "\x00" + person.PersonID))
rows = append(rows, monthlyPerson{Key: "person-" + hex.EncodeToString(sum[:]), Name: person.Name, State: person.State, Region: person.Region, Departments: person.Departments, Questions: n.Total, Succeeded: n.Succeeded, Failed: n.Failed, Other: n.Total - n.Succeeded - n.Failed})
}
sort.Slice(rows, func(i, j int) bool {
a, b := rows[i], rows[j]
if a.Name == "" && b.Name != "" {
return false
}
if a.Name != "" && b.Name == "" {
return true
}
if a.Name != b.Name {
return a.Name < b.Name
}
return a.Key < b.Key
})
result.Total = len(rows)
start := (f.Page - 1) * f.Limit
if start < len(rows) {
end := min(start+f.Limit, len(rows))
result.Rows = rows[start:end]
result.HasMore = end < len(rows)
}
return result
}
// Names remain in the bounded read-query body, not URLs/access logs. The source
// reader and governance store are still strictly read-only on this route.
func monthlyRequestValues(w http.ResponseWriter, r *http.Request) (url.Values, error) {
values := url.Values{}
if r.URL.RawQuery != "" || r.Header.Get("X-Governance-Action") != "qa-usage-read" {
return nil, dobotaiops.ErrInvalidQuery
}
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8192))
token, err := decoder.Token()
if err != nil || token != json.Delim('{') {
return nil, dobotaiops.ErrInvalidQuery
}
for decoder.More() {
token, err = decoder.Token()
key, ok := token.(string)
if err != nil || !ok || values.Has(key) {
return nil, dobotaiops.ErrInvalidQuery
}
var raw json.RawMessage
if decoder.Decode(&raw) != nil || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
return nil, dobotaiops.ErrInvalidQuery
}
if key == "page" || key == "limit" {
var n int
if json.Unmarshal(raw, &n) != nil {
return nil, dobotaiops.ErrInvalidQuery
}
values.Set(key, strconv.Itoa(n))
} else {
var text string
if json.Unmarshal(raw, &text) != nil {
return nil, dobotaiops.ErrInvalidQuery
}
values.Set(key, text)
}
}
if _, err = decoder.Token(); err != nil {
return nil, dobotaiops.ErrInvalidQuery
}
var extra any
if decoder.Decode(&extra) != io.EOF {
return nil, dobotaiops.ErrInvalidQuery
}
return values, nil
}
func qaMonthlyPeople(w http.ResponseWriter, r *http.Request, config Config) {
if !authorizeQAOps(w, r) {
return
}
values, err := monthlyRequestValues(w, r)
if err != nil {
qaOpsError(w, err)
return
}
f, err := parseMonthlyFilter(values, config.Now())
if err != nil {
qaOpsError(w, err)
return
}
p, err := recordAttribution(r.Context(), config)
if err != nil {
qaOpsError(w, err)
return
}
if p.Metadata.State != "ready" {
writeJSON(w, 409, map[string]string{"code": "directory_missing", "error": "尚无完整通讯录,请先从区域使用页同步;不能生成零记录人员名单"})
return
}
if values.Has("directory_id") || values.Has("revision_id") {
if !values.Has("directory_id") || !values.Has("revision_id") {
qaOpsError(w, dobotaiops.ErrInvalidQuery)
return
}
if values.Get("directory_id") != p.Metadata.DirectoryID || values.Get("revision_id") != p.Metadata.RevisionID {
writeJSON(w, 409, map[string]string{"code": "organization_changed", "error": "通讯录或区域配置已变化,请重新查询个人月明细"})
return
}
}
if f.Department != "" {
found := false
for _, d := range p.Metadata.View.Departments {
found = found || d.ID == f.Department
}
if !found {
qaOpsError(w, dobotaiops.ErrInvalidQuery)
return
}
}
reader, ok := config.QAOps.(qaUsageReader)
if !ok || config.QAOpsTenantKey == "" {
qaOpsError(w, dobotaiops.ErrUnavailable)
return
}
groups, err := reader.ReadUsageGroups(r.Context(), dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: config.QAOpsTenantKey, Start: f.Start, End: f.End}})
if err != nil {
qaOpsError(w, err)
return
}
writeJSON(w, 200, map[string]any{"data": monthlyResult(groups, p, f)})
}
+221
View File
@@ -0,0 +1,221 @@
package httpapi
import (
"bytes"
"context"
"encoding/json"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qaopsorg"
"net/http"
"net/http/httptest"
"strconv"
"net/url"
"strings"
"testing"
"time"
)
type monthlyReaderSpy struct {
attributedReader
query dobotaiops.RecordQuery
calls int
}
func (s *monthlyReaderSpy) ReadUsageGroups(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.UsageGroups, error) {
s.calls++
s.query = q
return s.attributedReader.ReadUsageGroups(ctx, q)
}
func monthlyRequest(h http.Handler, path, token string) *httptest.ResponseRecorder {
u, _ := url.Parse(path)
body := map[string]any{}
for k, v := range u.Query() {
if len(v) != 1 {
body[k] = v
continue
}
if k == "page" || k == "limit" {
if n, e := strconv.Atoi(v[0]); e == nil {
body[k] = n
} else {
body[k] = v[0]
}
} else {
body[k] = v[0]
}
}
raw, _ := json.Marshal(body)
r := httptest.NewRequest(http.MethodPost, u.Path, bytes.NewReader(raw))
r.Header.Set("Content-Type", "application/json")
r.Header.Set("X-Governance-Action", "qa-usage-read")
if token != "" {
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token})
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
func monthlyHandler(t *testing.T) (http.Handler, *attributionOrgSpy, *monthlyReaderSpy) {
t.Helper()
d := qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "root", Name: "示例根"}, {ID: "child", ParentID: "root", Name: "子部门"}}, People: []qaopsorg.Person{{ID: "fixture-private-staff", Name: "同名示例", UnionID: "fixture-private-union", DepartmentIDs: []string{"root"}}, {ID: "private-zero", Name: "同名示例", DepartmentIDs: []string{"child"}}, {ID: "private-cross", Name: "跨区域示例", DepartmentIDs: []string{"root", "child"}}, {ID: "private-unnamed", DepartmentIDs: []string{"child"}}}}
now := time.Date(2026, 10, 17, 8, 0, 0, 0, time.UTC)
p, err := qaopsorg.BuildAttribution(qaopsorg.State{State: "ready", DirectoryID: "monthly-directory", DirectorySource: "weekly_report_live", DirectorySyncedAt: &now, RevisionID: "monthly-regions", Rules: []qaopsorg.Rule{{DepartmentID: "root", Region: "国内工业"}, {DepartmentID: "child", Region: "APAC"}}}, d)
if err != nil {
t.Fatal(err)
}
org := &attributionOrgSpy{projection: p}
reader := &monthlyReaderSpy{}
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: reader, QAOpsTenantKey: "fixed", QAOrg: org, Now: func() time.Time { return now }})
if err != nil {
t.Fatal(err)
}
return h, org, reader
}
func TestQAMonthlyPeopleIncludesZeroUseAndKeepsUnresolvedEvents(t *testing.T) {
h, _, reader := monthlyHandler(t)
path := "/api/v1/qa-ops/usage/people?month=2026-10&limit=2"
w := monthlyRequest(h, path, "attribution-admin")
if w.Code != 200 {
t.Fatal(w.Code, w.Body.String())
}
var result struct {
Data struct {
Month string
Timezone string
Partial bool
Questions int64
LinkedQuestions int64 `json:"linked_questions"`
UnresolvedQuestions int64 `json:"unresolved_questions"`
RosterPeople int `json:"roster_people"`
UsedPeople int `json:"used_people"`
ZeroPeople int `json:"zero_people"`
MissingNames int `json:"missing_names"`
Total int
HasMore bool `json:"has_more"`
Rows []struct {
Key string
Name string
Questions int64
State string
}
}
}
if json.Unmarshal(w.Body.Bytes(), &result) != nil {
t.Fatal("invalid monthly JSON")
}
v := result.Data
if v.Month != "2026-10" || v.Timezone != "Asia/Shanghai" || !v.Partial || v.Questions != 7 || v.LinkedQuestions != 5 || v.UnresolvedQuestions != 2 || v.RosterPeople != 4 || v.UsedPeople != 1 || v.ZeroPeople != 3 || v.MissingNames != 1 || v.Total != 4 || len(v.Rows) != 2 || !v.HasMore {
t.Fatal("monthly roster, zero count or alias dedup wrong", w.Body.String())
}
if reader.query.Window.TenantKey != "fixed" || reader.query.Window.Start.Format(time.RFC3339) != "2026-10-01T00:00:00+08:00" || reader.query.Window.End.Format(time.RFC3339) != "2026-10-17T16:00:00+08:00" {
t.Fatal("month was not normalized to the named timezone")
}
if strings.Contains(w.Body.String(), "private-") || strings.Contains(w.Body.String(), "performance") || strings.Contains(w.Body.String(), "staff_id") {
t.Fatal("raw identities or unapproved verdict exposed")
}
page2 := monthlyRequest(h, path+"&page=2&directory_id=monthly-directory&revision_id=monthly-regions", "attribution-admin")
if page2.Code != 200 {
t.Fatal(page2.Body.String())
}
for _, extra := range []string{"&activity=zero", "&region=cross_region", "&department_id=child", "&search=" + url.QueryEscape("子部门")} {
r := monthlyRequest(h, "/api/v1/qa-ops/usage/people?month=2026-10"+extra, "attribution-admin")
if r.Code != 200 {
t.Fatal("valid monthly filter failed", r.Body.String())
}
}
}
func TestQAMonthlyScopeAndVersionFailClosed(t *testing.T) {
h, org, reader := monthlyHandler(t)
base := "/api/v1/qa-ops/usage/people?month=2026-10"
for _, tc := range []struct {
suffix, token string
status int
}{{"", "", 401}, {"", "attribution-viewer", 403}, {"&tenant=forged", "attribution-admin", 400}, {"&threshold=5", "attribution-admin", 400}, {"&month=duplicate", "attribution-admin", 400}, {"&page=0", "attribution-admin", 400}, {"&limit=101", "attribution-admin", 400}, {"&activity=under5", "attribution-admin", 400}, {"&region=invalid", "attribution-admin", 400}, {"&department_id=invalid", "attribution-admin", 400}, {"&page=2", "attribution-admin", 400}, {"&page=2&directory_id=changed&revision_id=monthly-regions", "attribution-admin", 409}, {"&cutoff=2026-11-01T00:00:00Z", "attribution-admin", 400}} {
w := monthlyRequest(h, base+tc.suffix, tc.token)
if w.Code != tc.status {
t.Fatalf("monthly %s: %d want %d", tc.suffix, w.Code, tc.status)
}
}
for _, month := range []string{"2026-1", " 2026-10", "2026-13", "0000-01", "2026-11"} {
r := monthlyRequest(h, "/api/v1/qa-ops/usage/people?month="+url.QueryEscape(month), "attribution-admin")
if r.Code != 400 {
t.Fatal("invalid/future month accepted")
}
}
if reader.calls != 0 {
t.Fatal("invalid or unauthorized monthly request reached source")
}
org.projection, _ = qaopsorg.BuildAttribution(qaopsorg.State{State: "empty"}, qaopsorg.Directory{})
if w := monthlyRequest(h, base, "attribution-admin"); w.Code != 409 {
t.Fatal("no roster presented as zero-use list")
}
org.err = qaopsorg.ErrUnavailable
if w := monthlyRequest(h, base, "attribution-admin"); w.Code != 503 {
t.Fatal("store failure hidden as empty")
}
}
func TestQAMonthlyPersonFiltersDoNotGuessNamesOrDuplicateDescendantMembers(t *testing.T) {
h, _, _ := monthlyHandler(t)
for _, tc := range []struct {
filter string
total int
}{{"&activity=used", 1}, {"&activity=zero", 3}, {"&region=cross_region", 1}, {"&region=APAC", 2}, {"&department_id=child", 3}, {"&department_id=root", 4}, {"&search=" + url.QueryEscape("同名示例"), 2}, {"&search=" + url.QueryEscape("子部门"), 3}, {"&search=%25_", 0}} {
w := monthlyRequest(h, "/api/v1/qa-ops/usage/people?month=2026-10"+tc.filter, "attribution-admin")
var payload struct{ Data monthlyPeople }
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &payload) != nil || payload.Data.Total != tc.total || payload.Data.Questions != 7 {
t.Fatal("person-scope filter did not preserve source totals or person dedup", tc.filter)
}
for _, r := range payload.Data.Rows {
if tc.filter == "&activity=zero" && r.Questions != 0 {
t.Fatal("used member labeled zero")
}
}
}
}
func TestQAMonthlyReadBodyRejectsDuplicateNullTrailingAndOversizedInput(t *testing.T) {
h, _, reader := monthlyHandler(t)
for _, body := range []string{`{"month":"2026-10","month":"2026-10"}`, `{"month":"2026-10","search":null}`, `{"month":"2026-10","page":"1"}`, `{"month":"2026-10"}{}`, `[]`, `{"month":"2026-10","search":"` + strings.Repeat("x", 9000) + `"}`} {
r := httptest.NewRequest("POST", "/api/v1/qa-ops/usage/people", strings.NewReader(body))
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "attribution-admin"})
r.Header.Set("X-Governance-Action", "qa-usage-read")
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
if w.Code != 400 {
t.Fatal("invalid read body reached source", w.Code)
}
}
for _, method := range []string{"POST", "GET"} {
r := httptest.NewRequest(method, "/api/v1/qa-ops/usage/people?search=sensitive-example", strings.NewReader(`{"month":"2026-10"}`))
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "attribution-admin"})
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
if w.Code != 400 && w.Code != 405 {
t.Fatal("URL-based name query accepted")
}
}
if reader.calls != 0 {
t.Fatal("invalid body read production source")
}
}
func TestQAMonthlyPastLeapMonthUsesClosedCalendarWindow(t *testing.T) {
h, _, reader := monthlyHandler(t)
w := monthlyRequest(h, "/api/v1/qa-ops/usage/people?month=2024-02", "attribution-admin")
if w.Code != 200 {
t.Fatal(w.Body.String())
}
if reader.query.Window.End.Format(time.RFC3339) != "2024-03-01T00:00:00+08:00" || reader.query.Window.End.Sub(reader.query.Window.Start) != 29*24*time.Hour {
t.Fatal("leap month boundary incorrect")
}
var raw struct{ Data struct{ Partial bool } }
_ = json.Unmarshal(w.Body.Bytes(), &raw)
if raw.Data.Partial {
t.Fatal("past natural month mislabeled as current progress")
}
}
+16
View File
@@ -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"
+2
View File
@@ -175,6 +175,8 @@ func NewHandler(config Config) (http.Handler, error) {
config.NewID = newID
}
mux := http.NewServeMux()
mux.HandleFunc("POST /api/v1/qa-ops/usage/people", func(w http.ResponseWriter, r *http.Request) { qaMonthlyPeople(w, r, config) })
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) })
+123
View File
@@ -0,0 +1,123 @@
package qaopsorg
import (
"context"
"sort"
)
type PersonAttribution struct {
Name string `json:"name"`
DepartmentIDs []string `json:"-"`
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 (p *Attribution) Members() []PersonAttribution {
result := []PersonAttribution{}
if p == nil {
return result
}
for _, person := range p.people {
result = append(result, person)
}
sort.Slice(result, func(i, j int) bool { return result[i].PersonID < result[j].PersonID })
return result
}
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{Name: person.Name, DepartmentIDs: append([]string{}, person.DepartmentIDs...), 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)
}
+46
View File
@@ -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")
}
}
+30
View File
@@ -0,0 +1,30 @@
package qaopsorg
import (
"encoding/json"
"strings"
"testing"
)
func TestMembersKeepNamedAndUnnamedRosterPeopleWithoutRawIdentifiers(t *testing.T) {
d := Directory{Departments: []Department{{ID: "root", Name: "fixture"}}, People: []Person{{ID: "private-a", Name: "<源端姓名>", UnionID: "private-union", DepartmentIDs: []string{"root"}}, {ID: "private-zero", DepartmentIDs: []string{"root"}}}}
p, err := BuildAttribution(State{State: "ready", DirectoryID: "directory"}, d)
if err != nil {
t.Fatal(err)
}
members := p.Members()
if len(members) != 2 {
t.Fatal("zero-use roster member omitted")
}
if p.Resolve("private-a", "").Name != "<源端姓名>" || p.Resolve("private-zero", "").Name != "" {
t.Fatal("display name lost or guessed")
}
raw, _ := json.Marshal(members)
if strings.Contains(string(raw), "private-") || strings.Contains(string(raw), "department_ids") {
t.Fatal("internal identifiers serialized")
}
d.People[0].Name = "bad\x00name"
if _, err = BuildAttribution(State{State: "ready", DirectoryID: "directory"}, d); err == nil {
t.Fatal("invalid display name accepted")
}
}
+2 -1
View File
@@ -15,6 +15,7 @@ type Department struct {
Name string `json:"name"`
}
type Person struct {
Name string `json:"name,omitempty"`
ID string `json:"id"`
UnionID string `json:"union_id,omitempty"`
DepartmentIDs []string `json:"department_ids"`
@@ -107,7 +108,7 @@ func Preview(directory Directory, rules []Rule) (PreviewResult, error) {
}
people := map[string]bool{}
for _, person := range directory.People {
if !validID(person.ID) || people[person.ID] || len(person.DepartmentIDs) > 1000 {
if !validID(person.ID) || people[person.ID] || len(person.DepartmentIDs) > 1000 || len(person.Name) > 1000 || strings.ContainsRune(person.Name, 0) {
return result, ErrInvalid
}
people[person.ID] = true
@@ -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)
}
+4 -1
View File
@@ -36,6 +36,9 @@ def _validate_directory(departments, people):
seen.add(current)
current = int(departments[current].get('parent_id') or 0)
for identity, person in people.items():
name = person.get('name')
if name is not None and (not isinstance(name, str) or len(name.encode('utf-8')) > 1000 or '\x00' in name):
raise DirectorySyncError('directory_integrity_failed')
if not identity or str(person.get('user_id') or '') != str(identity):
raise DirectorySyncError('directory_integrity_failed')
if not person.get('department_ids') or any(int(d) not in departments for d in person['department_ids']):
@@ -78,7 +81,7 @@ def collect_directory(client, fetch_departments, fetch_users, get_detail, logger
# List membership provides stable staff IDs; do not reuse the old
# guessed primary department, employment policy or openId fallback.
'people': [
{'id': str(identity), 'union_id': str((p.get('raw_payload') or {}).get('unionid') or (p.get('raw_payload') or {}).get('unionId') or ''), 'department_ids': [str(d) for d in sorted(p['department_ids'])]}
{'id': str(identity), **({'name': p['name']} if p.get('name') else {}), 'union_id': str((p.get('raw_payload') or {}).get('unionid') or (p.get('raw_payload') or {}).get('unionId') or ''), 'department_ids': [str(d) for d in sorted(p['department_ids'])]}
for identity, p in sorted(people.items())
],
},
+2
View File
@@ -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",
+7
View File
@@ -24,6 +24,13 @@ def root_detail(client,logger,department_id):
return {'id':department_id,'parent_id':0,'name':'真实源端返回的示例根部门'},False,False
class DirectoryBridgeTests(unittest.TestCase):
def test_real_display_name_is_retained_without_guessing_or_requiring_it(self):
def users(*args,**kwargs):
return {'u':{'user_id':'u','name':'<示例员工>','department_ids':{10},'raw_payload':{}}},set(),set()
result=sync.collect_directory(FakeClient(),full_departments,users,root_detail,logging.getLogger('fixture'))
self.assertEqual(result['directory']['people'][0].get('name'),'<示例员工>')
result=sync.collect_directory(FakeClient(),full_departments,full_users,root_detail,logging.getLogger('fixture'))
self.assertNotIn('name',result['directory']['people'][0])
def test_fetches_the_real_missing_root_and_preserves_stable_identities(self):
result=sync.collect_directory(FakeClient(),full_departments,full_users,root_detail,logging.getLogger('fixture'))
self.assertTrue(result['complete'])
+37
View File
@@ -0,0 +1,37 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, it, expect } from 'vitest'
import { QAMonthlyView } from './QAMonthly'
import { monthlyFixture } from './qaMonthly.fixture'
import { parseQAMonthly } from './qaMonthly'
describe('personal monthly view', () => {
it('shows a partial month as progress, escapes source names and does not imply eligibility', () => {
const html = renderToStaticMarkup(
<QAMonthlyView
data={parseQAMonthly(monthlyFixture)}
loading={false}
error=""
onRetry={() => {}}
onPage={() => {}}
/>
)
for (const text of ['本源零记录', '当月进度', '姓名未同步', '不是考核名单', '当前通讯录', '未关联'])
expect(html).toContain(text)
expect(html).not.toContain('<script>')
expect(html).not.toContain('达标率')
expect(html).not.toContain('绩效合格')
})
it('does not display stale rows or fake zeros on errors', () => {
const html = renderToStaticMarkup(
<QAMonthlyView
data={parseQAMonthly(monthlyFixture)}
loading={false}
error="统计不可用"
onRetry={() => {}}
onPage={() => {}}
/>
)
expect(html).toContain('统计不可用')
expect(html).not.toContain('<table')
expect(html).not.toContain('共 0')
})
})
+252
View File
@@ -0,0 +1,252 @@
import { useEffect, useState } from 'react'
import type { FormEvent } from 'react'
import { beijingMonth, fetchQAMonthly } from './qaMonthly'
import type { MonthlyPeople, MonthlyQuery } from './qaMonthly'
import { usageLabels } from './qaUsage'
const stamp = (v: string) => new Date(v).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
interface ViewProps {
data: MonthlyPeople | null
loading: boolean
error: string
onRetry: () => void
onPage: (page: number) => void
}
export function QAMonthlyView({ data, loading, error, onRetry, onPage }: ViewProps) {
return (
<section className="qa-ops-results qa-monthly-results" aria-label="个人月度使用明细">
{loading ? (
<p className="qa-ops-muted" role="status">
正在读取个人月明细…
</p>
) : null}
{error ? (
<div className="error-banner" role="alert">
{error}{' '}
<button type="button" onClick={onRetry} disabled={loading}>
重新查询
</button>
</div>
) : null}
{data && !loading && !error ? (
<>
<div className="qa-ops-result-bar">
<strong>
{data.month} · {data.partial ? '当月进度 / 截止时点' : '完整自然月时间范围'}
</strong>
<span>仅 DobotAI 2.0 · 北京时间</span>
</div>
<p className="qa-ops-muted">
全名册:{data.roster_people} 人 · 已关联提问 {data.used_people} 人 · 本源零记录 {data.zero_people}{' '}
人。名册来自当前通讯录,不是在职证明,也不是考核名单。
</p>
<p className="qa-ops-muted">
本月范围内 {data.questions} 条问答,已关联 {data.linked_questions} 条,未关联 {data.unresolved_questions}{' '}
条。0 仅表示本源未关联到提问,不等于实际未使用;成功/失败不是答案正确性结论。
</p>
{data.missing_names > 0 ? (
<p className="qa-ops-warning">
{data.missing_names} 人姓名未同步,请重新同步通讯录;不根据姓名猜身份,不用原始标识代替姓名。
</p>
) : null}
<details className="qa-ops-organization">
<summary>统计范围与组织版本</summary>
<p>
范围:{stamp(data.start)} 至 {stamp(data.end)}(不含结束)。当前通讯录同步于{' '}
{stamp(data.organization.synced_at!)}
;不代表提问时部门或正式绩效分母。自然月时间范围完整不代表已归档全部历史。目录:
{data.organization.directory_id};区域:{data.organization.revision_id || '未保存'}。
</p>
</details>
<div className="qa-ops-result-bar">
<span>
符合人员筛选 {data.total} 人 · 第 {data.page} 页
</span>
<span>上方全名册指标不随人员筛选变化</span>
</div>
{data.rows.length ? (
<div className="qa-ops-table-scroll" aria-label="个人月明细表格滚动区" tabIndex={0}>
<table className="qa-ops-table qa-monthly-table">
<thead>
<tr>
{['姓名', '当前部门完整路径', '区域 / 待核对状态', '问答次数', '成功', '失败', '其他'].map((v) => (
<th key={v}>{v}</th>
))}
</tr>
</thead>
<tbody>
{data.rows.map((row) => (
<tr key={row.key}>
<td>{row.name || '姓名未同步'}</td>
<td>{row.departments.join(';') || '无部门记录'}</td>
<td>{usageLabels[row.region || row.state]}</td>
<td>{row.questions}</td>
<td>{row.succeeded}</td>
<td>{row.failed}</td>
<td>{row.other}</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<p className="qa-ops-empty">没有符合人员筛选的记录,请调整条件;这不是通讯录为空。</p>
)}
<footer className="qa-ops-page-bar">
<span>本次读取:{stamp(data.as_of)}</span>
<div>
{data.page > 1 ? (
<button type="button" onClick={() => onPage(data.page - 1)}>
上一页
</button>
) : null}
{data.has_more ? (
<button type="button" onClick={() => onPage(data.page + 1)}>
下一页
</button>
) : null}
</div>
</footer>
</>
) : null}
</section>
)
}
export function QAMonthly() {
const [draft, setDraft] = useState(() => ({
month: beijingMonth(),
cutoff: '',
region: '',
department_id: '',
activity: 'all',
search: '',
}))
const [request, setRequest] = useState<MonthlyQuery>({ month: draft.month })
const [data, setData] = useState<MonthlyPeople | null>(null),
[options, setOptions] = useState<MonthlyPeople['department_options']>([]),
[loading, setLoading] = useState(false),
[error, setError] = useState('')
useEffect(() => {
const controller = new AbortController()
setLoading(true)
setData(null)
setError('')
fetchQAMonthly(request, controller.signal)
.then((next) => {
if (!controller.signal.aborted) {
setData(next)
setOptions(next.department_options)
}
})
.catch((reason) => {
if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : '个人月明细读取失败')
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false)
})
return () => controller.abort()
}, [request])
const change = (key: keyof typeof draft, value: string) => {
setDraft({ ...draft, [key]: value })
setData(null)
setError('')
}
const query = () => {
try {
setRequest({
...draft,
cutoff: draft.cutoff ? new Date(draft.cutoff + '+08:00').toISOString() : undefined,
page: 1,
})
} catch {
setData(null)
setError('截止时间无效,请按北京时间填写')
}
}
const submit = (event: FormEvent) => {
event.preventDefault()
query()
}
const page = (n: number) => {
if (data)
setRequest({
...request,
cutoff: data.end,
page: n,
directory_id: data.organization.directory_id,
revision_id: data.organization.revision_id,
})
}
return (
<>
<form className="qa-ops-query qa-monthly-query" onSubmit={submit} aria-label="个人月明细筛选">
<label>
自然月(北京时间)
<input
type="month"
required
value={draft.month}
disabled={loading}
onChange={(e) => change('month', e.target.value)}
/>
</label>
<label>
截止时间(可留空)
<input
type="datetime-local"
value={draft.cutoff}
disabled={loading}
onChange={(e) => change('cutoff', e.target.value)}
/>
</label>
<label>
区域 / 状态
<select value={draft.region} disabled={loading} onChange={(e) => change('region', e.target.value)}>
<option value="">全部区域 / 状态</option>
{['国内工业', 'APAC', 'EMEA', 'America', 'unassigned', 'cross_region'].map((key) => (
<option key={key} value={key}>
{usageLabels[key]}
</option>
))}
</select>
</label>
<label>
部门(含子部门)
<select
value={draft.department_id}
disabled={loading}
onChange={(e) => change('department_id', e.target.value)}
>
<option value="">全部部门</option>
{options.map((d) => (
<option value={d.id} key={d.id}>
{d.path}
</option>
))}
</select>
</label>
<label>
使用记录
<select value={draft.activity} disabled={loading} onChange={(e) => change('activity', e.target.value)}>
<option value="all">全部人员</option>
<option value="used">已关联提问</option>
<option value="zero">本源零记录</option>
</select>
</label>
<label>
姓名 / 部门路径
<input
type="search"
maxLength={100}
value={draft.search}
disabled={loading}
onChange={(e) => change('search', e.target.value)}
/>
</label>
<button type="submit" disabled={loading}>
查询个人月明细
</button>
</form>
<QAMonthlyView data={data} loading={loading} error={error} onRetry={query} onPage={page} />
</>
)
}
+94 -31
View File
@@ -1,10 +1,13 @@
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 { QAMonthly } from './QAMonthly'
import { usageLabels } from './qaUsage'
interface ViewProps {
page: QARecordPage | null
@@ -48,6 +51,13 @@ export function QAOperationsView(props: ViewProps) {
DobotAI 2.0 / 钉钉 · 独立只读连接{props.status ? ` · ${stateLabels[props.status.state]}` : ''}
</span>
</div>
{page?.organization ? (
<p className="qa-ops-muted qa-ops-organization">
{page.organization.state === 'ready'
? `缺失组织信息按当前通讯录补全(${stamp(page.organization.synced_at!)}),不代表提问时归属。目录:${page.organization.directory_id};区域版本:${page.organization.revision_id || '未保存'}`
: '尚无完整通讯录,仅展示源端已有组织快照,不根据姓名推断。'}
</p>
) : null}
{props.status?.warnings.map((warning) => (
<p className="qa-ops-warning" key={warning}>
{warningLabels[warning] ?? '数据源有待审核的安全告警'}
@@ -79,7 +89,9 @@ export function QAOperationsView(props: ViewProps) {
<td
key={key}
className={
key === 'answer' || key === 'question' || key === 'question_chinese' ? 'qa-ops-text-cell' : ''
key === 'answer' || key === 'question' || key === 'question_chinese' || key === 'department'
? 'qa-ops-text-cell'
: ''
}
>
<span
@@ -174,6 +186,40 @@ export function QAOperationsView(props: ViewProps) {
</dd>
<dt>提问人</dt>
<dd>{detail.asker || '未关联'}</dd>
<dt>部门</dt>
<dd>
{detail.department || '未匹配'}
{detail.organization?.department_origin === 'current_directory' ? '(当前通讯录补全)' : ''}
</dd>
<dt>区域</dt>
<dd>
{detail.region || '未配置/待核对'}
{detail.organization?.region_origin === 'current_directory' ? '(当前配置补全)' : ''}
</dd>
{detail.organization ? (
<>
<dt>当前组织关联</dt>
<dd>
{detail.organization.state === 'matched'
? '已关联'
: (usageLabels[detail.organization.state] ?? detail.organization.state)}
</dd>
<dt>当前通讯录部门/区域</dt>
<dd>
{detail.organization.departments.join(';') || '未匹配'} /{' '}
{detail.organization.region || '未配置或待核对'}
</dd>
<dt>组织版本</dt>
<dd>
{detail.organization.version.directory_id || '无完整目录'} /{' '}
{detail.organization.version.revision_id || '未保存区域配置'}
</dd>
<dt>源端组织快照</dt>
<dd>
{detail.organization.source_department || '空'} / {detail.organization.source_region || '空'}
</dd>
</>
) : null}
<dt>问答状态</dt>
<dd>{statusLabels[detail.status] ?? detail.status}</dd>
<dt>流程触发人员信息</dt>
@@ -230,7 +276,8 @@ function initialDraft() {
}
export function QAOperations() {
const [view, setView] = useState<'records' | 'regions'>('records')
const [view, setView] = useState<'records' | 'regions' | 'usage'>('records')
const [usageMode, setUsageMode] = useState<'regions' | 'monthly'>('regions')
const auth = useOptionalAuth()
const canRead = auth?.identity?.role === 'admin'
const [draft, setDraft] = useState(initialDraft)
@@ -260,6 +307,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 +340,7 @@ export function QAOperations() {
if (!controller.signal.aborted) setLoading(false)
})
return () => controller.abort()
}, [query, canRead, revision])
}, [query, canRead, revision, view])
useEffect(
() => () => {
@@ -341,17 +395,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 +408,7 @@ export function QAOperations() {
<section className="qa-ops" aria-label="问答运营">
<header className="qa-ops-header">
<h2>
问答运营 <span>/ {view === 'regions' ? '区域归属' : '问答记录'}</span>
问答运营 <span>/ {view === 'regions' ? '区域归属' : view === 'usage' ? '使用统计' : '问答记录'}</span>
</h2>
<p>真实问答只读查询;原始记录、源端判断与治理复检分开保留。</p>
</header>
@@ -378,11 +422,26 @@ export function QAOperations() {
<button type="button" aria-pressed={view === 'records'} onClick={() => setView('records')}>
问答记录
</button>
<button type="button" aria-pressed={view === 'usage'} onClick={() => setView('usage')}>
使用统计
</button>
<button type="button" aria-pressed={view === 'regions'} onClick={() => setView('regions')}>
区域使用
</button>
</nav>
{view === 'regions' ? (
{view === 'usage' ? (
<nav className="qa-region-tabs" aria-label="使用统计视图">
<button type="button" aria-pressed={usageMode === 'regions'} onClick={() => setUsageMode('regions')}>
区域汇总
</button>
<button type="button" aria-pressed={usageMode === 'monthly'} onClick={() => setUsageMode('monthly')}>
个人月明细
</button>
</nav>
) : null}
{view === 'usage' && usageMode === 'monthly' ? (
<QAMonthly />
) : view === 'regions' ? (
<QARegions />
) : (
<>
@@ -420,21 +479,25 @@ export function QAOperations() {
</button>
</form>
<p className="qa-ops-slice-note">
当前切片:问答查询与覆盖复检。外语翻译、AI评估及人员映射尚未接入;空值不默认填“否”。
部门/区域保留源快照,缺失时按当前通讯录补全;使用统计不是绩效结论。外语翻译与AI评估仍暂缓,空值不默认填“否”。
</p>
<QAOperationsView
page={page}
status={status}
error={error}
loading={loading}
detail={detail}
detailLoading={detailLoading}
detailError={detailError}
onSelect={(id) => void select(id)}
onCloseDetail={close}
onLoadMore={() => void loadMore()}
onRetry={() => setRevision((value) => value + 1)}
/>
{view === 'usage' ? (
<QAUsage query={query} />
) : (
<QAOperationsView
page={page}
status={status}
error={error}
loading={loading}
detail={detail}
detailLoading={detailLoading}
detailError={detailError}
onSelect={(id) => void select(id)}
onCloseDetail={close}
onLoadMore={() => void loadMore()}
onRetry={() => setRevision((value) => value + 1)}
/>
)}
</>
)}
</>
+36
View File
@@ -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(<QAUsageView data={usage} loading={false} error="" onRetry={() => {}} />)
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(<QAUsageView data={null} loading={false} error="上游不可用" onRetry={() => {}} />)
expect(html).toContain('上游不可用')
expect(html).not.toContain('共 0 条')
})
})
+105
View File
@@ -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 (
<section className="qa-ops-results" aria-label="使用统计">
<p className="qa-ops-slice-note">
按当前通讯录回看历史问答,不代表提问时的组织归属。成功/失败是源端运行状态,不等于答案正确;不输出绩效结论。
</p>
{loading ? <p role="status">正在读取完整筛选范围的使用统计…</p> : null}
{error ? (
<p className="error-banner" role="alert">
{error}{' '}
<button type="button" onClick={onRetry} disabled={loading}>
重试统计
</button>
</p>
) : null}
{data && !error ? (
<>
<div className="qa-ops-result-bar">
<span>
共 {data.questions} 条问答 · 已关联提问人数 {data.identified_users}
</span>
<span>统计截止读取时间:{stamp(data.as_of)}</span>
</div>
<p className="qa-ops-muted qa-ops-organization">
范围:{stamp(data.start)} 至 {stamp(data.end)}(不含结束时刻)
{data.keyword ? ` · 原问题包含:${data.keyword}` : ''}
</p>
<p className="qa-ops-muted qa-ops-organization">
{data.organization.state === 'ready'
? `通讯录同步:${stamp(data.organization.synced_at!)} · 目录 ${data.organization.directory_id} · 区域配置 ${data.organization.revision_id || '尚未保存'}`
: '尚无完整通讯录,当前不能确定部门区域或去重人数。'}
</p>
<div className="qa-ops-table-scroll" tabIndex={0} aria-label="使用统计表格滚动区">
<table className="qa-ops-table qa-usage-table">
<thead>
<tr>
<th>区域/待核对状态</th>
<th>问答条数</th>
<th>成功</th>
<th>失败</th>
<th>其他状态</th>
<th>已关联提问人数</th>
<th>通讯录归属人数</th>
</tr>
</thead>
<tbody>
{data.rows.map((row) => (
<tr key={row.key}>
<td>{usageLabels[row.key]}</td>
<td>{row.questions}</td>
<td>{row.succeeded}</td>
<td>{row.failed}</td>
<td>{row.other}</td>
<td>{row.users ?? '不可确定'}</td>
<td>{row.roster_people ?? '不适用'}</td>
</tr>
))}
</tbody>
</table>
</div>
<p className="qa-ops-muted qa-ops-organization">
按问答唯一 ID 计次;同一名册人员的多部门、多个身份记录只计 1
人。未匹配或身份冲突不编造人数;通讯录人数不是在职或考核人数。
</p>
</>
) : null}
</section>
)
}
export function QAUsage({ query }: { query: QAQuery | null }) {
const [data, setData] = useState<Usage | null>(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 <QAUsageView data={data} loading={loading} error={error} onRetry={() => setRevision((v) => v + 1)} />
}
+50
View File
@@ -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()
})
})
+54
View File
@@ -0,0 +1,54 @@
export const monthlyFixture = {
organization: {
state: 'ready',
directory_id: 'd',
directory_source: 'weekly_report_live',
synced_at: '2026-10-17T07:59:50Z',
revision_id: 'r',
basis: 'current_directory',
},
source: '2.0',
timezone: 'Asia/Shanghai',
month: '2026-10',
start: '2026-10-01T00:00:00+08:00',
end: '2026-10-17T16:00:00+08:00',
month_end: '2026-11-01T00:00:00+08:00',
as_of: '2026-10-17T08:00:01Z',
partial: true,
questions: 3,
linked_questions: 2,
unresolved_questions: 1,
roster_people: 2,
used_people: 1,
zero_people: 1,
missing_names: 1,
total: 2,
page: 1,
limit: 30,
has_more: false,
department_options: [{ id: 'root', path: '示例部门' }],
rows: [
{
key: 'person-a',
name: '<script>示例姓名</script>',
departments: ['示例部门'],
region: 'APAC',
state: 'matched',
questions: 2,
succeeded: 1,
failed: 1,
other: 0,
},
{
key: 'person-b',
name: '',
departments: ['示例部门'],
region: '',
state: 'unassigned',
questions: 0,
succeeded: 0,
failed: 0,
other: 0,
},
],
}
+37
View File
@@ -0,0 +1,37 @@
import { describe, it, expect, vi } from 'vitest'
import { parseQAMonthly, fetchQAMonthly, beijingMonth } from './qaMonthly'
import { monthlyFixture } from './qaMonthly.fixture'
describe('personal natural-month contracts', () => {
it('sends personnel filters only in a same-origin no-store read body', async () => {
const fake = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: monthlyFixture }), { status: 200 }))
vi.stubGlobal('fetch', fake)
try {
await fetchQAMonthly({ month: '2026-10', search: '示例敏感筛选' })
expect(fake.mock.calls[0][0]).toBe('/api/v1/qa-ops/usage/people')
expect(fake.mock.calls[0][1]).toMatchObject({ method: 'POST', credentials: 'same-origin', cache: 'no-store' })
expect(JSON.parse(fake.mock.calls[0][1].body).search).toBe('示例敏感筛选')
} finally {
vi.unstubAllGlobals()
}
})
it('selects the month in Beijing rather than the browser timezone', () => {
expect(beijingMonth(new Date('2026-09-30T16:00:00Z'))).toBe('2026-10')
})
it('keeps named and missing-name zero-use members with a separate unresolved bucket', () => {
expect(parseQAMonthly(monthlyFixture)).toMatchObject({ zero_people: 1, missing_names: 1, unresolved_questions: 1 })
})
it('rejects nonconserving totals, fabricated pagination and inconsistent month boundaries', () => {
for (const invalid of [
{ ...monthlyFixture, zero_people: 0 },
{ ...monthlyFixture, linked_questions: 3 },
{ ...monthlyFixture, rows: [monthlyFixture.rows[0]] },
{ ...monthlyFixture, partial: false },
{ ...monthlyFixture, source: '1.0' },
{ ...monthlyFixture, month: '2026-1' },
{ ...monthlyFixture, month_end: '2026-11-02T00:00:00+08:00' },
{ ...monthlyFixture, rows: [monthlyFixture.rows[0], monthlyFixture.rows[0]] },
])
expect(() => parseQAMonthly(invalid)).toThrow()
})
})
+200
View File
@@ -0,0 +1,200 @@
import { parseQAOrganizationVersion } from './qaOps'
import type { QAOrganizationVersion } from './qaOps'
import { getPayload } from './qaOps'
export interface MonthlyQuery {
month: string
cutoff?: string
region?: string
department_id?: string
activity?: string
search?: string
page?: number
limit?: number
directory_id?: string
revision_id?: string
}
export interface MonthlyPerson {
key: string
name: string
departments: string[]
region: string
state: 'matched' | 'unassigned' | 'cross_region'
questions: number
succeeded: number
failed: number
other: number
}
export interface MonthlyPeople {
organization: QAOrganizationVersion
source: '2.0'
timezone: 'Asia/Shanghai'
month: string
start: string
end: string
month_end: string
as_of: string
partial: boolean
questions: number
linked_questions: number
unresolved_questions: number
roster_people: number
used_people: number
zero_people: number
missing_names: number
total: number
page: number
limit: number
has_more: boolean
rows: MonthlyPerson[]
department_options: { id: string; path: string }[]
}
const fail = (): never => {
throw new Error('个人月明细返回格式异常,未展示可能失真的统计')
}
const obj = (v: unknown): Record<string, unknown> =>
v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : fail()
const text = (v: unknown): string => (typeof v === 'string' ? v : fail())
const count = (v: unknown): number => (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? v : fail())
const flag = (v: unknown): boolean => (typeof v === 'boolean' ? v : fail())
const instant = (v: unknown): string => {
const t = text(v)
return Number.isFinite(Date.parse(t)) ? t : fail()
}
const regions = ['国内工业', 'APAC', 'EMEA', 'America']
export function parseQAMonthly(value: unknown): MonthlyPeople {
const v = obj(value),
organization = parseQAOrganizationVersion(v.organization)
if (organization.state !== 'ready' || v.source !== '2.0' || v.timezone !== 'Asia/Shanghai') fail()
const month = text(v.month)
if (!/^(?!0000)\d{4}-(0[1-9]|1[0-2])$/.test(month)) fail()
const start = instant(v.start),
end = instant(v.end),
month_end = instant(v.month_end),
as_of = instant(v.as_of),
partial = flag(v.partial)
const expectedEnd = new Date(`${month}-01T00:00:00Z`)
expectedEnd.setUTCMonth(expectedEnd.getUTCMonth() + 1)
if (
Date.parse(start) !== Date.parse(`${month}-01T00:00:00+08:00`) ||
Date.parse(month_end) !== expectedEnd.getTime() - 8 * 60 * 60 * 1000 ||
Date.parse(end) <= Date.parse(start) ||
Date.parse(end) > Date.parse(month_end) ||
partial !== Date.parse(end) < Date.parse(month_end)
)
fail()
const questions = count(v.questions),
linked_questions = count(v.linked_questions),
unresolved_questions = count(v.unresolved_questions),
roster_people = count(v.roster_people),
used_people = count(v.used_people),
zero_people = count(v.zero_people),
missing_names = count(v.missing_names),
total = count(v.total),
page = count(v.page),
limit = count(v.limit),
has_more = flag(v.has_more)
if (
questions !== linked_questions + unresolved_questions ||
roster_people !== used_people + zero_people ||
missing_names > roster_people ||
total > roster_people ||
page < 1 ||
page > 100000 ||
limit < 1 ||
limit > 100
)
fail()
if (!Array.isArray(v.rows) || !Array.isArray(v.department_options)) return fail()
const keys = new Set<string>()
const rows = v.rows.map((raw: unknown) => {
const r = obj(raw),
key = text(r.key),
name = text(r.name),
region = text(r.region),
state = text(r.state)
if (
!key ||
keys.has(key) ||
name.length > 1000 ||
!['matched', 'unassigned', 'cross_region'].includes(state) ||
(state === 'matched' && !regions.includes(region)) ||
(state !== 'matched' && region !== '')
)
fail()
keys.add(key)
if (!Array.isArray(r.departments)) return fail()
const q = count(r.questions),
s = count(r.succeeded),
f = count(r.failed),
o = count(r.other)
if (s + f + o !== q) fail()
return {
key,
name,
region,
state: state as MonthlyPerson['state'],
departments: r.departments.map(text),
questions: q,
succeeded: s,
failed: f,
other: o,
}
})
const offset = (page - 1) * limit
if (
rows.length !== Math.max(0, Math.min(limit, total - offset)) ||
has_more !== offset + rows.length < total ||
rows.reduce((n, r) => n + r.questions, 0) > linked_questions
)
fail()
const ids = new Set<string>()
const department_options = v.department_options.map((raw: unknown) => {
const d = obj(raw),
id = text(d.id),
path = text(d.path)
if (!id || !path || ids.has(id)) fail()
ids.add(id)
return { id, path }
})
return {
organization,
source: '2.0',
timezone: 'Asia/Shanghai',
month,
start,
end,
month_end,
as_of,
partial,
questions,
linked_questions,
unresolved_questions,
roster_people,
used_people,
zero_people,
missing_names,
total,
page,
limit,
has_more,
rows,
department_options,
}
}
export async function fetchQAMonthly(q: MonthlyQuery, signal?: AbortSignal): Promise<MonthlyPeople> {
return parseQAMonthly(
await getPayload('/api/v1/qa-ops/usage/people', signal, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-usage-read' },
body: JSON.stringify(q),
})
)
}
export function beijingMonth(now = new Date()): string {
const parts = new Intl.DateTimeFormat('en-CA', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
}).formatToParts(now)
return `${parts.find((p) => p.type === 'year')!.value}-${parts.find((p) => p.type === 'month')!.value}`
}
+54
View File
@@ -7,6 +7,54 @@
height: calc(100dvh - 44px);
overflow: hidden;
}
.qa-ops-query.qa-monthly-query {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.qa-monthly-query label {
min-width: 0;
}
.qa-monthly-query select,
.qa-monthly-query input {
width: 100%;
min-width: 0;
}
.qa-monthly-query select {
min-height: 36px;
padding: 7px;
color: var(--ink-strong);
background: var(--bg-panel);
border: 1px solid var(--border-strong);
border-radius: var(--r-sm);
}
.qa-monthly-results > .qa-ops-muted {
margin: 6px 14px;
font-size: 12px;
line-height: 1.5;
}
.qa-ops-table.qa-monthly-table {
min-width: 800px;
table-layout: fixed;
}
.qa-monthly-table th:nth-child(1) {
width: 15%;
}
.qa-monthly-table th:nth-child(2) {
width: 30%;
}
.qa-monthly-table th:nth-child(3) {
width: 23%;
}
.qa-monthly-table td:nth-child(1),
.qa-monthly-table td:nth-child(2) {
white-space: normal;
overflow-wrap: anywhere;
}
@media (max-width: 760px) {
.qa-ops-query.qa-monthly-query {
grid-template-columns: minmax(0, 1fr);
}
}
.qa-ops-header h2 {
margin: 0 0 5px;
font-size: 21px;
@@ -66,6 +114,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;
+98 -3
View File
@@ -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,11 +220,23 @@ 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<unknown> {
const response = await fetch(path, { credentials: 'same-origin', cache: 'no-store', signal })
export async function getPayload(
path: string,
signal?: AbortSignal,
request: Pick<RequestInit, 'method' | 'headers' | 'body'> = {}
): Promise<unknown> {
const response = await fetch(path, { ...request, credentials: 'same-origin', cache: 'no-store', signal })
const raw: unknown = await response.json().catch(() => null)
if (!response.ok) {
const payload = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : null
+85
View File
@@ -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<string, unknown> =>
v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : 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<string, string> = {
国内工业: '国内工业',
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<QAUsage> {
const params = new URLSearchParams({ start: query.start, end: query.end, keyword: query.keyword })
return parseQAUsage(await getPayload(`/api/v1/qa-ops/usage?${params}`, signal))
}