Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9556db1ef0 | |||
| 56b8cabed9 | |||
| cc4906b6a9 | |||
| 6adfdcdd4f | |||
| 5874134e04 | |||
| dab74b706b |
@@ -10,6 +10,17 @@ DOBOTAI_OPS_QUERY_TIMEOUT=4s
|
||||
DOBOTAI_OPS_MAX_CONNS=2
|
||||
DOBOTAI_OPS_MIN_CONNS=0
|
||||
|
||||
# API and worker share this opt-in binding; no browser-selected paths/credentials.
|
||||
# Runtime root is the read-only existing weekly_report directory (SDK/config and
|
||||
# private secret file). Python must be compatible and already provide PyYAML.
|
||||
# Container deployment requires approved runtime/script mounts; not auto-installed.
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED=false
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_PYTHON=
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_SCRIPT=
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_RUNTIME_ROOT=
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_SPOOL_ROOT=
|
||||
DOBOTAI_OPS_DIRECTORY_SYNC_TIMEOUT=20m
|
||||
|
||||
APP_ADDR=:8080
|
||||
DATABASE_URL=postgres://governance@postgres:5432/governance?sslmode=disable
|
||||
PGPASSFILE=/run/secrets/pgpass
|
||||
|
||||
+9
-1
@@ -4,7 +4,15 @@
|
||||
|
||||
### Added
|
||||
|
||||
- **「问答运营 → 问答记录」首个开发切片**:在现有导航中查看 DobotAI 2.0 钉钉问答,支持半开时间范围、原问题关键词、稳定游标分页和完整详情;按整个筛选结果隐藏空列,反馈聚合不放大问答条数。外语翻译、AI 评估、人员区域映射尚未接入,不标为第一阶段完成。
|
||||
- 「使用统计 → 个人月明细」按北京时间自然月及截止时点展示当前应用可见名册的人员用量(包含本源零记录),支持部门含子部门、区域/待核对状态、姓名/完整部门路径和已有提问/零记录筛选。稳定身份关联去重、不可关联问答单列、过期组织版本阻断翻页;源端姓名可缺失并提示重新同步,不按姓名匹配身份。姓名筛选通过有界只读 POST 请求体传递、不进入 URL,原始员工标识不返回浏览器;名册不作为在职/考核分母,当月进度不作为绩效结论。
|
||||
|
||||
- 问答运营按稳定身份关联当前治理通讯录,缺失部门/区域补全并保留源快照及目录/区域版本;空列判断包含完整筛选结果,不混合配置已变化的分页。新增完整时间/关键词范围的使用统计,问答计次、名册内人员去重,跨区/未匹配/身份缺失分列,不输出绩效结论;不回写 DobotAI 原表。
|
||||
- 「问答运营 → 区域使用」支持管理员从网页发起持久化通讯录同步,重复请求重放、进行中操作合并;按服务器固定范围注册后台执行器,未接线或未检测到心跳时不创建新任务。界面显示真实任务状态、不编造百分比;失败保留旧快照与区域规则,同步完成不覆盖未保存草稿。旧执行器丢失租约后不能激活结果,重启接管和已提交快照的续跑使用原任务。
|
||||
- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件。同步默认关闭,容器启用仍需批准的既有周报 SDK/配置及兼容 Python 运行时挂载。
|
||||
- 区域归属表支持长部门路径换行,避免继承全局不换行规则后将生效区域与归属依据列挤出桌面面板。
|
||||
- **「问答运营 → 区域使用」区域归属配置切片**:按稳定部门 ID 搜索和勾选完整路径,预览去重归属人数,保存版本后重新读取;父部门包含子部门、子部门显式配置优先,多部门跨区域人员单独待核对。预览不写入,过期版本和不完整部门树被阻断。基础使用统计见本期新增,不代表绩效验收;翻译及 AI 评估模型接入按用户要求暂缓。
|
||||
- 新增治理侧组织快照与区域修订迁移、受确认保护的后台导入命令;不修改 DobotAI 原表或钉钉组织结构。
|
||||
- **「问答运营 → 问答记录」首个开发切片**:在现有导航中查看 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`(仅管理员手动同步,并发同步复用同一作业)。
|
||||
|
||||
@@ -44,6 +44,63 @@
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"/api/v1/qa-ops/organization/sync": {
|
||||
"get": {"tags":["QA operations"],"operationId":"getQAOrganizationSync","summary":"管理员读取通讯录同步执行器状态及最近任务的安全汇总,不返回人员名单或运行配置","responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"状态存储不可用,不伪装为空记录"}}},
|
||||
"post": {"tags":["QA operations"],"operationId":"startQAOrganizationSync","summary":"管理员同源发起持久化通讯录同步;重复请求重放同一任务,进行中任务合并;失败保留现有快照","parameters":[{"$ref":"#/components/parameters/IdempotencyKey"},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-organization"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false}}}},"responses":{"202":{"$ref":"#/components/responses/OperationEnvelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员同源操作"},"409":{"description":"操作标识与原请求冲突"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"同步未接线、执行器离线或入队失败;未创建新任务"}}}
|
||||
},
|
||||
"/api/v1/qa-ops/organization": {
|
||||
"get": {
|
||||
"tags": ["QA operations"],
|
||||
"operationId": "getQAOrganization",
|
||||
"summary": "管理员读取服务器固定租户的完整部门路径、已保存区域归属与快照时间,不返回人员名单",
|
||||
"responses": {
|
||||
"200": {"$ref": "#/components/responses/Envelope"},
|
||||
"400": {"$ref": "#/components/responses/BadRequest"},
|
||||
"401": {"description": "需要登录"},
|
||||
"403": {"description": "仅管理员可访问"},
|
||||
"500": {"$ref": "#/components/responses/InternalError"},
|
||||
"503": {"description": "治理侧组织存储不可用"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/qa-ops/organization/preview": {
|
||||
"post": {
|
||||
"tags": ["QA operations"],
|
||||
"operationId": "previewQAOrganizationRegions",
|
||||
"summary": "预览当前通讯录版本下的父子部门区域归属和去重人数,不保存修改",
|
||||
"parameters": [{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-organization"}}],
|
||||
"requestBody": {"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["directory_id","base_revision","rules"],"properties":{"directory_id":{"type":"string"},"base_revision":{"type":"string"},"rules":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["department_id","region"],"properties":{"department_id":{"type":"string"},"region":{"enum":["国内工业","APAC","EMEA","America"]}}}}}}}}},
|
||||
"responses": {
|
||||
"200": {"$ref": "#/components/responses/Envelope"},
|
||||
"400": {"$ref": "#/components/responses/BadRequest"},
|
||||
"401": {"description": "需要登录"},
|
||||
"403": {"description": "仅管理员同源操作可访问"},
|
||||
"409": {"description": "通讯录或配置版本已变化,需重新读取"},
|
||||
"500": {"$ref": "#/components/responses/InternalError"},
|
||||
"503": {"description": "治理侧组织存储不可用"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/qa-ops/organization/regions": {
|
||||
"put": {
|
||||
"tags": ["QA operations"],
|
||||
"operationId": "saveQAOrganizationRegions",
|
||||
"summary": "保存版本化区域配置;操作人取管理员会话,不改变钉钉或DobotAI数据",
|
||||
"parameters": [{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-organization"}}],
|
||||
"requestBody": {"$ref":"#/paths/~1api~1v1~1qa-ops~1organization~1preview/post/requestBody"},
|
||||
"responses": {
|
||||
"200": {"$ref": "#/components/responses/Envelope"},
|
||||
"400": {"$ref": "#/components/responses/BadRequest"},
|
||||
"401": {"description": "需要登录"},
|
||||
"403": {"description": "仅管理员同源操作可访问"},
|
||||
"409": {"description": "版本冲突或尚无完整通讯录"},
|
||||
"500": {"$ref": "#/components/responses/InternalError"},
|
||||
"503": {"description": "治理侧组织存储不可用"}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/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"],
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"knowledge-governance/internal/serviceverify"
|
||||
)
|
||||
|
||||
@@ -132,7 +133,19 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
if qaSettings.Problem != "" {
|
||||
log.Print("QA operations source is unavailable; governance remains online")
|
||||
}
|
||||
qaOrganizationStore := qaopsorg.NewStore(pool, getenv("DOBOTAI_OPS_TENANT_KEY"))
|
||||
qaSyncSettings, qaSyncErr := qaopsorg.LoadSyncSettings(getenv)
|
||||
if qaSyncErr != nil {
|
||||
log.Print("QA directory synchronization is not configured; governance remains online")
|
||||
}
|
||||
var qaSyncStore httpapi.QAOrgSyncStore
|
||||
if getenv("DOBOTAI_OPS_TENANT_KEY") != "" {
|
||||
qaSyncStore = qaOrganizationStore
|
||||
}
|
||||
handler, err := httpapi.NewHandler(httpapi.Config{
|
||||
QAOrgSync: qaSyncStore,
|
||||
QAOrgSyncEnabled: qaSyncErr == nil && qaSyncSettings.Enabled,
|
||||
QAOrg: qaOrganizationStore,
|
||||
QAOps: qaReader,
|
||||
QAOpsTenantKey: qaSettings.TenantKey,
|
||||
QAOpsEnabled: qaSettings.Enabled,
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(os.Args[1:], os.Getenv, os.Stdout); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "directory import failed; check private input and governance connection (details withheld)")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(args []string, getenv func(string) string, out io.Writer) error {
|
||||
if len(args) != 1 || getenv("QAOPS_CONFIRM_DIRECTORY_IMPORT") != "import-governance-directory" || getenv("DOBOTAI_OPS_TENANT_KEY") == "" || getenv("DATABASE_URL") == "" {
|
||||
return errors.New("explicit input, tenant, governance database and confirmation required")
|
||||
}
|
||||
info, err := os.Lstat(args[0])
|
||||
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 || info.Size() > 16<<20 {
|
||||
return errors.New("input must be a private regular JSON file")
|
||||
}
|
||||
file, err := os.Open(args[0])
|
||||
if err != nil {
|
||||
return errors.New("input unavailable")
|
||||
}
|
||||
defer file.Close()
|
||||
decoder := json.NewDecoder(io.LimitReader(file, (16<<20)+1))
|
||||
decoder.DisallowUnknownFields()
|
||||
var input qaopsorg.Import
|
||||
if decoder.Decode(&input) != nil || decoder.Decode(&struct{}{}) != io.EOF {
|
||||
return errors.New("input invalid")
|
||||
}
|
||||
if !input.Complete {
|
||||
return qaopsorg.ErrInvalid
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
pool, err := pgxpool.New(ctx, getenv("DATABASE_URL"))
|
||||
if err != nil {
|
||||
return qaopsorg.ErrUnavailable
|
||||
}
|
||||
defer pool.Close()
|
||||
store := qaopsorg.NewStore(pool, getenv("DOBOTAI_OPS_TENANT_KEY"))
|
||||
saved, err := store.ReplaceDirectory(ctx, input)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
active, err := store.GetView(ctx)
|
||||
if err != nil || active.DirectoryID != saved.DirectoryID {
|
||||
return qaopsorg.ErrConflict
|
||||
}
|
||||
return json.NewEncoder(out).Encode(map[string]any{"directory_id": active.DirectoryID, "source": active.DirectorySource, "synced_at": active.DirectorySyncedAt, "departments": len(active.View.Departments), "people": active.View.TotalPeople, "readback_verified": true})
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDirectoryImportRequiresExplicitGovernanceConfirmationAndPrivateInput(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
if run(nil, func(string) string { return "" }, &output) == nil || output.Len() != 0 {
|
||||
t.Fatal("unconfigured importer must not connect or report success")
|
||||
}
|
||||
path := filepath.Join(t.TempDir(), "directory.json")
|
||||
if os.WriteFile(path, []byte(`{"complete":false}`), 0644) != nil {
|
||||
t.Fatal("fixture creation failed")
|
||||
}
|
||||
env := func(k string) string {
|
||||
return map[string]string{"QAOPS_CONFIRM_DIRECTORY_IMPORT": "import-governance-directory", "DOBOTAI_OPS_TENANT_KEY": "fixture", "DATABASE_URL": "postgres://invalid.invalid/no_connection_expected"}[k]
|
||||
}
|
||||
if run([]string{path}, env, &output) == nil {
|
||||
t.Fatal("public personnel input accepted")
|
||||
}
|
||||
if os.Chmod(path, 0600) != nil {
|
||||
t.Fatal("fixture chmod failed")
|
||||
}
|
||||
if run([]string{path}, env, &output) == nil || output.Len() != 0 {
|
||||
t.Fatal("partial sync accepted or importer reported fabricated success")
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,9 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if syncErr := configureDirectorySync(pool, getenv, handlers); syncErr != nil {
|
||||
log.Print("QA directory synchronization unavailable; handler was not registered")
|
||||
}
|
||||
worker, err := jobs.NewWorker(jobs.WorkerConfig{
|
||||
Queue: store,
|
||||
WorkerID: config.WorkerID,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
)
|
||||
|
||||
func configureDirectorySync(pool *pgxpool.Pool, getenv func(string) string, handlers map[string]jobs.Handler) error {
|
||||
settings, err := qaopsorg.LoadSyncSettings(getenv)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !settings.Enabled {
|
||||
return nil
|
||||
}
|
||||
if err = settings.CheckWorkerRuntime(); err != nil {
|
||||
return err
|
||||
}
|
||||
store := qaopsorg.NewStore(pool, settings.Tenant)
|
||||
handlers[store.SyncJobType()] = func(ctx context.Context, job jobs.Job) error {
|
||||
return store.HandleDirectorySync(ctx, job, settings.Runner)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDirectorySyncWorkerRegistrationIsOptInAndRuntimeChecked(t *testing.T) {
|
||||
handlers := map[string]jobs.Handler{}
|
||||
values := map[string]string{}
|
||||
get := func(k string) string { return values[k] }
|
||||
if err := configureDirectorySync(nil, get, handlers); err != nil || len(handlers) != 0 {
|
||||
t.Fatal("disabled sync registered")
|
||||
}
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED"] = "true"
|
||||
if err := configureDirectorySync(nil, get, handlers); err == nil {
|
||||
t.Fatal("incomplete binding registered")
|
||||
}
|
||||
root := t.TempDir()
|
||||
script := filepath.Join(root, "fixture.py")
|
||||
if err := os.WriteFile(script, []byte("# fixture; not executed by registration"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
values["DOBOTAI_OPS_TENANT_KEY"] = "fixture-tenant"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_PYTHON"] = "/bin/sh"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_SCRIPT"] = script
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_RUNTIME_ROOT"] = root
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_SPOOL_ROOT"] = root
|
||||
if err := configureDirectorySync(nil, get, handlers); err != nil || handlers[qaopsorg.NewStore(nil, "fixture-tenant").SyncJobType()] == nil {
|
||||
t.Fatal("configured worker was not wired")
|
||||
}
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_SCRIPT"] = filepath.Join(root, "missing.py")
|
||||
if err := configureDirectorySync(nil, get, map[string]jobs.Handler{}); err == nil {
|
||||
t.Fatal("missing runtime advertised as ready")
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -77,7 +77,7 @@ func TestOpenAPICatalogMutationsRequireIdempotencyKeyHeader(t *testing.T) {
|
||||
if !ok || schema["type"] != "string" || schema["minLength"] != float64(1) || schema["maxLength"] != float64(128) {
|
||||
t.Fatalf("IdempotencyKey header schema is unsafe: %#v", parameter["schema"])
|
||||
}
|
||||
for _, path := range []string{"/api/v1/source-catalog/route", "/api/v1/source-catalog/sources/{id}/refresh"} {
|
||||
for _, path := range []string{"/api/v1/qa-ops/organization/sync", "/api/v1/source-catalog/route", "/api/v1/source-catalog/sources/{id}/refresh"} {
|
||||
operation, ok := document.Paths[path]["post"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("missing POST %s", path)
|
||||
|
||||
@@ -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)})
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)})
|
||||
}
|
||||
@@ -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", "®ion=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}, {"®ion=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}, {"®ion=cross_region", 1}, {"®ion=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")
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type QAOrgStore interface {
|
||||
GetView(context.Context) (qaopsorg.State, error)
|
||||
PreviewRules(context.Context, qaopsorg.SaveRequest) (qaopsorg.State, error)
|
||||
SaveRules(context.Context, qaopsorg.SaveRequest, string) (qaopsorg.State, error)
|
||||
}
|
||||
|
||||
func qaOrganization(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if r.URL.RawQuery != "" {
|
||||
writeOrgError(w, qaopsorg.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if config.QAOrg == nil {
|
||||
writeOrgError(w, qaopsorg.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
var result qaopsorg.State
|
||||
var err error
|
||||
if r.Method == http.MethodGet {
|
||||
result, err = config.QAOrg.GetView(r.Context())
|
||||
} else {
|
||||
if !authorizeQAOrganizationWrite(w, r) {
|
||||
return
|
||||
}
|
||||
var request qaopsorg.SaveRequest
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&request) != nil || decoder.Decode(&struct{}{}) != io.EOF || request.DirectoryID == "" || request.Rules == nil {
|
||||
writeOrgError(w, qaopsorg.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodPost {
|
||||
result, err = config.QAOrg.PreviewRules(r.Context(), request)
|
||||
} else {
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
result, err = config.QAOrg.SaveRules(r.Context(), request, identity.Username)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
writeOrgError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": result})
|
||||
}
|
||||
func writeOrgError(w http.ResponseWriter, err error) {
|
||||
status, message := 503, "通讯录或区域配置存储不可用,未展示为空数据"
|
||||
switch {
|
||||
case errors.Is(err, qaopsorg.ErrInvalid):
|
||||
status, message = 400, "部门树或区域配置无效,请核对重复、缺失路径及区域"
|
||||
case errors.Is(err, qaopsorg.ErrConflict):
|
||||
status, message = 409, "通讯录或区域配置已变化,请重新读取后预览"
|
||||
case errors.Is(err, qaopsorg.ErrNoDirectory):
|
||||
status, message = 409, "尚无完整通讯录快照,不能保存区域配置"
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": message})
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestQAOrganizationSameOriginThroughReverseProxy(t *testing.T) {
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["org-proxy-admin"] = "usr-boss"
|
||||
spy := &orgSpy{}
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, QAOrg: spy, Auth: &AuthConfig{Store: auth}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
site string
|
||||
status int
|
||||
}{{"same-origin", 200}, {"cross-site", 403}, {"same-site", 403}} {
|
||||
req := httptest.NewRequest("PUT", "http://internal-api:8080/api/v1/qa-ops/organization/regions", strings.NewReader(`{"directory_id":"d","base_revision":"","rules":[]}`))
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "org-proxy-admin"})
|
||||
req.Header.Set("X-Governance-Action", "qa-organization")
|
||||
req.Header.Set("Origin", "http://frontend:8088")
|
||||
req.Header.Set("Sec-Fetch-Site", tc.site)
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, req)
|
||||
if res.Code != tc.status {
|
||||
t.Fatalf("proxy fetch site %s got %d want %d", tc.site, res.Code, tc.status)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type QAOrgSyncStore interface {
|
||||
GetSyncStatus(context.Context) (qaopsorg.SyncStatus, error)
|
||||
EnqueueSync(context.Context, string, string) (qaopsorg.SyncReceipt, bool, error)
|
||||
}
|
||||
|
||||
func authorizeQAOrganizationWrite(w http.ResponseWriter, r *http.Request) bool {
|
||||
if r.Header.Get("X-Governance-Action") != "qa-organization" || r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||
writeJSON(w, 403, map[string]string{"error": "区域配置需要同源操作意图"})
|
||||
return false
|
||||
}
|
||||
// Fetch Metadata survives same-origin proxies that rewrite Host; untrusted
|
||||
// forwarded headers must not grant cross-origin write authority.
|
||||
if raw := r.Header.Get("Origin"); raw != "" && r.Header.Get("Sec-Fetch-Site") != "same-origin" {
|
||||
origin, err := url.Parse(raw)
|
||||
if err != nil || (origin.Scheme != "http" && origin.Scheme != "https") || origin.Host != r.Host {
|
||||
writeJSON(w, 403, map[string]string{"error": "拒绝跨站配置请求"})
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func qaOrganizationSync(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if r.URL.RawQuery != "" {
|
||||
writeOrgError(w, qaopsorg.ErrInvalid)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if r.Method == http.MethodGet {
|
||||
if c.QAOrgSync == nil {
|
||||
writeJSON(w, 200, map[string]any{"data": qaopsorg.SyncStatus{}})
|
||||
return
|
||||
}
|
||||
result, err := c.QAOrgSync.GetSyncStatus(r.Context())
|
||||
if err != nil {
|
||||
writeOrgError(w, err)
|
||||
return
|
||||
}
|
||||
result.Configured = c.QAOrgSyncEnabled
|
||||
writeJSON(w, 200, map[string]any{"data": result})
|
||||
return
|
||||
}
|
||||
if !authorizeQAOrganizationWrite(w, r) {
|
||||
return
|
||||
}
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
if key == "" || len(key) > 128 || strings.TrimSpace(key) != key {
|
||||
writeJSON(w, 400, map[string]string{"error": "同步请求需要有效 Idempotency-Key,重试须复用原标识"})
|
||||
return
|
||||
}
|
||||
var body *struct{}
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024))
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&body) != nil || body == nil || decoder.Decode(&struct{}{}) != io.EOF {
|
||||
writeOrgError(w, qaopsorg.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if !c.QAOrgSyncEnabled || c.QAOrgSync == nil {
|
||||
writeJSON(w, 503, map[string]string{"error": "通讯录后台同步未接线,未创建任务"})
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
receipt, replayed, err := c.QAOrgSync.EnqueueSync(r.Context(), key, identity.Username)
|
||||
if err != nil {
|
||||
if errors.Is(err, qaopsorg.ErrSyncWorkerUnavailable) {
|
||||
writeJSON(w, 503, map[string]string{"error": "通讯录执行器未在线,未创建任务;请检查后台同步配置"})
|
||||
return
|
||||
}
|
||||
writeOrgError(w, err)
|
||||
return
|
||||
}
|
||||
operation := "created"
|
||||
if replayed {
|
||||
operation = "replayed"
|
||||
}
|
||||
writeJSON(w, 202, map[string]any{"data": receipt, "operation": operation})
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGenericJobCreationCannotBypassDirectorySyncAdminPath(t *testing.T) {
|
||||
h, err := NewHandler(Config{Store: &fakeJobStore{}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest("POST", "/api/v1/jobs", strings.NewReader(`{"type":"qaops.directory.sync.fixture","payload":{"triggered_by":"forged"},"idempotency_key":"bypass"}`))
|
||||
res := httptest.NewRecorder()
|
||||
h.ServeHTTP(res, req)
|
||||
if res.Code != 400 {
|
||||
t.Fatalf("reserved sync job bypassed its dedicated admission path: %d", res.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type orgSyncSpy struct {
|
||||
calls int
|
||||
key, actor string
|
||||
replay bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *orgSyncSpy) GetSyncStatus(context.Context) (qaopsorg.SyncStatus, error) {
|
||||
s.calls++
|
||||
return qaopsorg.SyncStatus{Configured: true, WorkerReady: true}, s.err
|
||||
}
|
||||
func (s *orgSyncSpy) EnqueueSync(_ context.Context, key, actor string) (qaopsorg.SyncReceipt, bool, error) {
|
||||
s.calls++
|
||||
s.key = key
|
||||
s.actor = actor
|
||||
return qaopsorg.SyncReceipt{JobID: "fixture-job"}, s.replay, s.err
|
||||
}
|
||||
func TestQAOrganizationSyncRequiresAdminIntentAndDurableOperation(t *testing.T) {
|
||||
spy := &orgSyncSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["sync-admin"] = "usr-boss"
|
||||
auth.sessions["sync-viewer"] = "usr-eye"
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, QAOrgSync: spy, QAOrgSyncEnabled: true, Auth: &AuthConfig{Store: auth}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
method, token, key, action, origin, body string
|
||||
status int
|
||||
}{
|
||||
{"GET", "", "", "", "", "", 401}, {"GET", "sync-viewer", "", "", "", "", 403}, {"GET", "sync-admin", "", "", "", "", 200},
|
||||
{"POST", "sync-admin", "op-one", "", "", "{}", 403}, {"POST", "sync-admin", "op-one", "qa-organization", "https://evil.invalid", "{}", 403},
|
||||
{"POST", "sync-admin", "", "qa-organization", "", "{}", 400}, {"POST", "sync-admin", " op-one ", "qa-organization", "", "{}", 400},
|
||||
{"POST", "sync-admin", "op-one", "qa-organization", "", `null`, 400},
|
||||
{"POST", "sync-admin", "op-one", "qa-organization", "", `{"tenant":"forged"}`, 400}, {"POST", "sync-admin", "op-one", "qa-organization", "", "{} {}", 400},
|
||||
{"POST", "sync-admin", "op-one", "qa-organization", "", "{}", 202},
|
||||
} {
|
||||
req := httptest.NewRequest(tc.method, "/api/v1/qa-ops/organization/sync", strings.NewReader(tc.body))
|
||||
if tc.token != "" {
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: tc.token})
|
||||
}
|
||||
req.Header.Set("Idempotency-Key", tc.key)
|
||||
req.Header.Set("X-Governance-Action", tc.action)
|
||||
req.Header.Set("Origin", tc.origin)
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, req)
|
||||
if res.Code != tc.status {
|
||||
t.Fatalf("%+v got %d: %s", tc, res.Code, res.Body.String())
|
||||
}
|
||||
}
|
||||
if spy.calls != 2 || spy.key != "op-one" || spy.actor == "" {
|
||||
t.Fatalf("invalid request reached store: %+v", spy)
|
||||
}
|
||||
spy.replay = true
|
||||
req := httptest.NewRequest("POST", "/api/v1/qa-ops/organization/sync", strings.NewReader("{}"))
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "sync-admin"})
|
||||
req.Header.Set("Idempotency-Key", "op-one")
|
||||
req.Header.Set("X-Governance-Action", "qa-organization")
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, req)
|
||||
var body map[string]any
|
||||
if json.Unmarshal(res.Body.Bytes(), &body) != nil || body["operation"] != "replayed" {
|
||||
t.Fatal("operation replay not exposed")
|
||||
}
|
||||
disabled, _ := NewHandler(Config{Store: &fakeJobStore{}, QAOrgSync: spy, Auth: &AuthConfig{Store: auth}})
|
||||
req.Body = io.NopCloser(strings.NewReader("{}"))
|
||||
res = httptest.NewRecorder()
|
||||
disabled.ServeHTTP(res, req)
|
||||
if res.Code != 503 {
|
||||
t.Fatal("disabled sync enqueued")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type orgSpy struct {
|
||||
calls int
|
||||
actor string
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *orgSpy) GetView(context.Context) (qaopsorg.State, error) {
|
||||
s.calls++
|
||||
return qaopsorg.State{State: "empty"}, s.err
|
||||
}
|
||||
func (s *orgSpy) PreviewRules(context.Context, qaopsorg.SaveRequest) (qaopsorg.State, error) {
|
||||
s.calls++
|
||||
return qaopsorg.State{}, s.err
|
||||
}
|
||||
func (s *orgSpy) SaveRules(_ context.Context, _ qaopsorg.SaveRequest, actor string) (qaopsorg.State, error) {
|
||||
s.calls++
|
||||
s.actor = actor
|
||||
return qaopsorg.State{}, s.err
|
||||
}
|
||||
func TestQAOrganizationGuardsIdentityIntentAndErrors(t *testing.T) {
|
||||
spy := &orgSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["org-admin"] = "usr-boss"
|
||||
auth.sessions["org-viewer"] = "usr-eye"
|
||||
handler, err := NewHandler(Config{Store: &fakeJobStore{}, QAOrg: spy, Auth: &AuthConfig{Store: auth}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := "/api/v1/qa-ops/organization"
|
||||
for _, tc := range []struct {
|
||||
method, path, token, action, origin, body string
|
||||
status int
|
||||
}{
|
||||
{"GET", base, "", "", "", "", 401},
|
||||
{"GET", base, "org-viewer", "", "", "", 403},
|
||||
{"GET", base, "org-admin", "", "", "", 200},
|
||||
{"GET", base + "?tenant=another", "org-admin", "", "", "", 400},
|
||||
{"PUT", base + "/regions", "org-admin", "", "", "{}", 403},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "https://untrusted.invalid", "{}", 403},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"updated_by":"forged"}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{} {}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":null}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":[]}`, 200},
|
||||
{"POST", base + "/preview", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":[]}`, 200},
|
||||
} {
|
||||
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
|
||||
if tc.token != "" {
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: tc.token})
|
||||
}
|
||||
req.Header.Set("X-Governance-Action", tc.action)
|
||||
req.Header.Set("Origin", tc.origin)
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, req)
|
||||
if res.Code != tc.status {
|
||||
t.Fatalf("%s %s got %d want %d: %s", tc.method, tc.path, res.Code, tc.status, res.Body.String())
|
||||
}
|
||||
}
|
||||
if spy.calls != 3 || spy.actor == "" || spy.actor == "forged" {
|
||||
t.Fatalf("invalid requests reached store or actor not stamped: %+v", spy)
|
||||
}
|
||||
spy.err = qaopsorg.ErrConflict
|
||||
req := httptest.NewRequest("PUT", base+"/regions", strings.NewReader(`{"directory_id":"d","base_revision":"","rules":[]}`))
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "org-admin"})
|
||||
req.Header.Set("X-Governance-Action", "qa-organization")
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, req)
|
||||
if res.Code != 409 {
|
||||
t.Fatal("stale configuration not reported as conflict")
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
)
|
||||
|
||||
type JobStore interface {
|
||||
@@ -101,6 +102,9 @@ type Store interface {
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
QAOrgSync QAOrgSyncStore
|
||||
QAOrgSyncEnabled bool
|
||||
QAOrg QAOrgStore
|
||||
QAOps QAOpsReader
|
||||
QAOpsTenantKey string
|
||||
QAOpsEnabled bool
|
||||
@@ -171,6 +175,13 @@ 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) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/organization/preview", func(w http.ResponseWriter, r *http.Request) { qaOrganization(w, r, config) })
|
||||
mux.HandleFunc("PUT /api/v1/qa-ops/organization/regions", func(w http.ResponseWriter, r *http.Request) { qaOrganization(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/status", func(w http.ResponseWriter, r *http.Request) {
|
||||
qaOpsStatus(w, r, config)
|
||||
})
|
||||
@@ -552,6 +563,10 @@ func createJob(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON request"})
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(input.Type, qaopsorg.SyncJobPrefix) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "通讯录同步任务只能从问答运营的管理员入口创建"})
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(input.Type) == "" || len(input.Type) > 100 {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "type is required and must not exceed 100 characters"})
|
||||
return
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
DROP TABLE IF EXISTS qa_ops_organization_state;
|
||||
DROP TABLE IF EXISTS qa_ops_region_revisions;
|
||||
DROP TABLE IF EXISTS qa_ops_directory_snapshots;
|
||||
@@ -0,0 +1,26 @@
|
||||
CREATE TABLE qa_ops_directory_snapshots (
|
||||
tenant_key TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
source TEXT NOT NULL CHECK (source IN ('weekly_report_snapshot','weekly_report_live')),
|
||||
synced_at TIMESTAMPTZ NOT NULL,
|
||||
imported_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
payload JSONB NOT NULL CHECK (jsonb_typeof(payload)='object'),
|
||||
PRIMARY KEY (tenant_key,id)
|
||||
);
|
||||
CREATE TABLE qa_ops_region_revisions (
|
||||
tenant_key TEXT NOT NULL,
|
||||
id TEXT NOT NULL,
|
||||
directory_id TEXT NOT NULL,
|
||||
rules JSONB NOT NULL CHECK (jsonb_typeof(rules)='array'),
|
||||
updated_by TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (tenant_key,id),
|
||||
FOREIGN KEY (tenant_key,directory_id) REFERENCES qa_ops_directory_snapshots(tenant_key,id)
|
||||
);
|
||||
CREATE TABLE qa_ops_organization_state (
|
||||
tenant_key TEXT PRIMARY KEY,
|
||||
directory_id TEXT NOT NULL,
|
||||
revision_id TEXT,
|
||||
FOREIGN KEY (tenant_key,directory_id) REFERENCES qa_ops_directory_snapshots(tenant_key,id),
|
||||
FOREIGN KEY (tenant_key,revision_id) REFERENCES qa_ops_region_revisions(tenant_key,id)
|
||||
);
|
||||
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 47 {
|
||||
t.Fatalf("migration count = %d, want 47", len(migrations))
|
||||
if len(migrations) != 48 {
|
||||
t.Fatalf("migration count = %d, want 48", len(migrations))
|
||||
}
|
||||
if migrations[0].Version != 1 || !strings.Contains(migrations[0].UpSQL, "CREATE TABLE IF NOT EXISTS jobs") {
|
||||
t.Fatalf("migration 1 = %#v", migrations[0])
|
||||
|
||||
@@ -20,6 +20,12 @@ var ErrOperationRequestConflict = errors.New("operation request conflicts with a
|
||||
|
||||
type operationExecutor func(pgx.Tx) (json.RawMessage, error)
|
||||
|
||||
// ExecuteOperation lets bounded modules share the durable operation transaction
|
||||
// instead of caching responses after their business writes have committed.
|
||||
func (s *Store) ExecuteOperation(ctx context.Context, operationType, operationID, fingerprint string, now time.Time, execute func(pgx.Tx) (json.RawMessage, error)) (json.RawMessage, bool, error) {
|
||||
return s.executeOperation(ctx, operationType, operationID, fingerprint, now, execute)
|
||||
}
|
||||
|
||||
func (s *Store) RouteCatalogFilesWithOperation(ctx context.Context, request governance.CatalogRouteRequest, operationID string) (governance.CatalogRouteResult, bool, error) {
|
||||
if err := validateCatalogRouteRequest(request); err != nil {
|
||||
return governance.CatalogRouteResult{}, false, err
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrDirectorySync = errors.New("directory synchronization failed; active snapshot was not replaced")
|
||||
|
||||
type ExecDirectoryRunner struct {
|
||||
Python string
|
||||
Script string
|
||||
RuntimeRoot string
|
||||
SpoolRoot string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Only server-owned paths cross this boundary. Credentials are read by the
|
||||
// existing directory client from its private file, never passed in argv/logs.
|
||||
func (r ExecDirectoryRunner) Run(ctx context.Context) (Import, error) {
|
||||
for _, path := range []string{r.Python, r.Script, r.RuntimeRoot, r.SpoolRoot} {
|
||||
if !filepath.IsAbs(path) || filepath.Clean(path) != path {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
}
|
||||
if r.Timeout == 0 {
|
||||
r.Timeout = 20 * time.Minute
|
||||
}
|
||||
if r.Timeout < time.Millisecond || r.Timeout > 30*time.Minute {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
work, err := os.MkdirTemp(r.SpoolRoot, "qa-directory-")
|
||||
if err != nil {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
defer os.RemoveAll(work)
|
||||
output := filepath.Join(work, "directory.json")
|
||||
runCtx, cancel := context.WithTimeout(ctx, r.Timeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(runCtx, r.Python, r.Script, "--runtime-root", r.RuntimeRoot, "--output", output, "--fetch-live-directory")
|
||||
cmd.Dir = r.RuntimeRoot
|
||||
cmd.Env = []string{"PYTHONUNBUFFERED=1"}
|
||||
for _, key := range []string{"PATH", "HOME", "TMPDIR", "LANG", "TZ"} {
|
||||
if value, ok := os.LookupEnv(key); ok {
|
||||
cmd.Env = append(cmd.Env, key+"="+value)
|
||||
}
|
||||
}
|
||||
cmd.Stdout = io.Discard
|
||||
cmd.Stderr = io.Discard
|
||||
cmd.WaitDelay = 3 * time.Second
|
||||
if err = cmd.Run(); err != nil {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
info, err := os.Lstat(output)
|
||||
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 || info.Size() < 1 || info.Size() > 16<<20 {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
file, err := os.Open(output)
|
||||
if err != nil {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
defer file.Close()
|
||||
decoder := json.NewDecoder(io.LimitReader(file, (16<<20)+1))
|
||||
decoder.DisallowUnknownFields()
|
||||
var result Import
|
||||
if decoder.Decode(&result) != nil || decoder.Decode(&struct{}{}) != io.EOF || !result.Complete || result.Source != "weekly_report_live" || result.SyncedAt.IsZero() || result.SyncedAt.After(time.Now().Add(time.Minute)) {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
if _, err = Preview(result.Directory, nil); err != nil {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDirectoryBridgeRegressionSuiteRunsInDefaultCI(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "python3", "-m", "unittest", "discover", "-s", "scripts", "-p", "test_qa_ops_directory_sync.py", "-v")
|
||||
cmd.Dir = filepath.Join("..", "..")
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("directory bridge regression failed: %v\n%s", err, output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectoryRunnerParsesPrivateOutputAndRemovesSpool(t *testing.T) {
|
||||
t.Setenv("DINGTALK_CLIENT_SECRET", "fixture-credential-do-not-forward")
|
||||
root := t.TempDir()
|
||||
spool := filepath.Join(root, "spool")
|
||||
if err := os.Mkdir(spool, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
script := filepath.Join(root, "fake-sync.sh")
|
||||
fixture := `{"source":"weekly_report_live","synced_at":"2026-10-01T00:00:00Z","complete":true,"directory":{"departments":[{"id":"root","parent_id":"","name":"隔离测试部门"}],"people":[{"id":"fixture-user","department_ids":["root"]}]}}`
|
||||
body := "#!/bin/sh\nif [ -n \"${DINGTALK_CLIENT_SECRET:-}\" ]; then exit 3; fi\nwhile [ \"$#\" -gt 0 ]; do if [ \"$1\" = --output ]; then output=$2; shift; fi; shift; done\numask 077\nprintf '%s' '" + fixture + "' > \"$output\"\n"
|
||||
if err := os.WriteFile(script, []byte(body), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner := ExecDirectoryRunner{Python: "/bin/sh", Script: script, RuntimeRoot: root, SpoolRoot: spool, Timeout: time.Second}
|
||||
result, err := runner.Run(context.Background())
|
||||
if err != nil || len(result.Directory.People) != 1 {
|
||||
t.Fatalf("runner failed: %v", err)
|
||||
}
|
||||
entries, err := os.ReadDir(spool)
|
||||
if err != nil || len(entries) != 0 {
|
||||
t.Fatal("personnel spool leaked")
|
||||
}
|
||||
if err := os.WriteFile(script, []byte("#!/bin/sh\nprintf 'secret-driver-detail' >&2\nexit 1\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = runner.Run(context.Background())
|
||||
if err == nil || strings.Contains(err.Error(), "secret-driver-detail") {
|
||||
t.Fatal("runner error is missing or leaks child stderr")
|
||||
}
|
||||
entries, _ = os.ReadDir(spool)
|
||||
if len(entries) != 0 {
|
||||
t.Fatal("failed runner leaked spool")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectoryRunnerRejectsMalformedOrPublicPersonnelOutput(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
for _, mode := range []string{"malformed", "public"} {
|
||||
script := filepath.Join(root, mode+".sh")
|
||||
body := "#!/bin/sh\numask 077\nwhile [ \"$#\" -gt 0 ]; do if [ \"$1\" = --output ]; then output=$2; shift; fi; shift; done\nprintf '%s' '{not-json}' > \"$output\"\n"
|
||||
if mode == "public" {
|
||||
body += "printf '%s' '{\"source\":\"weekly_report_live\",\"synced_at\":\"2026-10-01T00:00:00Z\",\"complete\":true,\"directory\":{\"departments\":[{\"id\":\"root\",\"parent_id\":\"\",\"name\":\"fixture\"}],\"people\":[{\"id\":\"fixture-user\",\"department_ids\":[\"root\"]}]}}' > \"$output\"\nchmod 644 \"$output\"\n"
|
||||
}
|
||||
if err := os.WriteFile(script, []byte(body), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner := ExecDirectoryRunner{Python: "/bin/sh", Script: script, RuntimeRoot: root, SpoolRoot: root, Timeout: time.Second}
|
||||
if _, err := runner.Run(context.Background()); err == nil {
|
||||
t.Fatal("invalid output accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectoryRunnerDeadlineStopsChildAndCleansPrivateSpool(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
spool := filepath.Join(root, "spool")
|
||||
if err := os.Mkdir(spool, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
script := filepath.Join(root, "timeout.sh")
|
||||
if err := os.WriteFile(script, []byte("#!/bin/sh\nexec sleep 30\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner := ExecDirectoryRunner{Python: "/bin/sh", Script: script, RuntimeRoot: root, SpoolRoot: spool, Timeout: 50 * time.Millisecond}
|
||||
started := time.Now()
|
||||
if _, err := runner.Run(context.Background()); err == nil {
|
||||
t.Fatal("timed-out source reported success")
|
||||
}
|
||||
if time.Since(started) > 5*time.Second {
|
||||
t.Fatal("source process cleanup is unbounded")
|
||||
}
|
||||
entries, err := os.ReadDir(spool)
|
||||
if err != nil || len(entries) != 0 {
|
||||
t.Fatal("timed-out source retained personnel spool")
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ErrInvalid = errors.New("invalid organization data or region rules")
|
||||
var RegionNames = []string{"国内工业", "APAC", "EMEA", "America"}
|
||||
|
||||
type Department struct {
|
||||
ID string `json:"id"`
|
||||
ParentID string `json:"parent_id"`
|
||||
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"`
|
||||
}
|
||||
type Directory struct {
|
||||
Departments []Department `json:"departments"`
|
||||
People []Person `json:"people"`
|
||||
}
|
||||
type Rule struct {
|
||||
DepartmentID string `json:"department_id"`
|
||||
Region string `json:"region"`
|
||||
}
|
||||
type DepartmentView struct {
|
||||
Department
|
||||
Path string `json:"path"`
|
||||
Region string `json:"region"`
|
||||
Explicit bool `json:"explicit"`
|
||||
InheritedFrom string `json:"inherited_from"`
|
||||
}
|
||||
type PreviewResult struct {
|
||||
Departments []DepartmentView `json:"departments"`
|
||||
Regions map[string]int `json:"regions"`
|
||||
TotalPeople int `json:"total_people"`
|
||||
UnassignedPeople int `json:"unassigned_people"`
|
||||
ConflictingPeople int `json:"conflicting_people"`
|
||||
MissingDepartments []string `json:"missing_departments"`
|
||||
}
|
||||
|
||||
// Identity is department ID. Names and legacy keyword rules never decide ownership.
|
||||
func Preview(directory Directory, rules []Rule) (PreviewResult, error) {
|
||||
result := PreviewResult{Departments: []DepartmentView{}, Regions: map[string]int{}, MissingDepartments: []string{}, TotalPeople: len(directory.People)}
|
||||
if len(directory.Departments) == 0 || len(directory.Departments) > 20000 || len(directory.People) == 0 || len(directory.People) > 100000 || len(rules) > 20000 {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
for _, region := range RegionNames {
|
||||
result.Regions[region] = 0
|
||||
}
|
||||
departments := make(map[string]Department, len(directory.Departments))
|
||||
for _, d := range directory.Departments {
|
||||
if !validID(d.ID) || d.Name == "" || len(d.Name) > 1000 || strings.ContainsRune(d.Name, 0) {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
if _, ok := departments[d.ID]; ok {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
departments[d.ID] = d
|
||||
}
|
||||
direct := map[string]string{}
|
||||
for _, rule := range rules {
|
||||
if !validID(rule.DepartmentID) {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
if _, ok := result.Regions[rule.Region]; !ok {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
if _, ok := direct[rule.DepartmentID]; ok {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
direct[rule.DepartmentID] = rule.Region
|
||||
if _, ok := departments[rule.DepartmentID]; !ok {
|
||||
result.MissingDepartments = append(result.MissingDepartments, rule.DepartmentID)
|
||||
}
|
||||
}
|
||||
resolved := map[string]DepartmentView{}
|
||||
for _, d := range directory.Departments {
|
||||
seen := map[string]bool{}
|
||||
chain := []string{}
|
||||
region, from := "", ""
|
||||
for cur := d.ID; cur != ""; {
|
||||
node, ok := departments[cur]
|
||||
if !ok || seen[cur] || len(chain) > 100 {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
seen[cur] = true
|
||||
chain = append(chain, node.Name)
|
||||
if region == "" && direct[cur] != "" {
|
||||
region, from = direct[cur], cur
|
||||
}
|
||||
cur = node.ParentID
|
||||
}
|
||||
for left, right := 0, len(chain)-1; left < right; left, right = left+1, right-1 {
|
||||
chain[left], chain[right] = chain[right], chain[left]
|
||||
}
|
||||
view := DepartmentView{Department: d, Path: strings.Join(chain, "/"), Region: region, Explicit: direct[d.ID] != ""}
|
||||
if from != d.ID {
|
||||
view.InheritedFrom = from
|
||||
}
|
||||
resolved[d.ID] = view
|
||||
result.Departments = append(result.Departments, view)
|
||||
}
|
||||
people := map[string]bool{}
|
||||
for _, person := range directory.People {
|
||||
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
|
||||
regions := map[string]bool{}
|
||||
for _, id := range person.DepartmentIDs {
|
||||
department, ok := resolved[id]
|
||||
if !ok {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
if department.Region != "" {
|
||||
regions[department.Region] = true
|
||||
}
|
||||
}
|
||||
switch len(regions) {
|
||||
case 0:
|
||||
result.UnassignedPeople++
|
||||
case 1:
|
||||
for region := range regions {
|
||||
result.Regions[region]++
|
||||
}
|
||||
default:
|
||||
result.ConflictingPeople++
|
||||
}
|
||||
}
|
||||
sort.Slice(result.Departments, func(i, j int) bool {
|
||||
a, b := result.Departments[i], result.Departments[j]
|
||||
if a.Path == b.Path {
|
||||
return a.ID < b.ID
|
||||
}
|
||||
return a.Path < b.Path
|
||||
})
|
||||
sort.Strings(result.MissingDepartments)
|
||||
return result, nil
|
||||
}
|
||||
func validID(value string) bool {
|
||||
return value != "" && len(value) <= 256 && strings.TrimSpace(value) == value && !strings.ContainsAny(value, "\x00\r\n")
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func exampleDirectory() Directory {
|
||||
return Directory{Departments: []Department{
|
||||
{ID: "root", Name: "示例公司"},
|
||||
{ID: "sales", ParentID: "root", Name: "销售"},
|
||||
{ID: "apac", ParentID: "sales", Name: "业务组"},
|
||||
{ID: "leaf", ParentID: "apac", Name: "支持"},
|
||||
{ID: "other", ParentID: "root", Name: "业务组"},
|
||||
}, People: []Person{
|
||||
{ID: "p1", DepartmentIDs: []string{"sales"}},
|
||||
{ID: "p2", DepartmentIDs: []string{"leaf"}},
|
||||
{ID: "p3", DepartmentIDs: []string{"sales", "leaf"}},
|
||||
{ID: "p4", DepartmentIDs: []string{"other"}},
|
||||
}}
|
||||
}
|
||||
|
||||
func TestRegionPreviewUsesNearestExplicitAncestorAndCountsPeopleOnce(t *testing.T) {
|
||||
view, err := Preview(exampleDirectory(), []Rule{{DepartmentID: "sales", Region: "国内工业"}, {DepartmentID: "apac", Region: "APAC"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
byID := map[string]DepartmentView{}
|
||||
for _, d := range view.Departments {
|
||||
byID[d.ID] = d
|
||||
}
|
||||
if got := byID["leaf"]; got.Region != "APAC" || got.InheritedFrom != "apac" || got.Path != "示例公司/销售/业务组/支持" {
|
||||
t.Fatalf("wrong child inheritance: %+v", got)
|
||||
}
|
||||
if !byID["apac"].Explicit || byID["other"].Region != "" {
|
||||
t.Fatal("explicit choice or unmapped department lost")
|
||||
}
|
||||
if view.Regions["国内工业"] != 1 || view.Regions["APAC"] != 1 || view.UnassignedPeople != 1 || view.ConflictingPeople != 1 || view.TotalPeople != 4 {
|
||||
t.Fatalf("person duplicated or conflict silently resolved: %+v", view)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegionPreviewRejectsBrokenDirectoryAndDuplicateAssignments(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
mutate func(*Directory)
|
||||
rules []Rule
|
||||
}{
|
||||
{name: "cycle", mutate: func(d *Directory) { d.Departments[0].ParentID = "leaf" }},
|
||||
{name: "missing parent", mutate: func(d *Directory) { d.Departments[1].ParentID = "absent" }},
|
||||
{name: "duplicate department", mutate: func(d *Directory) { d.Departments = append(d.Departments, d.Departments[0]) }},
|
||||
{name: "duplicate person", mutate: func(d *Directory) { d.People = append(d.People, d.People[0]) }},
|
||||
{name: "missing membership", mutate: func(d *Directory) { d.People[0].DepartmentIDs = []string{"absent"} }},
|
||||
{name: "conflicting direct rules", rules: []Rule{{DepartmentID: "sales", Region: "国内工业"}, {DepartmentID: "sales", Region: "APAC"}}},
|
||||
{name: "unknown region", rules: []Rule{{DepartmentID: "sales", Region: "automatic"}}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
d := exampleDirectory()
|
||||
if tc.mutate != nil {
|
||||
tc.mutate(&d)
|
||||
}
|
||||
_, err := Preview(d, tc.rules)
|
||||
if !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("must fail closed, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegionPreviewKeepsMissingRulesAndDoesNotInventPrimaryDepartment(t *testing.T) {
|
||||
d := exampleDirectory()
|
||||
d.People = append(d.People, Person{ID: "p5", DepartmentIDs: []string{"apac", "leaf"}})
|
||||
view, err := Preview(d, []Rule{{DepartmentID: "sales", Region: "国内工业"}, {DepartmentID: "apac", Region: "APAC"}, {DepartmentID: "removed", Region: "EMEA"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(view.MissingDepartments) != 1 || view.MissingDepartments[0] != "removed" || view.ConflictingPeople != 1 || view.Regions["APAC"] != 2 {
|
||||
t.Fatalf("lost orphan rule or duplicated same-region membership: %+v", view)
|
||||
}
|
||||
d.Departments[2].Name = "改名后的部门"
|
||||
renamed, err := Preview(d, []Rule{{DepartmentID: "sales", Region: "国内工业"}, {DepartmentID: "apac", Region: "APAC"}})
|
||||
if err != nil || renamed.Regions["APAC"] != 2 {
|
||||
t.Fatal("stable department ID did not survive rename")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
var ErrConflict = errors.New("organization snapshot or region revision changed")
|
||||
var ErrUnavailable = errors.New("organization store unavailable")
|
||||
var ErrNoDirectory = errors.New("organization directory has not been imported")
|
||||
|
||||
type Import struct {
|
||||
Source string `json:"source"`
|
||||
SyncedAt time.Time `json:"synced_at"`
|
||||
Complete bool `json:"complete"`
|
||||
Directory Directory `json:"directory"`
|
||||
}
|
||||
type SaveRequest struct {
|
||||
DirectoryID string `json:"directory_id"`
|
||||
BaseRevision string `json:"base_revision"`
|
||||
Rules []Rule `json:"rules"`
|
||||
}
|
||||
type State struct {
|
||||
State string `json:"state"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
DirectorySource string `json:"directory_source"`
|
||||
DirectorySyncedAt *time.Time `json:"directory_synced_at"`
|
||||
RevisionID string `json:"revision_id"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
Rules []Rule `json:"rules"`
|
||||
View PreviewResult `json:"view"`
|
||||
}
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
tenant string
|
||||
}
|
||||
|
||||
func NewStore(pool *pgxpool.Pool, tenant string) *Store { return &Store{pool: pool, tenant: tenant} }
|
||||
func (s *Store) available() bool { return s != nil && s.pool != nil && validID(s.tenant) }
|
||||
|
||||
type orgQuerier interface {
|
||||
QueryRow(context.Context, string, ...any) pgx.Row
|
||||
}
|
||||
|
||||
const readStateSQL = `SELECT d.id,d.source,d.synced_at,d.payload,COALESCE(r.id,''),COALESCE(r.rules,'[]'::jsonb),COALESCE(r.updated_by,''),r.created_at
|
||||
FROM qa_ops_organization_state st JOIN qa_ops_directory_snapshots d ON d.tenant_key=st.tenant_key AND d.id=st.directory_id
|
||||
LEFT JOIN qa_ops_region_revisions r ON r.tenant_key=st.tenant_key AND r.id=st.revision_id WHERE st.tenant_key=$1`
|
||||
|
||||
func (s *Store) read(ctx context.Context, q orgQuerier, lock bool) (State, Directory, error) {
|
||||
state := State{State: "empty", Rules: []Rule{}, View: PreviewResult{Departments: []DepartmentView{}, Regions: map[string]int{}, MissingDepartments: []string{}}}
|
||||
for _, r := range RegionNames {
|
||||
state.View.Regions[r] = 0
|
||||
}
|
||||
var directory Directory
|
||||
query := readStateSQL
|
||||
if lock {
|
||||
query += " FOR UPDATE OF st"
|
||||
}
|
||||
var payload, rules []byte
|
||||
err := q.QueryRow(ctx, query, s.tenant).Scan(&state.DirectoryID, &state.DirectorySource, &state.DirectorySyncedAt, &payload, &state.RevisionID, &rules, &state.UpdatedBy, &state.UpdatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return state, directory, nil
|
||||
}
|
||||
if err != nil || json.Unmarshal(payload, &directory) != nil || json.Unmarshal(rules, &state.Rules) != nil {
|
||||
return State{}, directory, ErrUnavailable
|
||||
}
|
||||
state.View, err = Preview(directory, state.Rules)
|
||||
if err != nil {
|
||||
return State{}, directory, ErrUnavailable
|
||||
}
|
||||
state.State = "ready"
|
||||
return state, directory, nil
|
||||
}
|
||||
func (s *Store) GetView(ctx context.Context) (State, error) {
|
||||
if !s.available() {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
state, _, err := s.read(ctx, s.pool, false)
|
||||
return state, err
|
||||
}
|
||||
func (s *Store) PreviewRules(ctx context.Context, request SaveRequest) (State, error) {
|
||||
if !s.available() {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
state, directory, err := s.read(ctx, s.pool, false)
|
||||
if err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
return applyRequest(state, directory, request)
|
||||
}
|
||||
func applyRequest(state State, directory Directory, request SaveRequest) (State, error) {
|
||||
if state.State != "ready" {
|
||||
return State{}, ErrNoDirectory
|
||||
}
|
||||
if request.DirectoryID != state.DirectoryID || request.BaseRevision != state.RevisionID {
|
||||
return State{}, ErrConflict
|
||||
}
|
||||
view, err := Preview(directory, request.Rules)
|
||||
if err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
// Missing saved paths are retained for operator review, never silently removed.
|
||||
old := map[string]string{}
|
||||
for _, rule := range state.Rules {
|
||||
old[rule.DepartmentID] = rule.Region
|
||||
}
|
||||
for _, missing := range view.MissingDepartments {
|
||||
for _, rule := range request.Rules {
|
||||
if rule.DepartmentID == missing && old[missing] != rule.Region {
|
||||
return State{}, ErrInvalid
|
||||
}
|
||||
}
|
||||
}
|
||||
state.View = view
|
||||
state.Rules = append([]Rule{}, request.Rules...)
|
||||
sort.Slice(state.Rules, func(i, j int) bool { return state.Rules[i].DepartmentID < state.Rules[j].DepartmentID })
|
||||
return state, nil
|
||||
}
|
||||
func (s *Store) SaveRules(ctx context.Context, request SaveRequest, actor string) (State, error) {
|
||||
if !s.available() {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
if !validID(actor) {
|
||||
return State{}, ErrInvalid
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
current, directory, err := s.read(ctx, tx, true)
|
||||
if err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
next, err := applyRequest(current, directory, request)
|
||||
if err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
before := append([]Rule{}, current.Rules...)
|
||||
sort.Slice(before, func(i, j int) bool { return before[i].DepartmentID < before[j].DepartmentID })
|
||||
oldJSON, _ := json.Marshal(before)
|
||||
newJSON, _ := json.Marshal(next.Rules)
|
||||
if current.RevisionID != "" && string(oldJSON) == string(newJSON) {
|
||||
if tx.Commit(ctx) != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
var nonce [16]byte
|
||||
if _, err = rand.Read(nonce[:]); err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
next.RevisionID = "reg-" + hex.EncodeToString(nonce[:])
|
||||
next.UpdatedBy = actor
|
||||
var at time.Time
|
||||
if err = tx.QueryRow(ctx, `INSERT INTO qa_ops_region_revisions(tenant_key,id,directory_id,rules,updated_by) VALUES($1,$2,$3,$4,$5) RETURNING created_at`, s.tenant, next.RevisionID, next.DirectoryID, newJSON, actor).Scan(&at); err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
next.UpdatedAt = &at
|
||||
if _, err = tx.Exec(ctx, `UPDATE qa_ops_organization_state SET revision_id=$2 WHERE tenant_key=$1`, s.tenant, next.RevisionID); err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
return next, nil
|
||||
}
|
||||
func (s *Store) ReplaceDirectory(ctx context.Context, input Import) (State, error) {
|
||||
return s.replaceDirectory(ctx, input, nil)
|
||||
}
|
||||
func (s *Store) replaceDirectory(ctx context.Context, input Import, lease *jobs.Job) (State, error) {
|
||||
if !s.available() {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
if !input.Complete || input.SyncedAt.IsZero() || input.SyncedAt.After(time.Now().Add(time.Minute)) || (input.Source != "weekly_report_snapshot" && input.Source != "weekly_report_live") {
|
||||
return State{}, ErrInvalid
|
||||
}
|
||||
if _, err := Preview(input.Directory, nil); err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
raw, err := json.Marshal(input)
|
||||
if err != nil || len(raw) > 16<<20 {
|
||||
return State{}, ErrInvalid
|
||||
}
|
||||
sum := sha256.Sum256(raw)
|
||||
id := "dir-" + hex.EncodeToString(sum[:])
|
||||
payload, _ := json.Marshal(input.Directory)
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
if lease != nil {
|
||||
if _, err = s.syncLease(ctx, tx, *lease, true); err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO qa_ops_directory_snapshots(tenant_key,id,source,synced_at,payload) VALUES($1,$2,$3,$4,$5) ON CONFLICT(tenant_key,id) DO NOTHING`, s.tenant, id, input.Source, input.SyncedAt, payload); err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `INSERT INTO qa_ops_organization_state(tenant_key,directory_id) VALUES($1,$2) ON CONFLICT(tenant_key) DO UPDATE SET directory_id=EXCLUDED.directory_id WHERE qa_ops_organization_state.directory_id=EXCLUDED.directory_id OR (SELECT synced_at FROM qa_ops_directory_snapshots WHERE tenant_key=$1 AND id=qa_ops_organization_state.directory_id)<$3`, s.tenant, id, input.SyncedAt)
|
||||
if err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return State{}, ErrConflict
|
||||
}
|
||||
if lease != nil {
|
||||
result, _ := json.Marshal(SyncResult{DirectoryID: id, Departments: len(input.Directory.Departments), People: len(input.Directory.People), SyncedAt: input.SyncedAt})
|
||||
tag, err = tx.Exec(ctx, `UPDATE jobs SET payload=jsonb_set(payload,'{result}',$3::jsonb),updated_at=now() WHERE id=$1 AND lease_owner=$2 AND state='running' AND lease_until>clock_timestamp() AND attempt=$4`, lease.ID, lease.LeaseOwner, result, lease.Attempt)
|
||||
if err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return State{}, ErrSyncLease
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
return s.GetView(ctx)
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package qaopsorg_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
)
|
||||
|
||||
func TestOrganizationStoreRoundTripAndOptimisticConflict(t *testing.T) {
|
||||
dsn := os.Getenv("KG_QAOPS_ORG_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("explicit isolated organization database is not configured")
|
||||
}
|
||||
u, err := url.Parse(dsn)
|
||||
if err != nil || u.Hostname() != "127.0.0.1" || !strings.HasPrefix(u.Path, "/kg_qaops_org_test_") || os.Getenv("KG_QAOPS_ORG_TEST_ISOLATED") != "1" {
|
||||
t.Fatal("refusing non-isolated organization database")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal("test database connection failed")
|
||||
}
|
||||
defer pool.Close()
|
||||
if err = postgresstore.ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := qaopsorg.NewStore(pool, "fixture-tenant")
|
||||
empty, err := store.GetView(ctx)
|
||||
if err != nil || empty.State != "empty" {
|
||||
t.Fatalf("empty state must be explicit: %+v %v", empty, err)
|
||||
}
|
||||
input := qaopsorg.Import{Source: "weekly_report_snapshot", SyncedAt: time.Date(2026, 9, 27, 14, 3, 44, 0, time.UTC), Complete: true, Directory: qaopsorg.Directory{
|
||||
Departments: []qaopsorg.Department{{ID: "root", Name: "示例公司"}, {ID: "a", ParentID: "root", Name: "国内组"}, {ID: "b", ParentID: "a", Name: "海外组"}},
|
||||
People: []qaopsorg.Person{{ID: "u1", DepartmentIDs: []string{"a"}}, {ID: "u2", DepartmentIDs: []string{"b"}}},
|
||||
}}
|
||||
imported, err := store.ReplaceDirectory(ctx, input)
|
||||
if err != nil || imported.DirectoryID == "" || imported.View.TotalPeople != 2 {
|
||||
t.Fatalf("import failed: %+v %v", imported, err)
|
||||
}
|
||||
request := qaopsorg.SaveRequest{DirectoryID: imported.DirectoryID, Rules: []qaopsorg.Rule{{DepartmentID: "a", Region: "国内工业"}, {DepartmentID: "b", Region: "APAC"}}}
|
||||
preview, err := store.PreviewRules(ctx, request)
|
||||
if err != nil || preview.View.Regions["APAC"] != 1 {
|
||||
t.Fatalf("preview failed: %+v %v", preview, err)
|
||||
}
|
||||
before, _ := store.GetView(ctx)
|
||||
if before.RevisionID != "" {
|
||||
t.Fatal("preview must not persist changes")
|
||||
}
|
||||
saved, err := store.SaveRules(ctx, request, "fixture-admin")
|
||||
if err != nil || saved.RevisionID == "" || saved.UpdatedBy != "fixture-admin" {
|
||||
t.Fatalf("save failed: %+v %v", saved, err)
|
||||
}
|
||||
read, err := store.GetView(ctx)
|
||||
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)
|
||||
}
|
||||
request.BaseRevision = saved.RevisionID
|
||||
again, err := store.SaveRules(ctx, request, "fixture-admin")
|
||||
if err != nil || again.RevisionID != saved.RevisionID {
|
||||
t.Fatal("unchanged save must not append duplicate revisions")
|
||||
}
|
||||
broken := input
|
||||
broken.Complete = false
|
||||
if _, err = store.ReplaceDirectory(ctx, broken); !errors.Is(err, qaopsorg.ErrInvalid) {
|
||||
t.Fatal("partial sync activated")
|
||||
}
|
||||
request.Rules = []qaopsorg.Rule{{DepartmentID: "absent", Region: "EMEA"}}
|
||||
if _, err = store.SaveRules(ctx, request, "fixture-admin"); !errors.Is(err, qaopsorg.ErrInvalid) {
|
||||
t.Fatal("invalid rule persisted")
|
||||
}
|
||||
after, _ := store.GetView(ctx)
|
||||
if after.RevisionID != saved.RevisionID {
|
||||
t.Fatal("failed writes changed active revision")
|
||||
}
|
||||
other, _ := qaopsorg.NewStore(pool, "another-tenant").GetView(ctx)
|
||||
if other.State != "empty" {
|
||||
t.Fatal("directory leaked across tenants")
|
||||
}
|
||||
input.Directory.Departments = input.Directory.Departments[:2]
|
||||
input.Directory.People = input.Directory.People[:1]
|
||||
input.SyncedAt = input.SyncedAt.Add(time.Hour)
|
||||
newer, err := store.ReplaceDirectory(ctx, input)
|
||||
if err != nil || newer.RevisionID != saved.RevisionID || len(newer.View.MissingDepartments) != 1 {
|
||||
t.Fatalf("directory refresh deleted rules or hid missing department: %+v %v", newer, err)
|
||||
}
|
||||
if _, err = store.PreviewRules(ctx, request); !errors.Is(err, qaopsorg.ErrConflict) {
|
||||
t.Fatal("preview accepted an obsolete directory snapshot")
|
||||
}
|
||||
older := input
|
||||
start := make(chan struct{})
|
||||
results := make(chan error, 2)
|
||||
for _, region := range []string{"APAC", "EMEA"} {
|
||||
go func(region string) {
|
||||
<-start
|
||||
_, failure := store.SaveRules(ctx, qaopsorg.SaveRequest{DirectoryID: newer.DirectoryID, BaseRevision: newer.RevisionID, Rules: []qaopsorg.Rule{{DepartmentID: "a", Region: region}}}, "concurrent-admin")
|
||||
results <- failure
|
||||
}(region)
|
||||
}
|
||||
close(start)
|
||||
successes, conflicts := 0, 0
|
||||
for range 2 {
|
||||
failure := <-results
|
||||
if failure == nil {
|
||||
successes++
|
||||
} else if errors.Is(failure, qaopsorg.ErrConflict) {
|
||||
conflicts++
|
||||
} else {
|
||||
t.Fatal(failure)
|
||||
}
|
||||
}
|
||||
if successes != 1 || conflicts != 1 {
|
||||
t.Fatalf("concurrent stale writes were not serialized: success=%d conflict=%d", successes, conflicts)
|
||||
}
|
||||
older.SyncedAt = older.SyncedAt.Add(-2 * time.Hour)
|
||||
if _, err = store.ReplaceDirectory(ctx, older); !errors.Is(err, qaopsorg.ErrConflict) {
|
||||
t.Fatalf("older directory rolled back the active roster: %v", err)
|
||||
}
|
||||
var revisions int
|
||||
if err = pool.QueryRow(ctx, "SELECT count(*) FROM qa_ops_region_revisions WHERE tenant_key=$1", "fixture-tenant").Scan(&revisions); err != nil || revisions != 2 {
|
||||
t.Fatal("revision history changed unexpectedly")
|
||||
}
|
||||
if err = postgresstore.RollbackLatestMigration(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var removed bool
|
||||
if err = pool.QueryRow(ctx, "SELECT to_regclass('qa_ops_organization_state') IS NULL AND to_regclass('qa_ops_region_revisions') IS NULL AND to_regclass('qa_ops_directory_snapshots') IS NULL").Scan(&removed); err != nil || !removed {
|
||||
t.Fatal("organization down migration left residue")
|
||||
}
|
||||
if err = postgresstore.ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if state, failure := store.GetView(ctx); failure != nil || state.State != "empty" {
|
||||
t.Fatal("organization migration could not be reapplied")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
var ErrSyncWorkerUnavailable = errors.New("directory sync worker is not connected")
|
||||
|
||||
const SyncJobPrefix = "qaops.directory.sync."
|
||||
|
||||
var ErrSyncLease = errors.New("directory sync lease is no longer owned")
|
||||
|
||||
type DirectoryRunner interface {
|
||||
Run(context.Context) (Import, error)
|
||||
}
|
||||
type SyncReceipt struct {
|
||||
JobID string `json:"job_id"`
|
||||
Deduplicated bool `json:"deduplicated"`
|
||||
}
|
||||
type SyncResult struct {
|
||||
DirectoryID string `json:"directory_id"`
|
||||
Departments int `json:"departments"`
|
||||
People int `json:"people"`
|
||||
SyncedAt time.Time `json:"synced_at"`
|
||||
}
|
||||
type SyncJob struct {
|
||||
ID string `json:"id"`
|
||||
State string `json:"state"`
|
||||
Attempt int `json:"attempt"`
|
||||
MaxAttempts int `json:"max_attempts"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
Result *SyncResult `json:"result"`
|
||||
}
|
||||
type SyncStatus struct {
|
||||
Configured bool `json:"configured"`
|
||||
WorkerReady bool `json:"worker_ready"`
|
||||
Job *SyncJob `json:"job"`
|
||||
}
|
||||
|
||||
func (s *Store) SyncJobType() string {
|
||||
h := sha256.Sum256([]byte(s.tenant))
|
||||
return SyncJobPrefix + hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
const syncWorkerReadySQL = `SELECT EXISTS(SELECT 1 FROM worker_heartbeats WHERE $1=ANY(string_to_array(job_types,',')) AND last_seen_at>clock_timestamp()-interval '2 minutes') OR EXISTS(SELECT 1 FROM jobs WHERE type=$1 AND state='running' AND lease_until>clock_timestamp())`
|
||||
|
||||
func (s *Store) EnqueueSync(ctx context.Context, key, actor string) (SyncReceipt, bool, error) {
|
||||
if !s.available() {
|
||||
return SyncReceipt{}, false, ErrUnavailable
|
||||
}
|
||||
if !validID(key) || len(key) > 128 || !validID(actor) {
|
||||
return SyncReceipt{}, false, ErrInvalid
|
||||
}
|
||||
fp := sha256.Sum256([]byte(actor))
|
||||
now := time.Now()
|
||||
raw, replayed, err := postgresstore.NewStore(s.pool).ExecuteOperation(ctx, s.SyncJobType(), key, hex.EncodeToString(fp[:]), now, func(tx pgx.Tx) (json.RawMessage, error) {
|
||||
if _, e := tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", s.SyncJobType()); e != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
// A last-attempt process may die without recording failure. A new explicit
|
||||
// action retires that exhausted lease; it never impersonates a live owner.
|
||||
if _, e := tx.Exec(ctx, `UPDATE jobs SET state='failed',last_error='directory worker stopped; previous snapshot retained',last_error_code='directory_sync_failed',lease_owner=NULL,lease_until=NULL,updated_at=now() WHERE type=$1 AND state='running' AND lease_until<clock_timestamp() AND attempt>=max_attempts`, s.SyncJobType()); e != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
var active string
|
||||
e := tx.QueryRow(ctx, `SELECT id FROM jobs WHERE type=$1 AND state IN ('pending','running','retry') ORDER BY created_at DESC,id DESC LIMIT 1`, s.SyncJobType()).Scan(&active)
|
||||
if e == nil {
|
||||
return json.Marshal(SyncReceipt{JobID: active, Deduplicated: true})
|
||||
}
|
||||
if !errors.Is(e, pgx.ErrNoRows) {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
var ready bool
|
||||
if tx.QueryRow(ctx, syncWorkerReadySQL, s.SyncJobType()).Scan(&ready) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
if !ready {
|
||||
return nil, ErrSyncWorkerUnavailable
|
||||
}
|
||||
digest := sha256.Sum256([]byte(s.SyncJobType() + ":" + key))
|
||||
id := "job-" + hex.EncodeToString(digest[:16])
|
||||
payload, _ := json.Marshal(map[string]string{"triggered_by": actor})
|
||||
job, e := postgresstore.NewStore(tx).Enqueue(ctx, jobs.EnqueueRequest{ID: id, Type: s.SyncJobType(), Payload: payload, AvailableAt: now, MaxAttempts: 3, IdempotencyKey: s.SyncJobType() + ":" + key}, now)
|
||||
if e != nil || job == nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return json.Marshal(SyncReceipt{JobID: job.ID})
|
||||
})
|
||||
if errors.Is(err, postgresstore.ErrOperationRequestConflict) {
|
||||
return SyncReceipt{}, false, ErrConflict
|
||||
}
|
||||
if err != nil {
|
||||
return SyncReceipt{}, false, err
|
||||
}
|
||||
var result SyncReceipt
|
||||
if json.Unmarshal(raw, &result) != nil || result.JobID == "" {
|
||||
return SyncReceipt{}, false, ErrUnavailable
|
||||
}
|
||||
return result, replayed, nil
|
||||
}
|
||||
func (s *Store) GetSyncStatus(ctx context.Context) (SyncStatus, error) {
|
||||
result := SyncStatus{Configured: true}
|
||||
if !s.available() {
|
||||
return SyncStatus{}, ErrUnavailable
|
||||
}
|
||||
if s.pool.QueryRow(ctx, syncWorkerReadySQL, s.SyncJobType()).Scan(&result.WorkerReady) != nil {
|
||||
return SyncStatus{}, ErrUnavailable
|
||||
}
|
||||
var job SyncJob
|
||||
var payload []byte
|
||||
var expired bool
|
||||
err := s.pool.QueryRow(ctx, `SELECT id,state,attempt,max_attempts,updated_at,payload,COALESCE(state='running' AND lease_until<clock_timestamp(),false) FROM jobs WHERE type=$1 ORDER BY created_at DESC,id DESC LIMIT 1`, s.SyncJobType()).Scan(&job.ID, &job.State, &job.Attempt, &job.MaxAttempts, &job.UpdatedAt, &payload, &expired)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return result, nil
|
||||
}
|
||||
if err != nil {
|
||||
return SyncStatus{}, ErrUnavailable
|
||||
}
|
||||
var parsed struct {
|
||||
Result *SyncResult `json:"result"`
|
||||
}
|
||||
if json.Unmarshal(payload, &parsed) != nil {
|
||||
return SyncStatus{}, ErrUnavailable
|
||||
}
|
||||
job.Result = parsed.Result
|
||||
if expired {
|
||||
job.State = "retry"
|
||||
if job.Attempt >= job.MaxAttempts {
|
||||
job.State = "failed"
|
||||
}
|
||||
}
|
||||
if job.State == "failed" || job.State == "retry" {
|
||||
job.ErrorCode = "directory_sync_failed"
|
||||
}
|
||||
result.Job = &job
|
||||
return result, nil
|
||||
}
|
||||
func (s *Store) syncLease(ctx context.Context, q orgQuerier, job jobs.Job, lock bool) (*SyncResult, error) {
|
||||
if job.Type != s.SyncJobType() || job.LeaseOwner == "" {
|
||||
return nil, ErrSyncLease
|
||||
}
|
||||
query := `SELECT payload FROM jobs WHERE id=$1 AND type=$2 AND state='running' AND lease_owner=$3 AND attempt=$4 AND lease_until>clock_timestamp() AND EXISTS(SELECT 1 FROM operation_requests op WHERE op.operation_type=jobs.type AND op.result->>'job_id'=jobs.id)`
|
||||
if lock {
|
||||
query += " FOR UPDATE"
|
||||
}
|
||||
var raw []byte
|
||||
if q.QueryRow(ctx, query, job.ID, s.SyncJobType(), job.LeaseOwner, job.Attempt).Scan(&raw) != nil {
|
||||
return nil, ErrSyncLease
|
||||
}
|
||||
var payload struct {
|
||||
Result *SyncResult `json:"result"`
|
||||
}
|
||||
if json.Unmarshal(raw, &payload) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return payload.Result, nil
|
||||
}
|
||||
func (s *Store) HandleDirectorySync(ctx context.Context, job jobs.Job, runner DirectoryRunner) error {
|
||||
if !s.available() || runner == nil {
|
||||
return ErrDirectorySync
|
||||
}
|
||||
result, err := s.syncLease(ctx, s.pool, job, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if result != nil {
|
||||
return nil
|
||||
}
|
||||
input, err := runner.Run(ctx)
|
||||
if err != nil {
|
||||
return ErrDirectorySync
|
||||
}
|
||||
if input.Source != "weekly_report_live" {
|
||||
return jobs.Permanent("directory_sync_failed", ErrDirectorySync)
|
||||
}
|
||||
_, err = s.replaceDirectory(ctx, input, &job)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrSyncLease) {
|
||||
return err
|
||||
}
|
||||
return ErrDirectorySync
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
package qaopsorg_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/jobs"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
)
|
||||
|
||||
type syncRunner func(context.Context) (qaopsorg.Import, error)
|
||||
|
||||
func (f syncRunner) Run(ctx context.Context) (qaopsorg.Import, error) { return f(ctx) }
|
||||
func TestDirectorySyncQueueDurableReplayAndLeaseFencing(t *testing.T) {
|
||||
dsn := os.Getenv("KG_QAOPS_ORG_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("explicit isolated organization database is not configured")
|
||||
}
|
||||
u, err := url.Parse(dsn)
|
||||
if err != nil || u.Hostname() != "127.0.0.1" || !strings.HasPrefix(u.Path, "/kg_qaops_org_test_") || os.Getenv("KG_QAOPS_ORG_TEST_ISOLATED") != "1" {
|
||||
t.Fatal("refusing non-isolated organization database")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal("isolated connection failed")
|
||||
}
|
||||
defer pool.Close()
|
||||
if err = postgresstore.ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := qaopsorg.NewStore(pool, "sync-fixture-tenant")
|
||||
queue := postgresstore.NewStore(pool)
|
||||
initial := qaopsorg.Import{Source: "weekly_report_live", Complete: true, SyncedAt: time.Now().Add(-time.Hour), Directory: qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "root", Name: "同步夹具"}}, People: []qaopsorg.Person{{ID: "fixture-person", DepartmentIDs: []string{"root"}}}}}
|
||||
old, err := store.ReplaceDirectory(ctx, initial)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saved, err := store.SaveRules(ctx, qaopsorg.SaveRequest{DirectoryID: old.DirectoryID, Rules: []qaopsorg.Rule{{DepartmentID: "root", Region: "APAC"}}}, "fixture-admin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err = store.EnqueueSync(ctx, "op-no-worker", "fixture-admin"); !errors.Is(err, qaopsorg.ErrSyncWorkerUnavailable) {
|
||||
t.Fatalf("disconnected worker accepted: %v", err)
|
||||
}
|
||||
if _, err = queue.Claim(ctx, "fixture-sync-worker", []string{store.SyncJobType()}, time.Now(), time.Minute); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var first qaopsorg.SyncReceipt
|
||||
var created atomic.Int32
|
||||
var wg sync.WaitGroup
|
||||
failures := make(chan error, 12)
|
||||
ids := make(chan string, 12)
|
||||
for range 12 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
r, replay, e := qaopsorg.NewStore(pool, "sync-fixture-tenant").EnqueueSync(ctx, "op-same-action", "fixture-admin")
|
||||
if e != nil {
|
||||
failures <- e
|
||||
return
|
||||
}
|
||||
if !replay {
|
||||
created.Add(1)
|
||||
}
|
||||
ids <- r.JobID
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(failures)
|
||||
for e := range failures {
|
||||
t.Fatal(e)
|
||||
}
|
||||
close(ids)
|
||||
for id := range ids {
|
||||
if first.JobID == "" {
|
||||
first.JobID = id
|
||||
}
|
||||
if id != first.JobID {
|
||||
t.Fatal("duplicate effect")
|
||||
}
|
||||
}
|
||||
if created.Load() != 1 {
|
||||
t.Fatal("operation replay was not durable")
|
||||
}
|
||||
reused, _, err := store.EnqueueSync(ctx, "op-another-click", "fixture-admin")
|
||||
if err != nil || !reused.Deduplicated || reused.JobID != first.JobID {
|
||||
t.Fatal("in-flight clicks did not coalesce")
|
||||
}
|
||||
if _, _, err = store.EnqueueSync(ctx, "op-same-action", "another-admin"); !errors.Is(err, qaopsorg.ErrConflict) {
|
||||
t.Fatal("actor fingerprint conflict ignored")
|
||||
}
|
||||
other, _ := qaopsorg.NewStore(pool, "other-sync-tenant").GetSyncStatus(ctx)
|
||||
if other.Job != nil {
|
||||
t.Fatal("job leaked across tenants")
|
||||
}
|
||||
var n int
|
||||
if err = pool.QueryRow(ctx, "SELECT count(*) FROM jobs WHERE type=$1", store.SyncJobType()).Scan(&n); err != nil || n != 1 {
|
||||
t.Fatal("job count must remain one")
|
||||
}
|
||||
job, err := queue.Claim(ctx, "worker-before-crash", []string{store.SyncJobType()}, time.Now(), time.Minute)
|
||||
if err != nil || job == nil {
|
||||
t.Fatal("job was not durable/claimable")
|
||||
}
|
||||
// A different process can reclaim expired work; the old owner must not activate data.
|
||||
if _, err = pool.Exec(ctx, "UPDATE jobs SET lease_until=now()-interval '1 second' WHERE id=$1", job.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reclaimed, err := queue.Claim(ctx, "worker-after-restart", []string{store.SyncJobType()}, time.Now(), time.Minute)
|
||||
if err != nil || reclaimed == nil || reclaimed.Attempt != 2 {
|
||||
t.Fatal("expired lease did not resume")
|
||||
}
|
||||
newer := initial
|
||||
newer.SyncedAt = time.Now()
|
||||
newer.Directory.People = append(append([]qaopsorg.Person{}, initial.Directory.People...), qaopsorg.Person{ID: "fixture-person-2", DepartmentIDs: []string{"root"}})
|
||||
var fetched atomic.Int32
|
||||
run := syncRunner(func(context.Context) (qaopsorg.Import, error) { fetched.Add(1); return newer, nil })
|
||||
if err = store.HandleDirectorySync(ctx, *job, run); err == nil {
|
||||
t.Fatal("stale owner activated a snapshot")
|
||||
}
|
||||
still, _ := store.GetView(ctx)
|
||||
if still.DirectoryID != old.DirectoryID {
|
||||
t.Fatal("stale lease changed active data")
|
||||
}
|
||||
if err = store.HandleDirectorySync(ctx, *reclaimed, run); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
count := fetched.Load()
|
||||
// Crash after committing the snapshot, before queue.Complete: do not fetch twice.
|
||||
if err = store.HandleDirectorySync(ctx, *reclaimed, run); err != nil || fetched.Load() != count {
|
||||
t.Fatal("committed source was fetched again")
|
||||
}
|
||||
if err = queue.Complete(ctx, reclaimed.ID, reclaimed.LeaseOwner, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current, _ := store.GetView(ctx)
|
||||
if current.View.TotalPeople != 2 || current.RevisionID != saved.RevisionID || current.View.Regions["APAC"] != 2 {
|
||||
t.Fatal("refresh lost regional rules or failed to activate")
|
||||
}
|
||||
status, err := store.GetSyncStatus(ctx)
|
||||
if err != nil || status.Job == nil || status.Job.State != "completed" || status.Job.Result == nil || status.Job.Result.People != 2 {
|
||||
t.Fatal("safe status missing durable result")
|
||||
}
|
||||
raw, _ := json.Marshal(status)
|
||||
if strings.Contains(string(raw), "fixture-person") || strings.Contains(string(raw), "lease_owner") {
|
||||
t.Fatal("personnel/lease details leaked in status")
|
||||
}
|
||||
// Failure must preserve the previous complete directory and never store raw exceptions.
|
||||
failed, _, err := store.EnqueueSync(ctx, "op-fails", "fixture-admin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bad, err := queue.Claim(ctx, "worker-failure", []string{store.SyncJobType()}, time.Now(), time.Minute)
|
||||
if err != nil || bad == nil || bad.ID != failed.JobID {
|
||||
t.Fatal("failure job was not enqueued")
|
||||
}
|
||||
failure := store.HandleDirectorySync(ctx, *bad, syncRunner(func(context.Context) (qaopsorg.Import, error) {
|
||||
return qaopsorg.Import{}, errors.New("sensitive-fixture-must-not-escape")
|
||||
}))
|
||||
if failure == nil || strings.Contains(failure.Error(), "sensitive-fixture") {
|
||||
t.Fatal("unsafe source exception")
|
||||
}
|
||||
if err = queue.Fail(ctx, bad.ID, bad.LeaseOwner, failure.Error(), "directory_sync_failed", time.Now(), time.Now().Add(time.Minute)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kept, _ := store.GetView(ctx)
|
||||
if kept.DirectoryID != current.DirectoryID || kept.RevisionID != saved.RevisionID {
|
||||
t.Fatal("failed refresh replaced valid state")
|
||||
}
|
||||
late := qaopsorg.NewStore(pool, "late-fence-tenant")
|
||||
lateOld, err := late.ReplaceDirectory(ctx, initial)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = queue.Claim(ctx, "late-worker", []string{late.SyncJobType()}, time.Now(), time.Minute); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err = late.EnqueueSync(ctx, "op-late-fence", "fixture-admin"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lateJob, err := queue.Claim(ctx, "late-worker", []string{late.SyncJobType()}, time.Now(), time.Minute)
|
||||
if err != nil || lateJob == nil {
|
||||
t.Fatal("late-fence job unavailable")
|
||||
}
|
||||
lateErr := late.HandleDirectorySync(ctx, *lateJob, syncRunner(func(context.Context) (qaopsorg.Import, error) {
|
||||
_, failure := pool.Exec(ctx, "UPDATE jobs SET lease_owner='replacement-worker',attempt=attempt+1,lease_until=now()+interval '1 minute' WHERE id=$1", lateJob.ID)
|
||||
return newer, failure
|
||||
}))
|
||||
if lateErr == nil {
|
||||
t.Fatal("lease lost DURING source fetch was not fenced at commit")
|
||||
}
|
||||
lateKept, _ := late.GetView(ctx)
|
||||
if lateKept.DirectoryID != lateOld.DirectoryID {
|
||||
t.Fatal("late stale worker activated data")
|
||||
}
|
||||
if err = pool.QueryRow(ctx, "SELECT count(*) FROM qa_ops_directory_snapshots WHERE tenant_key=$1", "late-fence-tenant").Scan(&n); err != nil || n != 1 {
|
||||
t.Fatal("rejected stale snapshot left durable rows")
|
||||
}
|
||||
if _, err = pool.Exec(ctx, "UPDATE jobs SET lease_until=now()-interval '1 second' WHERE id=$1", lateJob.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
interrupted, err := late.GetSyncStatus(ctx)
|
||||
if err != nil || interrupted.Job == nil || interrupted.Job.State != "retry" {
|
||||
t.Fatal("interrupted lease must wait for takeover, not claim active source processing")
|
||||
}
|
||||
if _, err = pool.Exec(ctx, "UPDATE jobs SET attempt=max_attempts,lease_until=now()-interval '1 second' WHERE id=$1", lateJob.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
exhausted, err := late.GetSyncStatus(ctx)
|
||||
if err != nil || exhausted.Job == nil || exhausted.Job.State != "failed" {
|
||||
t.Fatal("exhausted crashed worker reported running forever")
|
||||
}
|
||||
fresh, _, err := late.EnqueueSync(ctx, "op-after-exhausted", "fixture-admin")
|
||||
if err != nil || fresh.JobID == lateJob.ID {
|
||||
t.Fatal("explicit retry could not replace an exhausted crashed job")
|
||||
}
|
||||
ghost := qaopsorg.NewStore(pool, "unadmitted-tenant")
|
||||
if _, err = ghost.ReplaceDirectory(ctx, initial); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = queue.Enqueue(ctx, jobs.EnqueueRequest{ID: "fixture-unadmitted-job", Type: ghost.SyncJobType(), Payload: json.RawMessage(`{}`), AvailableAt: time.Now(), MaxAttempts: 1, IdempotencyKey: "fixture-unadmitted-job"}, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ghostJob, err := queue.Claim(ctx, "ghost-worker", []string{ghost.SyncJobType()}, time.Now(), time.Minute)
|
||||
if err != nil || ghostJob == nil {
|
||||
t.Fatal("forged fixture unavailable")
|
||||
}
|
||||
var ghostCalls int
|
||||
ghostErr := ghost.HandleDirectorySync(ctx, *ghostJob, syncRunner(func(context.Context) (qaopsorg.Import, error) { ghostCalls++; return newer, nil }))
|
||||
if ghostErr == nil || ghostCalls != 0 {
|
||||
t.Fatal("unadmitted generic task consumed the directory source")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
type SyncSettings struct {
|
||||
Enabled bool
|
||||
Tenant string
|
||||
Runner ExecDirectoryRunner
|
||||
}
|
||||
|
||||
func LoadSyncSettings(getenv func(string) string) (SyncSettings, error) {
|
||||
var s SyncSettings
|
||||
enabled := getenv("DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED")
|
||||
if enabled == "" || enabled == "false" {
|
||||
return s, nil
|
||||
}
|
||||
if enabled != "true" {
|
||||
return s, errors.New("invalid directory sync enable flag")
|
||||
}
|
||||
s.Tenant = getenv("DOBOTAI_OPS_TENANT_KEY")
|
||||
s.Runner = ExecDirectoryRunner{Python: getenv("DOBOTAI_OPS_DIRECTORY_SYNC_PYTHON"), Script: getenv("DOBOTAI_OPS_DIRECTORY_SYNC_SCRIPT"), RuntimeRoot: getenv("DOBOTAI_OPS_DIRECTORY_SYNC_RUNTIME_ROOT"), SpoolRoot: getenv("DOBOTAI_OPS_DIRECTORY_SYNC_SPOOL_ROOT"), Timeout: 20 * time.Minute}
|
||||
if value := getenv("DOBOTAI_OPS_DIRECTORY_SYNC_TIMEOUT"); value != "" {
|
||||
d, err := time.ParseDuration(value)
|
||||
if err != nil {
|
||||
return SyncSettings{}, errors.New("invalid directory sync timeout")
|
||||
}
|
||||
s.Runner.Timeout = d
|
||||
}
|
||||
if !validID(s.Tenant) || s.Runner.Timeout < time.Second || s.Runner.Timeout > 30*time.Minute {
|
||||
return SyncSettings{}, errors.New("directory sync binding is incomplete")
|
||||
}
|
||||
for _, path := range []string{s.Runner.Python, s.Runner.Script, s.Runner.RuntimeRoot, s.Runner.SpoolRoot} {
|
||||
if !filepath.IsAbs(path) || filepath.Clean(path) != path {
|
||||
return SyncSettings{}, errors.New("directory sync requires server-owned absolute paths")
|
||||
}
|
||||
}
|
||||
s.Enabled = true
|
||||
return s, nil
|
||||
}
|
||||
func (s SyncSettings) CheckWorkerRuntime() error {
|
||||
for _, path := range []string{s.Runner.Python, s.Runner.Script} {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
return ErrSyncWorkerUnavailable
|
||||
}
|
||||
}
|
||||
for _, path := range []string{s.Runner.RuntimeRoot, s.Runner.SpoolRoot} {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || !info.IsDir() {
|
||||
return ErrSyncWorkerUnavailable
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDirectorySyncSettingsAreExplicitAndServerOwned(t *testing.T) {
|
||||
values := map[string]string{}
|
||||
get := func(k string) string { return values[k] }
|
||||
off, err := LoadSyncSettings(get)
|
||||
if err != nil || off.Enabled {
|
||||
t.Fatal("sync must default off")
|
||||
}
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_ENABLED"] = "true"
|
||||
if _, err = LoadSyncSettings(get); err == nil {
|
||||
t.Fatal("unbound runtime accepted")
|
||||
}
|
||||
values["DOBOTAI_OPS_TENANT_KEY"] = "fixture-tenant"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_PYTHON"] = "/usr/bin/python3"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_SCRIPT"] = "/app/scripts/qa_ops_directory_sync.py"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_RUNTIME_ROOT"] = "/data/weekly-report"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_SPOOL_ROOT"] = "/data/private-spool"
|
||||
ready, err := LoadSyncSettings(get)
|
||||
if err != nil || !ready.Enabled || ready.Runner.Timeout != 20*time.Minute {
|
||||
t.Fatal("valid runtime not configured")
|
||||
}
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_TIMEOUT"] = "31m"
|
||||
if _, err = LoadSyncSettings(get); err == nil {
|
||||
t.Fatal("unbounded source timeout")
|
||||
}
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_TIMEOUT"] = "10m"
|
||||
values["DOBOTAI_OPS_DIRECTORY_SYNC_SCRIPT"] = "relative/script.py"
|
||||
if _, err = LoadSyncSettings(get); err == nil {
|
||||
t.Fatal("browser-like relative script accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Read-only bridge to the existing weekly-report contacts fetchers.
|
||||
|
||||
The bridge does not execute the weekly report, export spreadsheets, write its
|
||||
configuration, or infer company/department names. All new data stays in a private
|
||||
caller-selected JSON file for the governance importer.
|
||||
"""
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
import importlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import types
|
||||
from urllib.request import HTTPRedirectHandler, ProxyHandler, build_opener
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
|
||||
|
||||
class DirectorySyncError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _validate_directory(departments, people):
|
||||
if not departments or not people or len(departments) > 20000 or len(people) > 100000:
|
||||
raise DirectorySyncError('directory_integrity_failed')
|
||||
for identity, department in departments.items():
|
||||
if identity <= 0 or not department.get('name'):
|
||||
raise DirectorySyncError('directory_integrity_failed')
|
||||
seen = set()
|
||||
current = identity
|
||||
while current:
|
||||
if current in seen or current not in departments or len(seen) > 100:
|
||||
raise DirectorySyncError('directory_integrity_failed')
|
||||
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']):
|
||||
raise DirectorySyncError('directory_integrity_failed')
|
||||
|
||||
|
||||
def collect_directory(client, fetch_departments, fetch_users, get_detail, logger):
|
||||
if client.config.dry_run:
|
||||
raise DirectorySyncError('directory_dry_run_rejected')
|
||||
departments, denied, failed = fetch_departments(client, logger, None, None)
|
||||
if denied or failed or not departments:
|
||||
raise DirectorySyncError('directory_department_fetch_incomplete')
|
||||
departments = dict(departments)
|
||||
# Legacy full traversal returns children but omits the starting root. Read
|
||||
# actual missing ancestors; never manufacture a root or discard parent IDs.
|
||||
for _ in range(100):
|
||||
missing = sorted({int(d.get('parent_id') or 0) for d in departments.values()} - set(departments) - {0})
|
||||
if not missing:
|
||||
break
|
||||
for identity in missing:
|
||||
detail, denied, failed = get_detail(client, logger, identity)
|
||||
if denied or failed or not detail or int(detail.get('id') or 0) != identity or not detail.get('name'):
|
||||
raise DirectorySyncError('directory_ancestor_unavailable')
|
||||
departments[identity] = detail
|
||||
else:
|
||||
raise DirectorySyncError('directory_integrity_failed')
|
||||
people, denied, failed = fetch_users(client, logger, sorted(departments), enable_user_detail=False)
|
||||
if denied or failed:
|
||||
raise DirectorySyncError('directory_people_fetch_incomplete')
|
||||
_validate_directory(departments, people)
|
||||
return {
|
||||
'source': 'weekly_report_live',
|
||||
'synced_at': datetime.now(timezone.utc).isoformat(),
|
||||
'complete': True,
|
||||
'directory': {
|
||||
'departments': [
|
||||
{'id': str(identity), 'parent_id': str(int(d.get('parent_id') or 0)) if d.get('parent_id') else '', 'name': str(d['name'])}
|
||||
for identity, d in sorted(departments.items())
|
||||
],
|
||||
# List membership provides stable staff IDs; do not reuse the old
|
||||
# guessed primary department, employment policy or openId fallback.
|
||||
'people': [
|
||||
{'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())
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class _NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise DirectorySyncError('directory_redirect_rejected')
|
||||
|
||||
|
||||
def load_existing_runtime(root):
|
||||
root = Path(root)
|
||||
if not root.is_absolute() or not (root / 'scripts/dingtalk_sync/client.py').is_file():
|
||||
raise DirectorySyncError('directory_configuration_invalid')
|
||||
secret = root / '.env'
|
||||
info = secret.lstat()
|
||||
if not secret.is_file() or secret.is_symlink() or info.st_mode & 0o077:
|
||||
raise DirectorySyncError('directory_configuration_invalid')
|
||||
package_name = '_qaops_weekly_directory'
|
||||
package = types.ModuleType(package_name)
|
||||
package.__path__ = [str(root / 'scripts/dingtalk_sync')]
|
||||
sys.modules[package_name] = package
|
||||
client_module = importlib.import_module(package_name + '.client')
|
||||
dept_module = importlib.import_module(package_name + '.fetch_departments')
|
||||
people_module = importlib.import_module(package_name + '.fetch_users')
|
||||
config = client_module.load_sync_config(str(secret), str(root / 'config/dingtalk_sync.yaml'))
|
||||
if config.api_base_url.rstrip('/') != 'https://oapi.dingtalk.com' or config.dry_run or config.api_mode != 'topapi_v2':
|
||||
raise DirectorySyncError('directory_configuration_invalid')
|
||||
if not (1 <= config.timeout_seconds <= 30 and 0 <= config.max_retries <= 3 and 1 <= config.page_size <= 100):
|
||||
raise DirectorySyncError('directory_configuration_invalid')
|
||||
# Keep the old transport inside this private module namespace. Suppress its
|
||||
# potentially sensitive exception logging and refuse redirects/proxies.
|
||||
logger = logging.getLogger('qa_ops_directory_private')
|
||||
logger.handlers = [logging.NullHandler()]
|
||||
logger.propagate = False
|
||||
opener = build_opener(ProxyHandler({}), _NoRedirect())
|
||||
setattr(client_module, 'urlopen', opener.open)
|
||||
|
||||
class BoundedClient(client_module.DingtalkClient):
|
||||
def __init__(self):
|
||||
super().__init__(config, logger=logger)
|
||||
self.requests = 0
|
||||
self.pages = set()
|
||||
|
||||
def request_json(self, method, path, params=None, json_body=None, retry_on_business_error=True):
|
||||
self.requests += 1
|
||||
if self.requests > 10000:
|
||||
raise DirectorySyncError('directory_request_limit')
|
||||
if path.endswith('/listsub') or path.endswith('/user/list'):
|
||||
key = (path, json.dumps(json_body, sort_keys=True))
|
||||
if key in self.pages:
|
||||
raise DirectorySyncError('directory_pagination_repeated')
|
||||
self.pages.add(key)
|
||||
return super().request_json(method, path, params, json_body, retry_on_business_error)
|
||||
|
||||
return BoundedClient(), dept_module.fetch_all_departments, people_module.fetch_users, dept_module._get_department_detail, logger
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Fetch a complete read-only directory into private governance JSON; no weekly-report writes')
|
||||
parser.add_argument('--runtime-root', required=True)
|
||||
parser.add_argument('--output', required=True)
|
||||
parser.add_argument('--fetch-live-directory', action='store_true', required=True)
|
||||
args = parser.parse_args()
|
||||
output = Path(args.output)
|
||||
if not output.is_absolute() or output.exists():
|
||||
raise DirectorySyncError('directory_output_must_be_new_absolute_path')
|
||||
client, departments, people, detail, logger = load_existing_runtime(args.runtime_root)
|
||||
print(json.dumps({'stage': 'fetching_live_directory', 'weekly_report_outputs_modified': False}), flush=True)
|
||||
result = collect_directory(client, departments, people, detail, logger)
|
||||
raw = json.dumps(result, ensure_ascii=False).encode('utf-8')
|
||||
if len(raw) > 16 << 20:
|
||||
raise DirectorySyncError('directory_output_limit')
|
||||
fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
try:
|
||||
with os.fdopen(fd, 'wb') as stream:
|
||||
stream.write(raw)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
except BaseException:
|
||||
output.unlink(missing_ok=True)
|
||||
raise
|
||||
print(json.dumps({'stage': 'complete', 'departments': len(result['directory']['departments']), 'people': len(result['directory']['people']), 'synced_at': result['synced_at'], 'requests': client.requests, 'complete': True, 'employee_identities_logged': False, 'weekly_report_outputs_modified': False}), flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except Exception as failure:
|
||||
code = str(failure) if isinstance(failure, DirectorySyncError) else 'directory_sync_failed'
|
||||
print(json.dumps({'stage': 'failed', 'code': code}), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -9,6 +9,18 @@
|
||||
"⚠️ 文件缺失或解析不了 ⇒ 门禁红:范围声明不出来时,不许默认放行。"
|
||||
],
|
||||
"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",
|
||||
"reason": "仅显式一次性隔离PG库验证持久化入队、并发重放、进程接管与租约栅栏;不调用真实钉钉源、不连接共享或生产库;默认CI无库则明确跳过"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/qaopsorg",
|
||||
"test": "TestOrganizationStoreRoundTripAndOptimisticConflict",
|
||||
"reason": "仅在显式KG_QAOPS_ORG_TEST_ISOLATED=1且127.0.0.1上的一次性kg_qaops_org_test_库运行;写入治理侧快照与配置,禁止使用共享或生产库;本批已在隔离PG补验"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/dobotaiops",
|
||||
"test": "TestSSHDialerTransportsRealTraffic",
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import importlib.util
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
spec=importlib.util.spec_from_file_location('qa_ops_directory_sync',Path(__file__).with_name('qa_ops_directory_sync.py'))
|
||||
assert spec is not None and spec.loader is not None
|
||||
sync=importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(sync)
|
||||
|
||||
class FakeClient:
|
||||
class Config:
|
||||
dry_run=False
|
||||
def __init__(self):
|
||||
self.config=self.Config()
|
||||
|
||||
def full_departments(client,logger,include,exclude):
|
||||
return {10:{'id':10,'parent_id':1,'name':'示例业务'}},set(),set()
|
||||
def full_users(client,logger,ids,enable_user_detail):
|
||||
if enable_user_detail:
|
||||
raise AssertionError('Must not inherit silent per-user detail failures or guessed primary department')
|
||||
return {'fixture-user':{'user_id':'fixture-user','department_ids':{10},'raw_payload':{'unionid':'fixture-union'}}},set(),set()
|
||||
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'])
|
||||
self.assertEqual(result['source'],'weekly_report_live')
|
||||
self.assertEqual(result['directory']['departments'],[
|
||||
{'id':'1','parent_id':'','name':'真实源端返回的示例根部门'},
|
||||
{'id':'10','parent_id':'1','name':'示例业务'}])
|
||||
self.assertEqual(result['directory']['people'],[{'id':'fixture-user','union_id':'fixture-union','department_ids':['10']}])
|
||||
def test_inaccessible_root_is_not_replaced_with_a_fabricated_company(self):
|
||||
def denied(*args):return None,True,False
|
||||
with self.assertRaisesRegex(sync.DirectorySyncError,'directory_ancestor_unavailable'):
|
||||
sync.collect_directory(FakeClient(),full_departments,full_users,denied,logging.getLogger('fixture'))
|
||||
def test_partial_fetch_and_dry_run_do_not_become_complete_live_snapshots(self):
|
||||
def partial(*args):return {},set(),{10}
|
||||
with self.assertRaises(sync.DirectorySyncError):
|
||||
sync.collect_directory(FakeClient(),partial,full_users,root_detail,logging.getLogger('fixture'))
|
||||
client=FakeClient();client.config.dry_run=True
|
||||
with self.assertRaises(sync.DirectorySyncError):
|
||||
sync.collect_directory(client,full_departments,full_users,root_detail,logging.getLogger('fixture'))
|
||||
def test_union_id_does_not_fall_back_to_open_id(self):
|
||||
def users(*args,**kwargs):return {'u':{'user_id':'u','department_ids':{10},'union_id':'not-a-union','raw_payload':{'openId':'not-a-union'}}},set(),set()
|
||||
result=sync.collect_directory(FakeClient(),full_departments,users,root_detail,logging.getLogger('fixture'))
|
||||
self.assertEqual(result['directory']['people'][0]['union_id'],'')
|
||||
def test_wrong_root_identity_and_cycles_are_rejected(self):
|
||||
def wrong(*args):return {'id':999,'parent_id':0,'name':'wrong'},False,False
|
||||
with self.assertRaises(sync.DirectorySyncError):
|
||||
sync.collect_directory(FakeClient(),full_departments,full_users,wrong,logging.getLogger('fixture'))
|
||||
def cyclic(*args):return {1:{'id':1,'parent_id':10,'name':'a'},10:{'id':10,'parent_id':1,'name':'b'}},set(),set()
|
||||
with self.assertRaises(sync.DirectorySyncError):
|
||||
sync.collect_directory(FakeClient(),cyclic,full_users,root_detail,logging.getLogger('fixture'))
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
+142
-63
@@ -1,9 +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
|
||||
@@ -47,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] ?? '数据源有待审核的安全告警'}
|
||||
@@ -78,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
|
||||
@@ -173,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>
|
||||
@@ -229,6 +276,8 @@ function initialDraft() {
|
||||
}
|
||||
|
||||
export function QAOperations() {
|
||||
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)
|
||||
@@ -258,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()
|
||||
@@ -284,7 +340,7 @@ export function QAOperations() {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
})
|
||||
return () => controller.abort()
|
||||
}, [query, canRead, revision])
|
||||
}, [query, canRead, revision, view])
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
@@ -339,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)
|
||||
@@ -362,7 +408,7 @@ export function QAOperations() {
|
||||
<section className="qa-ops" aria-label="问答运营">
|
||||
<header className="qa-ops-header">
|
||||
<h2>
|
||||
问答运营 <span>/ 问答记录</span>
|
||||
问答运营 <span>/ {view === 'regions' ? '区域归属' : view === 'usage' ? '使用统计' : '问答记录'}</span>
|
||||
</h2>
|
||||
<p>真实问答只读查询;原始记录、源端判断与治理复检分开保留。</p>
|
||||
</header>
|
||||
@@ -372,55 +418,88 @@ export function QAOperations() {
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<form className="qa-ops-query" onSubmit={submit}>
|
||||
<label>
|
||||
开始时间
|
||||
<input
|
||||
type="datetime-local"
|
||||
required
|
||||
value={draft.start}
|
||||
onChange={(event) => setDraft({ ...draft, start: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
结束时间(不含)
|
||||
<input
|
||||
type="datetime-local"
|
||||
required
|
||||
value={draft.end}
|
||||
onChange={(event) => setDraft({ ...draft, end: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className="qa-ops-keyword">
|
||||
关键词
|
||||
<input
|
||||
type="search"
|
||||
maxLength={200}
|
||||
placeholder="检索原始问题"
|
||||
value={draft.keyword}
|
||||
onChange={(event) => setDraft({ ...draft, keyword: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" disabled={loading}>
|
||||
查询
|
||||
<nav className="qa-region-tabs" aria-label="问答运营视图">
|
||||
<button type="button" aria-pressed={view === 'records'} onClick={() => setView('records')}>
|
||||
问答记录
|
||||
</button>
|
||||
</form>
|
||||
<p className="qa-ops-slice-note">
|
||||
当前切片:问答查询与覆盖复检。外语翻译、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)}
|
||||
/>
|
||||
<button type="button" aria-pressed={view === 'usage'} onClick={() => setView('usage')}>
|
||||
使用统计
|
||||
</button>
|
||||
<button type="button" aria-pressed={view === 'regions'} onClick={() => setView('regions')}>
|
||||
区域使用
|
||||
</button>
|
||||
</nav>
|
||||
{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 />
|
||||
) : (
|
||||
<>
|
||||
<form className="qa-ops-query" onSubmit={submit}>
|
||||
<label>
|
||||
开始时间
|
||||
<input
|
||||
type="datetime-local"
|
||||
required
|
||||
value={draft.start}
|
||||
onChange={(event) => setDraft({ ...draft, start: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
结束时间(不含)
|
||||
<input
|
||||
type="datetime-local"
|
||||
required
|
||||
value={draft.end}
|
||||
onChange={(event) => setDraft({ ...draft, end: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className="qa-ops-keyword">
|
||||
关键词
|
||||
<input
|
||||
type="search"
|
||||
maxLength={200}
|
||||
placeholder="检索原始问题"
|
||||
value={draft.keyword}
|
||||
onChange={(event) => setDraft({ ...draft, keyword: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" disabled={loading}>
|
||||
查询
|
||||
</button>
|
||||
</form>
|
||||
<p className="qa-ops-slice-note">
|
||||
部门/区域保留源快照,缺失时按当前通讯录补全;使用统计不是绩效结论。外语翻译与AI评估仍暂缓,空值不默认填“否”。
|
||||
</p>
|
||||
{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)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
// @ts-expect-error The test runner provides Node; the browser bundle intentionally omits @types/node.
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { RegionMappingView } from './QARegions'
|
||||
import { parseOrganization } from './qaOrg'
|
||||
const state = parseOrganization({
|
||||
state: 'ready',
|
||||
directory_id: 'd',
|
||||
directory_source: 'weekly_report_snapshot',
|
||||
directory_synced_at: '2026-09-27T14:03:44Z',
|
||||
revision_id: 'r',
|
||||
updated_by: 'fixture-admin',
|
||||
updated_at: null,
|
||||
rules: [{ department_id: 'a', region: 'APAC' }],
|
||||
view: {
|
||||
departments: [
|
||||
{
|
||||
id: 'a',
|
||||
parent_id: '',
|
||||
name: '<script>test</script>',
|
||||
path: '示例公司/<script>test</script>',
|
||||
region: 'APAC',
|
||||
explicit: true,
|
||||
inherited_from: '',
|
||||
},
|
||||
],
|
||||
regions: { 国内工业: 0, APAC: 1, EMEA: 0, America: 0 },
|
||||
total_people: 2,
|
||||
unassigned_people: 0,
|
||||
conflicting_people: 1,
|
||||
missing_departments: [],
|
||||
},
|
||||
})
|
||||
const props = {
|
||||
state,
|
||||
preview: null,
|
||||
rules: state.rules,
|
||||
selectedRegion: 'APAC',
|
||||
search: '',
|
||||
busy: false,
|
||||
error: '',
|
||||
notice: '',
|
||||
dirty: false,
|
||||
onRegion: vi.fn(),
|
||||
onSearch: vi.fn(),
|
||||
onToggle: vi.fn(),
|
||||
onPreview: vi.fn(),
|
||||
onSave: vi.fn(),
|
||||
onReload: vi.fn(),
|
||||
onRemoveMissing: vi.fn(),
|
||||
}
|
||||
describe('region mapping workbench', () => {
|
||||
it('shows real synchronization stages without inventing progress and protects dirty drafts', () => {
|
||||
const syncStatus = {
|
||||
configured: true,
|
||||
worker_ready: true,
|
||||
job: {
|
||||
id: 'j',
|
||||
state: 'running' as const,
|
||||
attempt: 1,
|
||||
max_attempts: 3,
|
||||
updated_at: '2026-10-17T08:00:00Z',
|
||||
error_code: '',
|
||||
result: null,
|
||||
},
|
||||
}
|
||||
const html = renderToStaticMarkup(<RegionMappingView {...props} syncStatus={syncStatus} />)
|
||||
expect(html).toContain('正在读取并校验通讯录')
|
||||
expect(html).not.toMatch(/\d+%/)
|
||||
expect(html).toMatch(/disabled=""[^>]*>同步通讯录/)
|
||||
const dirty = renderToStaticMarkup(
|
||||
<RegionMappingView {...props} dirty syncStatus={{ configured: true, worker_ready: true, job: null }} />
|
||||
)
|
||||
expect(dirty).toContain('未保存的区域修改')
|
||||
expect(dirty).toMatch(/disabled=""[^>]*>同步通讯录/)
|
||||
})
|
||||
it('lets long directory paths wrap instead of inheriting the global nowrap table rule', () => {
|
||||
const css = readFileSync(new URL('./qaRegions.css', import.meta.url), 'utf8')
|
||||
const bodyRule = css.match(/\.qa-region-table td\s*\{([^}]+)\}/)?.[1] ?? ''
|
||||
expect(bodyRule).toMatch(/white-space:\s*normal/)
|
||||
expect(bodyRule).toMatch(/overflow-wrap:\s*anywhere/)
|
||||
const statusRule = css.match(/\.qa-region-table td:nth-child\(4\)\s*\{([^}]+)\}/)?.[1] ?? ''
|
||||
expect(statusRule).toMatch(/white-space:\s*nowrap/)
|
||||
})
|
||||
it('shows a dated historical roster, conflicts and no invented performance verdict', () => {
|
||||
const html = renderToStaticMarkup(<RegionMappingView {...props} />)
|
||||
expect(html).toContain('历史快照')
|
||||
expect(html).toContain('跨区域待核对:1')
|
||||
expect(html).toContain('配置区域归属不等于纳入绩效考核')
|
||||
expect(html).not.toContain('<script>test</script>')
|
||||
expect(html).not.toContain('达标率')
|
||||
expect(html).toMatch(/disabled=""[^>]*>保存归属/)
|
||||
})
|
||||
it('requires a preview of the current draft before enabling save', () => {
|
||||
const html = renderToStaticMarkup(<RegionMappingView {...props} dirty preview={state} />)
|
||||
expect(html).toContain('预览结果(未保存)')
|
||||
expect(html).not.toMatch(/disabled=""[^>]*>保存归属/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,372 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { changeRegionRule, fetchOrganization, previewOrganization, regionNames, saveOrganization } from './qaOrg'
|
||||
import type { Organization, RegionRule } from './qaOrg'
|
||||
import './qaRegions.css'
|
||||
import { completedSyncAction, directorySyncActive, fetchDirectorySync, startDirectorySync } from './qaOrgSync'
|
||||
import type { DirectorySyncStatus } from './qaOrgSync'
|
||||
import { newOperationID } from './operationKey'
|
||||
interface Props {
|
||||
syncStatus?: DirectorySyncStatus | null
|
||||
syncError?: string
|
||||
syncSubmitting?: boolean
|
||||
onSync?: () => void
|
||||
state: Organization | null
|
||||
preview: Organization | null
|
||||
rules: RegionRule[]
|
||||
selectedRegion: string
|
||||
search: string
|
||||
busy: boolean
|
||||
error: string
|
||||
notice: string
|
||||
dirty: boolean
|
||||
onRegion: (value: string) => void
|
||||
onSearch: (value: string) => void
|
||||
onToggle: (id: string, checked: boolean) => void
|
||||
onRemoveMissing: (id: string) => void
|
||||
onPreview: () => void
|
||||
onSave: () => void
|
||||
onReload: () => void
|
||||
}
|
||||
export function RegionMappingView(p: Props) {
|
||||
const display = p.preview ?? p.state
|
||||
const available = p.state?.state === 'ready'
|
||||
const departments =
|
||||
display?.view.departments.filter((d) => d.path.toLowerCase().includes(p.search.toLowerCase())) ?? []
|
||||
return (
|
||||
<section className="qa-regions" aria-label="区域归属配置">
|
||||
<div className="qa-region-heading">
|
||||
<h3>区域归属配置</h3>
|
||||
<button type="button" disabled={p.busy} onClick={p.onReload}>
|
||||
{p.dirty ? '放弃修改并重读' : '重新读取'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={
|
||||
p.busy ||
|
||||
p.dirty ||
|
||||
p.syncSubmitting ||
|
||||
!p.syncStatus?.configured ||
|
||||
!p.syncStatus.worker_ready ||
|
||||
directorySyncActive(p.syncStatus ?? null)
|
||||
}
|
||||
onClick={p.onSync}
|
||||
>
|
||||
同步通讯录
|
||||
</button>
|
||||
</div>
|
||||
<div className="qa-ops-muted" aria-label="通讯录后台同步状态" role="status">
|
||||
{!p.syncStatus
|
||||
? '正在读取后台同步状态…'
|
||||
: !p.syncStatus.configured
|
||||
? '后台同步未接线'
|
||||
: p.syncStatus.job
|
||||
? {
|
||||
pending: '等待后台执行器',
|
||||
running: '正在读取并校验通讯录',
|
||||
retry: '上次同步失败,等待后台重试;保留原快照',
|
||||
completed: '同步已完成,完整快照已落库',
|
||||
failed: '同步失败,保留原快照;可重新同步',
|
||||
cancelled: '同步已取消,保留原快照',
|
||||
}[p.syncStatus.job.state]
|
||||
: p.syncStatus.worker_ready
|
||||
? '后台执行器在线,尚未发起同步'
|
||||
: '后台执行器未在线,不会创建无人处理的任务'}
|
||||
{p.dirty ? ';存在未保存的区域修改,请先保存或放弃后同步' : ''}
|
||||
</div>
|
||||
{p.syncError ? (
|
||||
<p role="alert" className="error-banner">
|
||||
{p.syncError}
|
||||
</p>
|
||||
) : null}
|
||||
{p.state?.directory_synced_at ? (
|
||||
<p className="qa-ops-muted">
|
||||
{p.state.directory_source === 'weekly_report_snapshot' ? '历史快照' : '全量同步快照'} · 通讯录同步时间:
|
||||
{new Date(p.state.directory_synced_at).toLocaleString('zh-CN', { hour12: false })} · 配置版本:
|
||||
{p.state.revision_id || '尚未保存'}
|
||||
</p>
|
||||
) : null}
|
||||
<p className="qa-ops-muted">
|
||||
父部门包含子部门,子部门单独配置优先。配置区域归属不等于纳入绩效考核;跨区域多部门人员先待核对。
|
||||
</p>
|
||||
{p.error ? (
|
||||
<p role="alert" className="error-banner">
|
||||
{p.error}
|
||||
</p>
|
||||
) : null}
|
||||
{p.notice ? <p role="status">{p.notice}</p> : null}
|
||||
{!p.state ? (
|
||||
<p role="status">{p.busy ? '正在读取通讯录…' : '尚未读取通讯录'}</p>
|
||||
) : !available ? (
|
||||
<p className="qa-ops-empty">尚无完整通讯录快照。先接入已验证的全量同步结果,不能使用按需人员缓存或编造部门。</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="qa-region-filters">
|
||||
<label>
|
||||
选择区域
|
||||
<select value={p.selectedRegion} disabled={p.busy} onChange={(e) => p.onRegion(e.target.value)}>
|
||||
{regionNames.map((r) => (
|
||||
<option key={r}>{r}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
搜索完整部门路径
|
||||
<input
|
||||
type="search"
|
||||
value={p.search}
|
||||
onChange={(e) => p.onSearch(e.target.value)}
|
||||
placeholder="输入部门名称或完整路径"
|
||||
/>
|
||||
</label>
|
||||
<button type="button" disabled={p.busy || !p.dirty} onClick={p.onPreview}>
|
||||
预览影响
|
||||
</button>
|
||||
<button type="button" disabled={p.busy || !p.dirty || !p.preview} onClick={p.onSave}>
|
||||
保存归属
|
||||
</button>
|
||||
</div>
|
||||
{display ? (
|
||||
<div className="qa-region-preview" aria-label="归属人数预览">
|
||||
<strong>{p.preview ? '预览结果(未保存)' : '已保存归属'}</strong>
|
||||
<span>通讯录人数:{display.view.total_people}</span>
|
||||
{regionNames.map((r) => (
|
||||
<span key={r}>
|
||||
{r}:{display.view.regions[r]}
|
||||
</span>
|
||||
))}
|
||||
<span>未归属:{display.view.unassigned_people}</span>
|
||||
<span>跨区域待核对:{display.view.conflicting_people}</span>
|
||||
</div>
|
||||
) : null}
|
||||
{p.dirty && !p.preview ? (
|
||||
<p className="qa-ops-muted">勾选已修改,人数仍为已保存结果;请预览后保存。</p>
|
||||
) : null}
|
||||
{display?.view.missing_departments.length ? (
|
||||
<div role="alert" className="qa-ops-warning">
|
||||
部分已配置部门不在当前通讯录中,原规则保留,需核对:
|
||||
{display.view.missing_departments.map((id) => (
|
||||
<span key={id}>
|
||||
{id}{' '}
|
||||
<button type="button" disabled={p.busy} onClick={() => p.onRemoveMissing(id)}>
|
||||
移除此规则
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="qa-region-tree-scroll">
|
||||
<table className="qa-region-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>直接配置</th>
|
||||
<th>完整部门路径</th>
|
||||
<th>{p.dirty && !p.preview ? '已保存归属' : '生效归属'}</th>
|
||||
<th>依据</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{departments.map((d) => (
|
||||
<tr key={d.id}>
|
||||
<td>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={`将 ${d.path} 直接归入 ${p.selectedRegion}`}
|
||||
checked={p.rules.some((r) => r.department_id === d.id && r.region === p.selectedRegion)}
|
||||
disabled={p.busy}
|
||||
onChange={(e) => p.onToggle(d.id, e.target.checked)}
|
||||
/>
|
||||
</td>
|
||||
<td>{d.path}</td>
|
||||
<td>{d.region || '未归属'}</td>
|
||||
<td>{d.explicit ? '直接配置' : d.inherited_from ? '继承上级' : '未配置'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{!departments.length ? <p>没有匹配的部门路径</p> : null}
|
||||
</div>
|
||||
<p className="qa-ops-muted">
|
||||
此处仅预览通讯录归属人数;2.0 使用次数、考核名单与绩效统计尚未接入。不会将未知在职状态当作已确认在职人数。
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
function signature(rules: RegionRule[]) {
|
||||
return JSON.stringify([...rules].sort((a, b) => a.department_id.localeCompare(b.department_id)))
|
||||
}
|
||||
export function QARegions() {
|
||||
const [syncStatus, setSyncStatus] = useState<DirectorySyncStatus | null>(null),
|
||||
[syncError, setSyncError] = useState(''),
|
||||
[syncSubmitting, setSyncSubmitting] = useState(false)
|
||||
const syncOperation = useRef(''),
|
||||
syncFlight = useRef(false),
|
||||
syncAction = useRef<AbortController | null>(null),
|
||||
lastCompleted = useRef(''),
|
||||
dirtyRef = useRef(false)
|
||||
const [state, setState] = useState<Organization | null>(null),
|
||||
[preview, setPreview] = useState<Organization | null>(null),
|
||||
[rules, setRules] = useState<RegionRule[]>([])
|
||||
const [region, setRegion] = useState<string>(regionNames[0]),
|
||||
[search, setSearch] = useState(''),
|
||||
[busy, setBusy] = useState(false),
|
||||
[error, setError] = useState(''),
|
||||
[notice, setNotice] = useState('')
|
||||
const request = useRef<AbortController | null>(null)
|
||||
const accept = (value: Organization) => {
|
||||
setState(value)
|
||||
setRules(value.rules)
|
||||
setPreview(null)
|
||||
}
|
||||
const load = async () => {
|
||||
request.current?.abort()
|
||||
const controller = new AbortController()
|
||||
request.current = controller
|
||||
setBusy(true)
|
||||
setError('')
|
||||
setNotice('')
|
||||
setPreview(null)
|
||||
try {
|
||||
const value = await fetchOrganization(controller.signal)
|
||||
if (!controller.signal.aborted) {
|
||||
accept(value)
|
||||
return true
|
||||
}
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted) setError(e instanceof Error ? e.message : '读取失败')
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setBusy(false)
|
||||
}
|
||||
}
|
||||
useEffect(() => {
|
||||
void load()
|
||||
return () => request.current?.abort()
|
||||
}, [])
|
||||
const dirty = Boolean(state && signature(rules) !== signature(state.rules))
|
||||
dirtyRef.current = dirty
|
||||
const loadRef = useRef(load)
|
||||
loadRef.current = load
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
const poll = async () => {
|
||||
let delay = 10000
|
||||
try {
|
||||
const value = await fetchDirectorySync(controller.signal)
|
||||
if (controller.signal.aborted) return
|
||||
setSyncStatus(value)
|
||||
setSyncError('')
|
||||
delay = directorySyncActive(value) ? 1500 : 10000
|
||||
const job = value.job
|
||||
if (job?.state === 'completed' && job.id !== lastCompleted.current) {
|
||||
const action = completedSyncAction(value, lastCompleted.current, dirtyRef.current)
|
||||
lastCompleted.current = job.id
|
||||
if (action === 'preserve') setNotice('通讯录已同步,当前未保存草稿仍保留;请核对后重新读取')
|
||||
else if (action === 'reload' && (await loadRef.current())) setNotice('通讯录同步完成并已重新读取')
|
||||
} else if (job && lastCompleted.current === '') lastCompleted.current = 'pending:' + job.id
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted)
|
||||
setSyncError(e instanceof Error ? e.message : '同步状态读取失败,未将现有快照清空')
|
||||
} finally {
|
||||
if (!controller.signal.aborted) timer = setTimeout(() => void poll(), delay)
|
||||
}
|
||||
}
|
||||
void poll()
|
||||
return () => {
|
||||
controller.abort()
|
||||
clearTimeout(timer)
|
||||
syncAction.current?.abort()
|
||||
}
|
||||
}, [])
|
||||
const synchronize = async () => {
|
||||
if (
|
||||
busy ||
|
||||
dirty ||
|
||||
syncFlight.current ||
|
||||
!syncStatus?.configured ||
|
||||
!syncStatus.worker_ready ||
|
||||
directorySyncActive(syncStatus)
|
||||
)
|
||||
return
|
||||
syncFlight.current = true
|
||||
setSyncSubmitting(true)
|
||||
setSyncError('')
|
||||
const controller = new AbortController()
|
||||
syncAction.current = controller
|
||||
try {
|
||||
if (!syncOperation.current) syncOperation.current = newOperationID()
|
||||
const receipt = await startDirectorySync(syncOperation.current, controller.signal)
|
||||
syncOperation.current = ''
|
||||
if (controller.signal.aborted) return
|
||||
lastCompleted.current = 'submitted:' + receipt.job_id
|
||||
setSyncStatus(await fetchDirectorySync(controller.signal))
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted)
|
||||
setSyncError(e instanceof Error ? e.message : '同步提交结果未知;重试会复用原操作标识')
|
||||
} finally {
|
||||
syncFlight.current = false
|
||||
if (!controller.signal.aborted) setSyncSubmitting(false)
|
||||
}
|
||||
}
|
||||
const edit = (next: RegionRule[]) => {
|
||||
setRules(next)
|
||||
setPreview(null)
|
||||
setNotice('')
|
||||
setError('')
|
||||
}
|
||||
const act = async (save: boolean) => {
|
||||
if (!state || busy || (save && !preview)) return
|
||||
const controller = new AbortController()
|
||||
request.current?.abort()
|
||||
request.current = controller
|
||||
setBusy(true)
|
||||
setError('')
|
||||
setNotice('')
|
||||
try {
|
||||
const value = await (save
|
||||
? saveOrganization(state, rules, controller.signal)
|
||||
: previewOrganization(state, rules, controller.signal))
|
||||
if (!controller.signal.aborted) {
|
||||
if (save) {
|
||||
const readback = await fetchOrganization(controller.signal)
|
||||
if (controller.signal.aborted) return
|
||||
accept(readback)
|
||||
if (readback.revision_id !== value.revision_id) throw new Error('保存后配置再次变化,已读取最新版本,请核对')
|
||||
setNotice('区域归属已保存并重新读取')
|
||||
} else setPreview(value)
|
||||
}
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted) {
|
||||
setPreview(null)
|
||||
setError(e instanceof Error ? e.message : '操作失败')
|
||||
}
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setBusy(false)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<RegionMappingView
|
||||
syncStatus={syncStatus}
|
||||
syncError={syncError}
|
||||
syncSubmitting={syncSubmitting}
|
||||
onSync={() => void synchronize()}
|
||||
state={state}
|
||||
preview={preview}
|
||||
rules={rules}
|
||||
selectedRegion={region}
|
||||
search={search}
|
||||
busy={busy}
|
||||
error={error}
|
||||
notice={notice}
|
||||
dirty={dirty}
|
||||
onRegion={setRegion}
|
||||
onSearch={setSearch}
|
||||
onToggle={(id, checked) => edit(changeRegionRule(rules, id, region, checked))}
|
||||
onRemoveMissing={(id) => edit(rules.filter((r) => r.department_id !== id))}
|
||||
onPreview={() => void act(false)}
|
||||
onSave={() => void act(true)}
|
||||
onReload={() => void load()}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -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 条')
|
||||
})
|
||||
})
|
||||
@@ -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)} />
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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,
|
||||
},
|
||||
],
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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}`
|
||||
}
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { fetchOrganization, parseOrganization, changeRegionRule } from './qaOrg'
|
||||
|
||||
export const directoryFixture = {
|
||||
state: 'ready',
|
||||
directory_id: 'dir-fixture',
|
||||
directory_source: 'weekly_report_snapshot',
|
||||
directory_synced_at: '2026-09-27T14:03:44Z',
|
||||
revision_id: '',
|
||||
updated_by: '',
|
||||
updated_at: null,
|
||||
rules: [],
|
||||
view: {
|
||||
departments: [
|
||||
{
|
||||
id: 'root',
|
||||
parent_id: '',
|
||||
name: '示例公司',
|
||||
path: '示例公司',
|
||||
region: '',
|
||||
explicit: false,
|
||||
inherited_from: '',
|
||||
},
|
||||
],
|
||||
regions: { 国内工业: 0, APAC: 0, EMEA: 0, America: 0 },
|
||||
total_people: 1,
|
||||
unassigned_people: 1,
|
||||
conflicting_people: 0,
|
||||
missing_departments: [],
|
||||
},
|
||||
}
|
||||
describe('department region configuration', () => {
|
||||
it('parses an honest dated snapshot without exposing employee identities', () => {
|
||||
const state = parseOrganization(directoryFixture)
|
||||
expect(state.directory_source).toBe('weekly_report_snapshot')
|
||||
expect(state.view.unassigned_people).toBe(1)
|
||||
expect(() =>
|
||||
parseOrganization({ ...directoryFixture, view: { ...directoryFixture.view, total_people: 0 } })
|
||||
).toThrow()
|
||||
expect(() =>
|
||||
parseOrganization({ ...directoryFixture, view: { ...directoryFixture.view, departments: [{}, {}] } })
|
||||
).toThrow()
|
||||
})
|
||||
it('changes only a direct stable ID rule, leaving sibling and child overrides alone', () => {
|
||||
const rules = [
|
||||
{ department_id: 'parent', region: '国内工业' },
|
||||
{ department_id: 'child', region: 'APAC' },
|
||||
]
|
||||
expect(changeRegionRule(rules, 'parent', 'EMEA', true)).toEqual([
|
||||
{ department_id: 'child', region: 'APAC' },
|
||||
{ department_id: 'parent', region: 'EMEA' },
|
||||
])
|
||||
expect(changeRegionRule(rules, 'parent', '国内工业', false)).toEqual([{ department_id: 'child', region: 'APAC' }])
|
||||
})
|
||||
it('surfaces store errors rather than displaying an empty directory', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue({ ok: false, status: 503, json: async () => ({ error: '通讯录不可用' }) })
|
||||
)
|
||||
await expect(fetchOrganization()).rejects.toThrow('通讯录不可用')
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,152 @@
|
||||
export const regionNames = ['国内工业', 'APAC', 'EMEA', 'America'] as const
|
||||
export interface RegionRule {
|
||||
department_id: string
|
||||
region: string
|
||||
}
|
||||
export interface DepartmentRegion {
|
||||
id: string
|
||||
parent_id: string
|
||||
name: string
|
||||
path: string
|
||||
region: string
|
||||
explicit: boolean
|
||||
inherited_from: string
|
||||
}
|
||||
export interface Organization {
|
||||
state: 'empty' | 'ready'
|
||||
directory_id: string
|
||||
directory_source: string
|
||||
directory_synced_at: string | null
|
||||
revision_id: string
|
||||
updated_by: string
|
||||
updated_at: string | null
|
||||
rules: RegionRule[]
|
||||
view: {
|
||||
departments: DepartmentRegion[]
|
||||
regions: Record<string, number>
|
||||
total_people: number
|
||||
unassigned_people: number
|
||||
conflicting_people: number
|
||||
missing_departments: string[]
|
||||
}
|
||||
}
|
||||
export function invalid(): never {
|
||||
throw new Error('通讯录或区域配置响应格式无效')
|
||||
}
|
||||
export function obj(value: unknown): Record<string, unknown> {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return invalid()
|
||||
return value as Record<string, unknown>
|
||||
}
|
||||
export function str(value: unknown): string {
|
||||
return typeof value === 'string' ? value : invalid()
|
||||
}
|
||||
export function count(value: unknown): number {
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : invalid()
|
||||
}
|
||||
export function instant(value: unknown): string | null {
|
||||
return value === null ? null : typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : invalid()
|
||||
}
|
||||
export function parseOrganization(value: unknown): Organization {
|
||||
const s = obj(value),
|
||||
v = obj(s.view),
|
||||
regions = obj(v.regions)
|
||||
if (
|
||||
(s.state !== 'empty' && s.state !== 'ready') ||
|
||||
!Array.isArray(s.rules) ||
|
||||
!Array.isArray(v.departments) ||
|
||||
!Array.isArray(v.missing_departments)
|
||||
)
|
||||
return invalid()
|
||||
const rules = s.rules.map((raw) => {
|
||||
const r = obj(raw)
|
||||
const region = str(r.region)
|
||||
if (!regionNames.some((x) => x === region)) return invalid()
|
||||
return { department_id: str(r.department_id), region }
|
||||
})
|
||||
const departments = v.departments.map((raw) => {
|
||||
const d = obj(raw)
|
||||
if (typeof d.explicit !== 'boolean' || (d.region !== '' && !regionNames.some((x) => x === d.region)))
|
||||
return invalid()
|
||||
return {
|
||||
id: str(d.id),
|
||||
parent_id: str(d.parent_id),
|
||||
name: str(d.name),
|
||||
path: str(d.path),
|
||||
region: str(d.region),
|
||||
explicit: d.explicit,
|
||||
inherited_from: str(d.inherited_from),
|
||||
}
|
||||
})
|
||||
if (
|
||||
departments.some((d) => !d.id || !d.path) ||
|
||||
new Set(departments.map((d) => d.id)).size !== departments.length ||
|
||||
new Set(rules.map((r) => r.department_id)).size !== rules.length
|
||||
)
|
||||
return invalid()
|
||||
const total = count(v.total_people),
|
||||
unassigned = count(v.unassigned_people),
|
||||
conflicting = count(v.conflicting_people)
|
||||
const regionCounts = Object.fromEntries(regionNames.map((r) => [r, count(regions[r])]))
|
||||
if (Object.values(regionCounts).reduce((a, b) => a + b, 0) + unassigned + conflicting !== total) return invalid()
|
||||
const result: Organization = {
|
||||
state: s.state,
|
||||
directory_id: str(s.directory_id),
|
||||
directory_source: str(s.directory_source),
|
||||
directory_synced_at: instant(s.directory_synced_at),
|
||||
revision_id: str(s.revision_id),
|
||||
updated_by: str(s.updated_by),
|
||||
updated_at: instant(s.updated_at),
|
||||
rules,
|
||||
view: {
|
||||
departments,
|
||||
regions: regionCounts,
|
||||
total_people: total,
|
||||
unassigned_people: unassigned,
|
||||
conflicting_people: conflicting,
|
||||
missing_departments: v.missing_departments.map(str),
|
||||
},
|
||||
}
|
||||
if (s.state === 'ready' && (!result.directory_id || !result.directory_synced_at || !departments.length || !total))
|
||||
return invalid()
|
||||
return result
|
||||
}
|
||||
export function changeRegionRule(rules: RegionRule[], id: string, region: string, checked: boolean): RegionRule[] {
|
||||
return [...rules.filter((r) => r.department_id !== id), ...(checked ? [{ department_id: id, region }] : [])]
|
||||
}
|
||||
async function requestOrganization(
|
||||
path: string,
|
||||
method: string,
|
||||
body: unknown,
|
||||
signal?: AbortSignal
|
||||
): Promise<Organization> {
|
||||
const response = await fetch(`/api/v1/qa-ops/organization${path}`, {
|
||||
method,
|
||||
credentials: 'same-origin',
|
||||
cache: 'no-store',
|
||||
signal,
|
||||
headers:
|
||||
method === 'GET' ? undefined : { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-organization' },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
})
|
||||
const raw: unknown = await response.json().catch(() => null)
|
||||
if (!response.ok) {
|
||||
const error = raw && typeof raw === 'object' ? (raw as Record<string, unknown>).error : undefined
|
||||
throw new Error(typeof error === 'string' ? error : `区域配置读取失败(HTTP ${response.status})`)
|
||||
}
|
||||
return parseOrganization(obj(raw).data)
|
||||
}
|
||||
export const fetchOrganization = (signal?: AbortSignal) => requestOrganization('', 'GET', undefined, signal)
|
||||
export const previewOrganization = (state: Organization, rules: RegionRule[], signal?: AbortSignal) =>
|
||||
requestOrganization(
|
||||
'/preview',
|
||||
'POST',
|
||||
{ directory_id: state.directory_id, base_revision: state.revision_id, rules },
|
||||
signal
|
||||
)
|
||||
export const saveOrganization = (state: Organization, rules: RegionRule[], signal?: AbortSignal) =>
|
||||
requestOrganization(
|
||||
'/regions',
|
||||
'PUT',
|
||||
{ directory_id: state.directory_id, base_revision: state.revision_id, rules },
|
||||
signal
|
||||
)
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, it, vi, afterEach } from 'vitest'
|
||||
import { parseDirectorySync, startDirectorySync, fetchDirectorySync, completedSyncAction } from './qaOrgSync'
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
const idle = { configured: true, worker_ready: true, job: null }
|
||||
describe('directory synchronization contract', () => {
|
||||
it('reloads a completed job even on first observation, without replacing an unsaved draft', () => {
|
||||
const status = parseDirectorySync({
|
||||
...idle,
|
||||
job: {
|
||||
id: 'new-job',
|
||||
state: 'completed',
|
||||
attempt: 1,
|
||||
max_attempts: 3,
|
||||
updated_at: '2026-10-17T08:00:00Z',
|
||||
error_code: '',
|
||||
result: { directory_id: 'd', departments: 1, people: 1, synced_at: '2026-10-17T08:00:00Z' },
|
||||
},
|
||||
})
|
||||
expect(completedSyncAction(status, '', false)).toBe('reload')
|
||||
expect(completedSyncAction(status, '', true)).toBe('preserve')
|
||||
expect(completedSyncAction(status, 'new-job', false)).toBe('none')
|
||||
expect(completedSyncAction({ ...status, job: { ...status.job!, state: 'running' } }, '', false)).toBe('none')
|
||||
})
|
||||
it('keeps unknown/failed state distinct from empty data', () => {
|
||||
expect(parseDirectorySync(idle).job).toBeNull()
|
||||
expect(() => parseDirectorySync({ ...idle, worker_ready: 'yes' })).toThrow()
|
||||
expect(() => parseDirectorySync({ ...idle, job: { id: 'x', state: 'mystery' } })).toThrow()
|
||||
const result = { directory_id: 'd', departments: 327, people: 1534, synced_at: '2026-10-17T07:00:00Z' }
|
||||
const job = {
|
||||
id: 'j',
|
||||
state: 'completed',
|
||||
attempt: 1,
|
||||
max_attempts: 3,
|
||||
updated_at: '2026-10-17T07:01:00Z',
|
||||
error_code: '',
|
||||
result,
|
||||
}
|
||||
expect(parseDirectorySync({ ...idle, job }).job?.result?.people).toBe(1534)
|
||||
expect(() => parseDirectorySync({ ...idle, job: { ...job, result: { ...result, people: -1 } } })).toThrow()
|
||||
})
|
||||
it('sends a stable idempotency header and no tenant, credential or executable path', async () => {
|
||||
const fetcher = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ data: { job_id: 'j', deduplicated: false }, operation: 'replayed' }),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
expect((await startDirectorySync('same-action')).operation).toBe('replayed')
|
||||
expect(fetcher).toHaveBeenCalledWith(
|
||||
'/api/v1/qa-ops/organization/sync',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
body: '{}',
|
||||
headers: expect.objectContaining({
|
||||
'Idempotency-Key': 'same-action',
|
||||
'X-Governance-Action': 'qa-organization',
|
||||
}),
|
||||
})
|
||||
)
|
||||
})
|
||||
it('reads live job state and surfaces server failure instead of a successful empty result', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce({ ok: true, json: async () => ({ data: idle }) })
|
||||
.mockResolvedValueOnce({ ok: false, status: 503, json: async () => ({ error: '执行器未在线' }) })
|
||||
)
|
||||
expect((await fetchDirectorySync()).worker_ready).toBe(true)
|
||||
await expect(startDirectorySync('same-action')).rejects.toThrow('执行器未在线')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,104 @@
|
||||
export interface DirectorySyncResult {
|
||||
directory_id: string
|
||||
departments: number
|
||||
people: number
|
||||
synced_at: string
|
||||
}
|
||||
export interface DirectorySyncJob {
|
||||
id: string
|
||||
state: 'pending' | 'running' | 'retry' | 'completed' | 'failed' | 'cancelled'
|
||||
attempt: number
|
||||
max_attempts: number
|
||||
updated_at: string
|
||||
error_code: string
|
||||
result: DirectorySyncResult | null
|
||||
}
|
||||
export interface DirectorySyncStatus {
|
||||
configured: boolean
|
||||
worker_ready: boolean
|
||||
job: DirectorySyncJob | null
|
||||
}
|
||||
export function completedSyncAction(
|
||||
s: DirectorySyncStatus,
|
||||
last: string,
|
||||
dirty: boolean
|
||||
): 'none' | 'preserve' | 'reload' {
|
||||
if (s.job?.state !== 'completed' || s.job.id === last) return 'none'
|
||||
return dirty ? 'preserve' : 'reload'
|
||||
}
|
||||
export const directorySyncActive = (s: DirectorySyncStatus | null) =>
|
||||
Boolean(s?.job && ['pending', 'running', 'retry'].includes(s.job.state))
|
||||
import { invalid as bad, obj as object, str as text, count, instant as nullableInstant } from './qaOrg'
|
||||
function instant(v: unknown): string {
|
||||
return nullableInstant(v) ?? bad()
|
||||
}
|
||||
export function parseDirectorySync(raw: unknown): DirectorySyncStatus {
|
||||
const s = object(raw)
|
||||
if (typeof s.configured !== 'boolean' || typeof s.worker_ready !== 'boolean') return bad()
|
||||
let job: DirectorySyncJob | null = null
|
||||
if (s.job !== null) {
|
||||
const j = object(s.job)
|
||||
if (!['pending', 'running', 'retry', 'completed', 'failed', 'cancelled'].includes(text(j.state))) return bad()
|
||||
let result: DirectorySyncResult | null = null
|
||||
if (j.result !== null) {
|
||||
const r = object(j.result)
|
||||
result = {
|
||||
directory_id: text(r.directory_id),
|
||||
departments: count(r.departments),
|
||||
people: count(r.people),
|
||||
synced_at: instant(r.synced_at),
|
||||
}
|
||||
if (!result.directory_id || !result.departments || !result.people) return bad()
|
||||
}
|
||||
job = {
|
||||
id: text(j.id),
|
||||
state: j.state as DirectorySyncJob['state'],
|
||||
attempt: count(j.attempt),
|
||||
max_attempts: count(j.max_attempts),
|
||||
updated_at: instant(j.updated_at),
|
||||
error_code: text(j.error_code),
|
||||
result,
|
||||
}
|
||||
if (!job.id || !job.max_attempts || job.attempt > job.max_attempts || (job.state === 'completed' && !result))
|
||||
return bad()
|
||||
}
|
||||
return { configured: s.configured, worker_ready: s.worker_ready, job }
|
||||
}
|
||||
async function request(method: string, operationID?: string, signal?: AbortSignal) {
|
||||
const response = await fetch('/api/v1/qa-ops/organization/sync', {
|
||||
method,
|
||||
credentials: 'same-origin',
|
||||
cache: 'no-store',
|
||||
signal,
|
||||
headers:
|
||||
method === 'POST'
|
||||
? {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Governance-Action': 'qa-organization',
|
||||
'Idempotency-Key': operationID ?? '',
|
||||
}
|
||||
: undefined,
|
||||
body: method === 'POST' ? '{}' : undefined,
|
||||
})
|
||||
const raw: unknown = await response.json().catch(() => null)
|
||||
if (!response.ok) {
|
||||
const error = raw && typeof raw === 'object' ? (raw as Record<string, unknown>).error : undefined
|
||||
throw new Error(typeof error === 'string' ? error : `通讯录同步请求失败(HTTP ${response.status})`)
|
||||
}
|
||||
return object(raw)
|
||||
}
|
||||
export async function fetchDirectorySync(signal?: AbortSignal) {
|
||||
return parseDirectorySync((await request('GET', undefined, signal)).data)
|
||||
}
|
||||
export async function startDirectorySync(operationID: string, signal?: AbortSignal) {
|
||||
if (!operationID || operationID.trim() !== operationID || operationID.length > 128) return bad()
|
||||
const envelope = await request('POST', operationID, signal),
|
||||
data = object(envelope.data)
|
||||
if (
|
||||
(envelope.operation !== 'created' && envelope.operation !== 'replayed') ||
|
||||
typeof data.deduplicated !== 'boolean' ||
|
||||
!text(data.job_id)
|
||||
)
|
||||
return bad()
|
||||
return { job_id: text(data.job_id), deduplicated: data.deduplicated, operation: envelope.operation }
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
.qa-regions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
gap: 12px;
|
||||
flex: 1;
|
||||
}
|
||||
.qa-region-heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.qa-region-heading h3 {
|
||||
margin: 0;
|
||||
}
|
||||
.qa-region-filters {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
align-items: end;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.qa-region-filters label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.qa-region-filters label:nth-child(2) {
|
||||
flex: 1;
|
||||
min-width: 220px;
|
||||
}
|
||||
.qa-region-filters input,
|
||||
.qa-region-filters select {
|
||||
min-height: 36px;
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--line, #d8e1eb);
|
||||
border-radius: 6px;
|
||||
background: var(--panel, #fff);
|
||||
color: inherit;
|
||||
}
|
||||
.qa-region-preview {
|
||||
display: flex;
|
||||
gap: 8px 18px;
|
||||
flex-wrap: wrap;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--line, #d8e1eb);
|
||||
background: var(--panel-muted, #f3f7fc);
|
||||
border-radius: 6px;
|
||||
}
|
||||
.qa-region-tree-scroll {
|
||||
min-height: 120px;
|
||||
overflow: auto;
|
||||
flex: 1;
|
||||
border: 1px solid var(--line, #d8e1eb);
|
||||
border-radius: 6px;
|
||||
}
|
||||
.qa-region-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
text-align: left;
|
||||
font-size: 13px;
|
||||
}
|
||||
.qa-region-table th,
|
||||
.qa-region-table td {
|
||||
padding: 10px 12px;
|
||||
border-bottom: 1px solid var(--line, #d8e1eb);
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.qa-region-table th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: var(--panel, #fff);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.qa-region-table td:nth-child(2) {
|
||||
min-width: 240px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.qa-region-table td:nth-child(3),
|
||||
.qa-region-table td:nth-child(4) {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.qa-region-table input[type='checkbox'] {
|
||||
width: 17px;
|
||||
height: 17px;
|
||||
cursor: pointer;
|
||||
accent-color: #1765c1;
|
||||
}
|
||||
.qa-region-tabs {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
.qa-region-tabs button[aria-pressed='true'] {
|
||||
background: #e5efff;
|
||||
border-color: #8db8f0;
|
||||
color: #154a88;
|
||||
}
|
||||
.qa-regions button:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.5;
|
||||
}
|
||||
.qa-regions p {
|
||||
margin: 0;
|
||||
}
|
||||
.qa-ops-warning > span {
|
||||
display: inline-block;
|
||||
margin: 4px 8px;
|
||||
}
|
||||
.qa-regions :focus-visible {
|
||||
outline: 2px solid #1765c1;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
@media (max-width: 700px) {
|
||||
.qa-region-filters {
|
||||
align-items: stretch;
|
||||
}
|
||||
.qa-region-filters label {
|
||||
flex: 1;
|
||||
}
|
||||
.qa-region-tree-scroll {
|
||||
min-height: 300px;
|
||||
}
|
||||
.qa-region-preview {
|
||||
font-size: 13px;
|
||||
}
|
||||
.qa-region-heading {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
Reference in New Issue
Block a user