Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 76671e0784 | |||
| 8835a473dd | |||
| 93aabc8a81 |
@@ -76,6 +76,40 @@
|
||||
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯,
|
||||
> 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。
|
||||
|
||||
## 开发快照 snapshot/v0.1.31 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 区域配置支持新增、改名业务区域;稳定区域 ID 与部门映射同版本保存,改名不丢失归属。部门按一级、二级、三级及更深层级展示,支持层级/完整路径筛选、多选及批量归属。
|
||||
- 勾选、批量应用、预览和保存分离;取消本次勾选不删除既有映射,批量配置父部门不清除未选子部门的显式规则。预览核对去重人数,保存后独立读取并校验配置版本。
|
||||
|
||||
### Changed
|
||||
|
||||
- 新增治理库迁移 51,为历史区域修订补齐原四区目录;业务目录与映射原子留档,跨页问答、看板、使用统计、个人月明细和周报共用同一版本及名称。旧请求未传目录时沿用当前目录,不恢复固定四区白名单。
|
||||
- 迁移回退发现自定义区域历史时拒绝丢失目录;应用回退可保留加列迁移。统计人数不升级为在职或绩效分母,不改钉钉组织、DobotAI 原始数据及旧 Excel 流程。
|
||||
|
||||
### Security
|
||||
|
||||
- 配置请求拒绝缺失版本、重复 JSON 字段及嵌套 null;区域目录校验稳定 ID、重名及保留键,名称按文本展示,自定义名称不读取原型属性。保留管理员同源写入、租户隔离和双版本冲突保护。
|
||||
|
||||
## 开发快照 snapshot/v0.1.30 - 2026-10-18
|
||||
|
||||
### Changed
|
||||
|
||||
- 继续清理问答运营的冗余提示:质量统计移除完整范围留档、模型接入和读取时间说明;个人月明细移除重复的绩效/零记录解释及读取时间,保留实际数量、范围版本、分页和真实错误。质量统计按钮使用简短名称,不改统计与审计逻辑。
|
||||
|
||||
## 开发快照 snapshot/v0.1.29 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 问答运营调整为“问题流水、问题统计看板、区域配置、周报生成”四页,流水与看板共用年份、自然周和查询条件;区域页不再显示问题查询框,完整字段及人工复核入口保留。
|
||||
- 重做统计看板:展示完整筛选范围的问题量、覆盖率、正确率、人工复核、北京时间每日趋势、质量分布、区域、问题类型和产品分类;个人月明细折叠保留,未知分类与零分母不虚构结论。
|
||||
- 周报页提供手动草稿、Markdown 预览及 MD/完整明细 CSV 下载。核对副本版本、完整数量、质量范围与覆盖分布后生成;CSV 保留完整十五列并防护公式注入,不发送、不归档、不作为正式持久化周报验收。
|
||||
|
||||
### Changed
|
||||
|
||||
- 删除问答记录、同步栏和区域页中的冗余解释文字、读取时间与源连接提示,保留真实错误、未同步、权限阻断和安全告警。
|
||||
|
||||
## 开发快照 snapshot/v0.1.28 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
+2
-2
@@ -69,7 +69,7 @@
|
||||
"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"]}}}}}}}}},
|
||||
"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"},"regions":{"type":"array","maxItems":100,"description":"可选业务区域目录;缺省沿用当前目录,空数组表示无区域;ID稳定不随名称改动。与rules同一版本原子预览/保存。","items":{"type":"object","additionalProperties":false,"required":["id","name"],"properties":{"id":{"type":"string","minLength":1,"maxLength":256},"name":{"type":"string","minLength":1,"maxLength":256}}}},"rules":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["department_id","region"],"properties":{"department_id":{"type":"string"},"region":{"type":"string","description":"目录中稳定的区域ID,不是固定四区枚举"}}}}}}}}},
|
||||
"responses": {
|
||||
"200": {"$ref": "#/components/responses/Envelope"},
|
||||
"400": {"$ref": "#/components/responses/BadRequest"},
|
||||
@@ -99,7 +99,7 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/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/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", "description": "当前组织版本中的区域显示名称,或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/quality/query": {"post": {"operationId": "queryQAQualityCounts", "summary": "按完整筛选范围读取指纹/规则元数据并留档统计,最多5000条;summary.rates 返回 quality-rates-human-first-v1、原始分子/分母、百分比与分母构成。覆盖率=covered/(covered+uncovered+partial),正确率=covered_correct/(covered_correct+covered_incorrect);失效/不计入/相应待确认与未评估排除,零分母percent=null。原文仅在读取问答/复核时采集", "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-quality"]}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"start": {"type": "string", "format": "date-time"}, "end": {"type": "string", "format": "date-time"}, "keyword": {"type": "string", "maxLength": 200}}, "required": ["start", "end"]}}}}, "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
|
||||
"/api/v1/qa-ops/records/{id}/reviews": {"post": {"operationId": "saveQAQualityReview", "summary": "治理库追加人工复核,登录身份审计,源端只读,输入/复核乐观锁和nonce幂等;正确时根因为空,不计入须说明原因", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}, {"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-quality"]}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"input_hash": {"type": "string", "pattern": "^[a-f0-9]{64}$"}, "input_epoch": {"type": "integer", "minimum": 1}, "base_revision": {"type": "integer", "minimum": 0}, "nonce": {"type": "string", "pattern": "^[A-Za-z0-9_-]{16,128}$"}, "fields": {"type": "object", "additionalProperties": false, "properties": {"coverage": {"type": "string", "enum": ["covered", "uncovered", "partial", "pending", "excluded"]}, "correctness": {"type": "string", "enum": ["correct", "incorrect", "pending"]}, "product_category": {"type": "string", "maxLength": 128}, "problem_type": {"type": "string", "maxLength": 128}, "root_cause": {"type": "string", "maxLength": 2000}, "exclusion_reason": {"type": "string", "maxLength": 2000}}, "required": ["coverage", "correctness"]}, "reason": {"type": "string", "minLength": 1, "maxLength": 4000}}, "required": ["input_hash", "input_epoch", "base_revision", "nonce", "fields", "reason"]}}}}, "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
|
||||
|
||||
@@ -13,6 +13,7 @@ type ActorIdentity struct {
|
||||
UnionID string `json:"union_id"`
|
||||
}
|
||||
type OrganizationVersion struct {
|
||||
RegionNames []string `json:"region_names"`
|
||||
State string `json:"state"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
DirectorySource string `json:"directory_source"`
|
||||
|
||||
@@ -31,7 +31,7 @@ func recordAttribution(ctx context.Context, config Config) (*qaopsorg.Attributio
|
||||
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"}
|
||||
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", RegionNames: p.Metadata.RegionLabels()}
|
||||
}
|
||||
func enrichQARecord(item *dobotaiops.Record, p *qaopsorg.Attribution) {
|
||||
person := p.Resolve(item.Identity.StaffID, item.Identity.UnionID)
|
||||
@@ -92,7 +92,7 @@ type qaUsage struct {
|
||||
|
||||
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")
|
||||
keys := append(append([]string{}, p.Metadata.RegionLabels()...), "unassigned", "cross_region", "unmatched", "identity_conflict", "no_identity", "directory_missing")
|
||||
rows := map[string]*qaUsageRow{}
|
||||
members := map[string]map[string]bool{}
|
||||
all := map[string]bool{}
|
||||
@@ -108,7 +108,12 @@ func summarizeQAUsage(groups dobotaiops.UsageGroups, p *qaopsorg.Attribution, qu
|
||||
n = p.Metadata.View.ConflictingPeople
|
||||
default:
|
||||
var ok bool
|
||||
n, ok = p.Metadata.View.Regions[key]
|
||||
for _, region := range p.Metadata.RegionDefinitions() {
|
||||
if region.Name == key {
|
||||
n, ok = p.Metadata.View.Regions[region.ID]
|
||||
break
|
||||
}
|
||||
}
|
||||
valid = ok
|
||||
}
|
||||
if valid {
|
||||
|
||||
@@ -97,11 +97,7 @@ func parseMonthlyFilter(values url.Values, now time.Time) (monthlyFilter, error)
|
||||
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 {
|
||||
if !utf8.ValidString(f.Region) || len(f.Region) > 256 || strings.TrimSpace(f.Region) != f.Region || strings.ContainsAny(f.Region, "\x00\r\n") {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
if !utf8.ValidString(f.Search) || utf8.RuneCountInString(f.Search) > 100 || strings.ContainsRune(f.Search, 0) {
|
||||
@@ -288,6 +284,16 @@ func qaMonthlyPeople(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if f.Region != "" && f.Region != "unassigned" && f.Region != "cross_region" {
|
||||
found := false
|
||||
for _, name := range p.Metadata.RegionLabels() {
|
||||
found = found || f.Region == name
|
||||
}
|
||||
if !found {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
}
|
||||
if f.Department != "" {
|
||||
found := false
|
||||
for _, d := range p.Metadata.View.Departments {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -36,9 +37,14 @@ func qaOrganization(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
var request qaopsorg.SaveRequest
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
|
||||
raw, readErr := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
|
||||
check := json.NewDecoder(bytes.NewReader(raw))
|
||||
var fields map[string]json.RawMessage
|
||||
var extra any
|
||||
invalidJSON := readErr != nil || json.Unmarshal(raw, &fields) != nil || fields == nil || fields["base_revision"] == nil || walkQualityJSON(check) != nil || check.Decode(&extra) != io.EOF
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&request) != nil || decoder.Decode(&struct{}{}) != io.EOF || request.DirectoryID == "" || request.Rules == nil {
|
||||
if invalidJSON || decoder.Decode(&request) != nil || decoder.Decode(&extra) != io.EOF || request.DirectoryID == "" || request.Rules == nil {
|
||||
writeOrgError(w, qaopsorg.ErrInvalid)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -52,6 +52,12 @@ func TestQAOrganizationGuardsIdentityIntentAndErrors(t *testing.T) {
|
||||
{"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","rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","regions":null,"rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","regions":[null],"rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","regions":[{"id":"edu","name":null}],"rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":[],"rules":[]}`, 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},
|
||||
} {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestQAUsageConsumesTheCustomRegionCatalog(t *testing.T) {
|
||||
p, err := qaopsorg.BuildAttribution(qaopsorg.State{State: "ready", DirectoryID: "fixture-directory", Regions: []qaopsorg.RegionDefinition{{ID: "edu", Name: "国内教育"}}, Rules: []qaopsorg.Rule{{DepartmentID: "a", Region: "edu"}}}, qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "a", Name: "示例部门"}}, People: []qaopsorg.Person{{ID: "fixture-person", DepartmentIDs: []string{"a"}}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
usage := summarizeQAUsage(dobotaiops.UsageGroups{Groups: []dobotaiops.UsageGroup{{Identity: dobotaiops.ActorIdentity{StaffID: "fixture-person"}, Total: 3, Succeeded: 2, Failed: 1}}}, p, dobotaiops.RecordQuery{})
|
||||
if usage.Questions != 3 || usage.IdentifiedUsers != 1 {
|
||||
t.Fatal("the historical whitelist dropped custom-region events")
|
||||
}
|
||||
found := false
|
||||
for _, row := range usage.Rows {
|
||||
if row.Key == "国内教育" {
|
||||
found = true
|
||||
if row.Questions != 3 || row.RosterPeople == nil || *row.RosterPeople != 1 || row.Users == nil || *row.Users != 1 {
|
||||
t.Fatal("custom-region counts or roster denominator were lost")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("custom-region row missing")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (SELECT 1 FROM qa_ops_region_revisions WHERE region_definitions <> '[{"id":"国内工业","name":"国内工业"},{"id":"APAC","name":"APAC"},{"id":"EMEA","name":"EMEA"},{"id":"America","name":"America"}]'::jsonb) THEN
|
||||
RAISE EXCEPTION 'custom region catalog exists; application rollback may keep migration 51, destructive catalog rollback refused';
|
||||
END IF;
|
||||
END $$;
|
||||
ALTER TABLE qa_ops_region_revisions DROP COLUMN region_definitions;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE qa_ops_region_revisions ADD COLUMN region_definitions JSONB NOT NULL DEFAULT '[{"id":"国内工业","name":"国内工业"},{"id":"APAC","name":"APAC"},{"id":"EMEA","name":"EMEA"},{"id":"America","name":"America"}]'::jsonb CHECK (jsonb_typeof(region_definitions)='array');
|
||||
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 50 {
|
||||
t.Fatalf("migration count = %d, want 50", len(migrations))
|
||||
if len(migrations) != 51 {
|
||||
t.Fatalf("migration count = %d, want 51", 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])
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRegionCatalogMigrationIsAdditiveAndRefusesLossyDown(t *testing.T) {
|
||||
migrations, e := loadMigrations()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var up, down string
|
||||
for _, m := range migrations {
|
||||
if m.Version == 51 {
|
||||
up = m.UpSQL
|
||||
down = m.DownSQL
|
||||
}
|
||||
}
|
||||
for _, fragment := range []string{"ADD COLUMN region_definitions JSONB NOT NULL DEFAULT", "jsonb_typeof(region_definitions)='array'", "国内工业", "APAC", "EMEA", "America"} {
|
||||
if !strings.Contains(up, fragment) {
|
||||
t.Fatal("missing additive/backfill region contract", fragment)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(down, "RAISE EXCEPTION") || !strings.Contains(down, "region_definitions <>") || !strings.Contains(down, "DROP COLUMN region_definitions") {
|
||||
t.Fatal("lossy down migration was not guarded")
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ func BuildAttribution(state State, directory Directory) (*Attribution, error) {
|
||||
if state.State != "ready" || state.DirectoryID == "" {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
view, err := Preview(directory, state.Rules)
|
||||
view, err := PreviewRegions(directory, state.Rules, state.RegionDefinitions())
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
@@ -65,7 +65,7 @@ func BuildAttribution(state State, directory Directory) (*Attribution, error) {
|
||||
if len(regions) == 1 {
|
||||
item.State = "matched"
|
||||
for region := range regions {
|
||||
item.Region = region
|
||||
item.Region = state.RegionLabel(region)
|
||||
}
|
||||
} else if len(regions) > 1 {
|
||||
item.State = "cross_region"
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package qaopsorg
|
||||
|
||||
import "unicode/utf8"
|
||||
|
||||
// IDs are immutable mapping keys; names are editable labels. Existing keys remain
|
||||
// intact when migrating the historical four-region configuration.
|
||||
type RegionDefinition struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func DefaultRegions() []RegionDefinition {
|
||||
result := make([]RegionDefinition, 0, len(RegionNames))
|
||||
for _, name := range RegionNames {
|
||||
result = append(result, RegionDefinition{ID: name, Name: name})
|
||||
}
|
||||
return result
|
||||
}
|
||||
func (s State) RegionDefinitions() []RegionDefinition {
|
||||
if s.Regions == nil {
|
||||
return DefaultRegions()
|
||||
}
|
||||
return s.Regions
|
||||
}
|
||||
func (s State) RegionLabels() []string {
|
||||
labels := []string{}
|
||||
for _, region := range s.RegionDefinitions() {
|
||||
labels = append(labels, region.Name)
|
||||
}
|
||||
return labels
|
||||
}
|
||||
func (s State) RegionLabel(id string) string {
|
||||
for _, region := range s.RegionDefinitions() {
|
||||
if region.ID == id {
|
||||
return region.Name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func validRegions(regions []RegionDefinition) bool {
|
||||
if len(regions) > 100 {
|
||||
return false
|
||||
}
|
||||
reserved := map[string]bool{"unassigned": true, "cross_region": true, "unmatched": true, "identity_conflict": true, "no_identity": true, "directory_missing": true, "__proto__": true, "constructor": true, "prototype": true}
|
||||
ids, names := map[string]bool{}, map[string]bool{}
|
||||
for _, region := range regions {
|
||||
if !validID(region.ID) || !validID(region.Name) || !utf8.ValidString(region.ID) || !utf8.ValidString(region.Name) || reserved[region.ID] || reserved[region.Name] || ids[region.ID] || names[region.Name] {
|
||||
return false
|
||||
}
|
||||
ids[region.ID] = true
|
||||
names[region.Name] = true
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCustomRegionCatalogRejectsAmbiguousOrReservedDefinitions(t *testing.T) {
|
||||
for _, regions := range [][]RegionDefinition{
|
||||
{{ID: "one", Name: "国内教育"}, {ID: "one", Name: "国外工业Amercia"}},
|
||||
{{ID: "one", Name: "国内教育"}, {ID: "two", Name: "国内教育"}},
|
||||
{{ID: "unassigned", Name: "区域"}}, {{ID: "one", Name: "cross_region"}},
|
||||
{{ID: "__proto__", Name: "区域"}}, {{ID: "one", Name: "constructor"}},
|
||||
{{ID: "one", Name: ""}}, {{ID: "one", Name: " 区域"}},
|
||||
} {
|
||||
if _, err := PreviewRegions(exampleDirectory(), nil, regions); err == nil {
|
||||
t.Fatal("invalid region catalog was accepted")
|
||||
}
|
||||
}
|
||||
if _, err := PreviewRegions(exampleDirectory(), []Rule{{DepartmentID: "sales", Region: "missing"}}, []RegionDefinition{{ID: "education", Name: "国内教育"}}); err == nil {
|
||||
t.Fatal("unknown mapping ID accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomRegionCatalogBindsStableIDAndRenamePreservesRules(t *testing.T) {
|
||||
directory := exampleDirectory()
|
||||
state := State{State: "ready", DirectoryID: "d", Rules: []Rule{}}
|
||||
var request SaveRequest
|
||||
if err := json.Unmarshal([]byte(`{"directory_id":"d","base_revision":"","regions":[{"id":"education","name":"国内教育"},{"id":"overseas","name":"国外工业Amercia"}],"rules":[{"department_id":"sales","region":"education"},{"department_id":"apac","region":"overseas"}]}`), &request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next, err := applyRequest(state, directory, request)
|
||||
if err != nil {
|
||||
t.Fatalf("custom business regions must not be rejected by the old four-name whitelist: %v", err)
|
||||
}
|
||||
if next.View.Regions["education"] != 1 || next.View.Regions["overseas"] != 1 || next.View.ConflictingPeople != 1 {
|
||||
t.Fatal("inheritance or stable-ID person dedup changed")
|
||||
}
|
||||
projection, err := BuildAttribution(next, directory)
|
||||
if err != nil || projection.Resolve("p2", "").Region != "国外工业Amercia" {
|
||||
t.Fatal("attribution did not use the same catalog display name")
|
||||
}
|
||||
raw, _ := json.Marshal(request)
|
||||
var body map[string]any
|
||||
_ = json.Unmarshal(raw, &body)
|
||||
body["regions"].([]any)[1].(map[string]any)["name"] = "国外工业 EMEA"
|
||||
raw, _ = json.Marshal(body)
|
||||
_ = json.Unmarshal(raw, &request)
|
||||
renamed, err := applyRequest(next, directory, request)
|
||||
if err != nil || renamed.Rules[0].Region != next.Rules[0].Region {
|
||||
t.Fatal("renaming changed the stable mapping")
|
||||
}
|
||||
projection, err = BuildAttribution(renamed, directory)
|
||||
if err != nil || projection.Resolve("p2", "").Region != "国外工业 EMEA" {
|
||||
t.Fatal("renamed catalog not consumed by attribution")
|
||||
}
|
||||
}
|
||||
@@ -46,12 +46,18 @@ type PreviewResult struct {
|
||||
|
||||
// Identity is department ID. Names and legacy keyword rules never decide ownership.
|
||||
func Preview(directory Directory, rules []Rule) (PreviewResult, error) {
|
||||
return PreviewRegions(directory, rules, DefaultRegions())
|
||||
}
|
||||
func PreviewRegions(directory Directory, rules []Rule, regions []RegionDefinition) (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
|
||||
if !validRegions(regions) {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
for _, region := range regions {
|
||||
result.Regions[region.ID] = 0
|
||||
}
|
||||
departments := make(map[string]Department, len(directory.Departments))
|
||||
for _, d := range directory.Departments {
|
||||
|
||||
+32
-21
@@ -26,20 +26,22 @@ type Import struct {
|
||||
Directory Directory `json:"directory"`
|
||||
}
|
||||
type SaveRequest struct {
|
||||
DirectoryID string `json:"directory_id"`
|
||||
BaseRevision string `json:"base_revision"`
|
||||
Rules []Rule `json:"rules"`
|
||||
Regions []RegionDefinition `json:"regions,omitempty"`
|
||||
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"`
|
||||
Regions []RegionDefinition `json:"regions"`
|
||||
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
|
||||
@@ -53,12 +55,14 @@ 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
|
||||
const defaultRegionsJSON = `[{"id":"国内工业","name":"国内工业"},{"id":"APAC","name":"APAC"},{"id":"EMEA","name":"EMEA"},{"id":"America","name":"America"}]`
|
||||
|
||||
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,COALESCE(r.region_definitions,'` + defaultRegionsJSON + `'::jsonb)
|
||||
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{}}}
|
||||
state := State{Regions: DefaultRegions(), State: "empty", Rules: []Rule{}, View: PreviewResult{Departments: []DepartmentView{}, Regions: map[string]int{}, MissingDepartments: []string{}}}
|
||||
for _, r := range RegionNames {
|
||||
state.View.Regions[r] = 0
|
||||
}
|
||||
@@ -67,15 +71,15 @@ func (s *Store) read(ctx context.Context, q orgQuerier, lock bool) (State, Direc
|
||||
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)
|
||||
var payload, rules, regions []byte
|
||||
err := q.QueryRow(ctx, query, s.tenant).Scan(&state.DirectoryID, &state.DirectorySource, &state.DirectorySyncedAt, &payload, &state.RevisionID, &rules, &state.UpdatedBy, &state.UpdatedAt, ®ions)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return state, directory, nil
|
||||
}
|
||||
if err != nil || json.Unmarshal(payload, &directory) != nil || json.Unmarshal(rules, &state.Rules) != nil {
|
||||
if err != nil || json.Unmarshal(payload, &directory) != nil || json.Unmarshal(rules, &state.Rules) != nil || json.Unmarshal(regions, &state.Regions) != nil || state.Regions == nil {
|
||||
return State{}, directory, ErrUnavailable
|
||||
}
|
||||
state.View, err = Preview(directory, state.Rules)
|
||||
state.View, err = PreviewRegions(directory, state.Rules, state.RegionDefinitions())
|
||||
if err != nil {
|
||||
return State{}, directory, ErrUnavailable
|
||||
}
|
||||
@@ -106,7 +110,11 @@ func applyRequest(state State, directory Directory, request SaveRequest) (State,
|
||||
if request.DirectoryID != state.DirectoryID || request.BaseRevision != state.RevisionID {
|
||||
return State{}, ErrConflict
|
||||
}
|
||||
view, err := Preview(directory, request.Rules)
|
||||
regions := request.Regions
|
||||
if regions == nil {
|
||||
regions = state.RegionDefinitions()
|
||||
}
|
||||
view, err := PreviewRegions(directory, request.Rules, regions)
|
||||
if err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
@@ -123,6 +131,7 @@ func applyRequest(state State, directory Directory, request SaveRequest) (State,
|
||||
}
|
||||
}
|
||||
state.View = view
|
||||
state.Regions = append([]RegionDefinition{}, regions...)
|
||||
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
|
||||
@@ -151,7 +160,9 @@ func (s *Store) SaveRules(ctx context.Context, request SaveRequest, actor string
|
||||
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) {
|
||||
oldRegions, _ := json.Marshal(current.RegionDefinitions())
|
||||
newRegions, _ := json.Marshal(next.RegionDefinitions())
|
||||
if current.RevisionID != "" && string(oldJSON) == string(newJSON) && string(oldRegions) == string(newRegions) {
|
||||
if tx.Commit(ctx) != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
@@ -164,7 +175,7 @@ func (s *Store) SaveRules(ctx context.Context, request SaveRequest, actor string
|
||||
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 {
|
||||
if err = tx.QueryRow(ctx, `INSERT INTO qa_ops_region_revisions(tenant_key,id,directory_id,rules,updated_by,region_definitions) VALUES($1,$2,$3,$4,$5,$6) RETURNING created_at`, s.tenant, next.RevisionID, next.DirectoryID, newJSON, actor, newRegions).Scan(&at); err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
next.UpdatedAt = &at
|
||||
|
||||
@@ -134,6 +134,65 @@ func TestOrganizationStoreRoundTripAndOptimisticConflict(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
|
||||
t.Run("custom catalog persists with the mapping and rename advances revision", func(t *testing.T) {
|
||||
custom := qaopsorg.NewStore(pool, "catalog-fixture")
|
||||
imported, e := custom.ReplaceDirectory(ctx, input)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
request := qaopsorg.SaveRequest{DirectoryID: imported.DirectoryID, Regions: []qaopsorg.RegionDefinition{{ID: "education", Name: "国内教育"}}, Rules: []qaopsorg.Rule{{DepartmentID: "a", Region: "education"}}}
|
||||
preview, e := custom.PreviewRules(ctx, request)
|
||||
if e != nil || preview.View.Regions["education"] != 1 {
|
||||
t.Fatal("custom preview failed", e)
|
||||
}
|
||||
unchanged, _ := custom.GetView(ctx)
|
||||
if unchanged.RevisionID != "" {
|
||||
t.Fatal("catalog preview wrote data")
|
||||
}
|
||||
saved, e := custom.SaveRules(ctx, request, "catalog-admin")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
fresh, e := pgxpool.New(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer fresh.Close()
|
||||
read, e := qaopsorg.NewStore(fresh, "catalog-fixture").GetView(ctx)
|
||||
if e != nil || len(read.Regions) != 1 || read.Regions[0].Name != "国内教育" || read.Rules[0].Region != "education" {
|
||||
t.Fatal("catalog was not persisted with its rules", e)
|
||||
}
|
||||
request.BaseRevision = saved.RevisionID
|
||||
request.Regions[0].Name = "国外工业Amercia"
|
||||
renamed, e := custom.SaveRules(ctx, request, "catalog-admin")
|
||||
if e != nil || renamed.RevisionID == saved.RevisionID {
|
||||
t.Fatal("rename did not create an atomic revision", e)
|
||||
}
|
||||
projection, e := custom.GetAttribution(ctx)
|
||||
if e != nil || projection.Resolve("u1", "").Region != "国外工业Amercia" {
|
||||
t.Fatal("renamed labels not shared by the read paths")
|
||||
}
|
||||
if _, e = custom.SaveRules(ctx, request, "stale-admin"); !errors.Is(e, qaopsorg.ErrConflict) {
|
||||
t.Fatal("rename allowed stale overwrite")
|
||||
}
|
||||
request.BaseRevision = renamed.RevisionID
|
||||
repeated, e := custom.SaveRules(ctx, request, "catalog-admin")
|
||||
if e != nil || repeated.RevisionID != renamed.RevisionID {
|
||||
t.Fatal("unchanged catalog appended another revision")
|
||||
}
|
||||
if e = postgresstore.RollbackLatestMigration(ctx, pool); e == nil {
|
||||
t.Fatal("down migration discarded a custom catalog")
|
||||
}
|
||||
if _, e = custom.GetView(ctx); e != nil {
|
||||
t.Fatal("refused down migration damaged last-good catalog")
|
||||
}
|
||||
for _, table := range []string{"qa_ops_organization_state", "qa_ops_region_revisions", "qa_ops_directory_snapshots"} {
|
||||
if _, e = pool.Exec(ctx, "DELETE FROM "+table+" WHERE tenant_key=$1", "catalog-fixture"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
})
|
||||
// This test exercises migration 48, not whichever unrelated migration is latest.
|
||||
for {
|
||||
var latest int64
|
||||
|
||||
@@ -25,6 +25,6 @@ describe('AI answer Markdown preview', () => {
|
||||
expect(html).toContain('查看图片')
|
||||
})
|
||||
it('does not confuse an empty answer with a positive assessment', () => {
|
||||
expect(renderToStaticMarkup(<QAAnswerMarkdown answer="" />)).toContain('尚无答案;不默认判覆盖或正确')
|
||||
expect(renderToStaticMarkup(<QAAnswerMarkdown answer="" />)).toContain('暂无答案')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -16,7 +16,7 @@ export function safeAnswerURL(value: string): string {
|
||||
|
||||
export function QAAnswerMarkdown({ answer }: { answer: string }) {
|
||||
const [showImages, setShowImages] = useState(false)
|
||||
if (!answer) return <p>尚无答案;不默认判覆盖或正确</p>
|
||||
if (!answer) return <p>暂无答案</p>
|
||||
return (
|
||||
<div className="qa-answer">
|
||||
<div className="qa-answer-tools">
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { qaDailySeries, qaCategorySeries } from './qaDashboard'
|
||||
import { QADashboardView } from './QADashboard'
|
||||
import type { QARecord, QAQuery } from './qaOps'
|
||||
const query: QAQuery = { start: '2026-10-11T16:00:00Z', end: '2026-10-13T16:00:00Z', keyword: '', cursor: '' }
|
||||
const records = [
|
||||
{ id: 'a', asked_at: '2026-10-11T16:30:00Z', product_category: '<img src=x onerror=alert(1)>', problem_type: '通信' },
|
||||
{ id: 'b', asked_at: '2026-10-12T16:01:00Z' },
|
||||
] as QARecord[]
|
||||
describe('question dashboard projections', () => {
|
||||
it('groups by Beijing day and keeps zero days instead of using the browser timezone', () => {
|
||||
expect(qaDailySeries(records, query)).toEqual([
|
||||
{ label: '2026-10-12', count: 1 },
|
||||
{ label: '2026-10-13', count: 1 },
|
||||
])
|
||||
expect(qaDailySeries([], query).map((p) => p.count)).toEqual([0, 0])
|
||||
})
|
||||
it('keeps unclassified records distinct without inventing a category', () => {
|
||||
expect(qaCategorySeries(records, 'problem_type')).toEqual([
|
||||
{ label: '通信', count: 1 },
|
||||
{ label: '未分类', count: 1 },
|
||||
])
|
||||
})
|
||||
it('renders the real dashboard panels and escaped category text', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<QADashboardView
|
||||
page={{ items: records, columns: [], total: 2, has_more: false, next_cursor: '', as_of: query.end }}
|
||||
query={query}
|
||||
quality={null}
|
||||
usage={null}
|
||||
loading={false}
|
||||
error=""
|
||||
onRetry={vi.fn()}
|
||||
/>
|
||||
)
|
||||
for (const title of ['问题总量', '每日提问趋势', '质量分布', '区域分布', '产品分类', '问题类型'])
|
||||
expect(html).toContain(title)
|
||||
expect(html).not.toContain('<img src=x')
|
||||
expect(html).not.toContain('0.0%')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,223 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { QARecordPage, QAQuery } from './qaOps'
|
||||
import type { QualitySummary, QualityRate } from './qaQuality'
|
||||
import type { QAUsage } from './qaUsage'
|
||||
import { fetchQAUsage, usageLabels } from './qaUsage'
|
||||
import { qaDailySeries, qaCategorySeries, fetchQADashboardQuality } from './qaDashboard'
|
||||
import type { QACountPoint } from './qaDashboard'
|
||||
import { QAMonthly } from './QAMonthly'
|
||||
import './qaDashboard.css'
|
||||
export interface QADashboardProps {
|
||||
page: QARecordPage | null
|
||||
query: QAQuery | null
|
||||
quality: QualitySummary | null
|
||||
usage: QAUsage | null
|
||||
loading: boolean
|
||||
error: string
|
||||
onRetry: () => void
|
||||
}
|
||||
const percent = (r: QualityRate | undefined) => (r?.percent == null ? '—' : `${r.percent.toFixed(1)}%`)
|
||||
function Bars({ points }: { points: QACountPoint[] }) {
|
||||
const max = Math.max(1, ...points.map((p) => p.count))
|
||||
return points.length ? (
|
||||
<div className="qa-chart-bars">
|
||||
{points.map((p) => (
|
||||
<div className="qa-chart-bar" key={p.label}>
|
||||
<span title={p.label}>{p.label}</span>
|
||||
<div className="qa-chart-track">
|
||||
<i style={{ width: `${(p.count / max) * 100}%` }} />
|
||||
</div>
|
||||
<b>{p.count}</b>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="qa-chart-empty">暂无数据</p>
|
||||
)
|
||||
}
|
||||
export function QADashboardView(p: QADashboardProps) {
|
||||
const page = p.loading ? null : p.page,
|
||||
items = page?.items || [],
|
||||
q = page && p.quality?.summary.total === page.total ? p.quality : null
|
||||
const b = q?.summary.rates.breakdown
|
||||
const daily = page && p.query ? qaDailySeries(items, p.query) : []
|
||||
const max = Math.max(1, ...daily.map((d) => d.count))
|
||||
const outcomes = b
|
||||
? [
|
||||
['已覆盖', b.covered],
|
||||
['未覆盖', b.uncovered],
|
||||
['部分覆盖', b.partial],
|
||||
['待确认', b.pending],
|
||||
['未评估', b.unassessed],
|
||||
['不计入', b.excluded],
|
||||
['待重新核对', b.stale],
|
||||
].map(([label, count]) => ({ label: String(label), count: Number(count) }))
|
||||
: []
|
||||
return (
|
||||
<section className="qa-dashboard" aria-label="问题统计看板">
|
||||
{p.error ? (
|
||||
<div role="alert" className="error-banner">
|
||||
{p.error}{' '}
|
||||
<button type="button" onClick={p.onRetry}>
|
||||
重新读取
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
{p.loading ? <p role="status">正在读取完整统计范围…</p> : null}
|
||||
<div className="qa-dashboard-metrics" aria-label="问题概览">
|
||||
<div>
|
||||
<span>问题总量</span>
|
||||
<strong>{page?.total ?? '—'}</strong>
|
||||
<small>条</small>
|
||||
</div>
|
||||
<div>
|
||||
<span>知识覆盖率</span>
|
||||
<strong>{percent(q?.summary.rates.coverage)}</strong>
|
||||
<small>
|
||||
{q ? `${q.summary.rates.coverage.numerator} / ${q.summary.rates.coverage.denominator}` : '分子 / 分母'}
|
||||
</small>
|
||||
</div>
|
||||
<div>
|
||||
<span>回答正确率</span>
|
||||
<strong>{percent(q?.summary.rates.correctness)}</strong>
|
||||
<small>
|
||||
{q
|
||||
? `${q.summary.rates.correctness.numerator} / ${q.summary.rates.correctness.denominator}`
|
||||
: '分子 / 分母'}
|
||||
</small>
|
||||
</div>
|
||||
<div>
|
||||
<span>已人工复核</span>
|
||||
<strong>{q?.summary.reviewed ?? '—'}</strong>
|
||||
<small>{q ? `待复核 ${q.summary.unreviewed}` : '条'}</small>
|
||||
</div>
|
||||
</div>
|
||||
<div className="qa-dashboard-grid">
|
||||
<section className="qa-chart qa-chart-wide">
|
||||
<h3>每日提问趋势</h3>
|
||||
{daily.length ? (
|
||||
<div className="qa-daily-chart" role="img" aria-label="北京时间每日提问量">
|
||||
{daily.map((d) => (
|
||||
<div key={d.label} title={`${d.label}:${d.count} 条`}>
|
||||
<b>{d.count}</b>
|
||||
<div>
|
||||
<i style={{ height: `${(d.count / max) * 100}%` }} />
|
||||
</div>
|
||||
<span>{d.label.slice(5)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="qa-chart-empty">暂无数据</p>
|
||||
)}
|
||||
</section>
|
||||
<section className="qa-chart">
|
||||
<h3>质量分布</h3>
|
||||
<Bars points={outcomes} />
|
||||
</section>
|
||||
<section className="qa-chart qa-chart-wide">
|
||||
<h3>区域分布</h3>
|
||||
<Bars
|
||||
points={
|
||||
p.usage?.rows
|
||||
.filter((r) => r.questions > 0)
|
||||
.map((r) => ({ label: usageLabels[r.key] || r.key, count: r.questions })) || []
|
||||
}
|
||||
/>
|
||||
{p.usage ? (
|
||||
<div className="qa-dashboard-region-table">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>区域</th>
|
||||
<th>提问量</th>
|
||||
<th>已关联使用人数</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{p.usage.rows
|
||||
.filter((r) => r.questions > 0 || r.roster_people !== null)
|
||||
.map((r) => (
|
||||
<tr key={r.key}>
|
||||
<td>{usageLabels[r.key] || r.key}</td>
|
||||
<td>{r.questions}</td>
|
||||
<td>{r.users ?? '—'}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
<section className="qa-chart">
|
||||
<h3>问题类型</h3>
|
||||
<Bars points={qaCategorySeries(items, 'problem_type')} />
|
||||
</section>
|
||||
<section className="qa-chart qa-chart-full">
|
||||
<h3>产品分类</h3>
|
||||
<Bars points={qaCategorySeries(items, 'product_category')} />
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
export function QADashboard({
|
||||
page,
|
||||
query,
|
||||
loading,
|
||||
error,
|
||||
revision,
|
||||
onRetry,
|
||||
}: {
|
||||
page: QARecordPage | null
|
||||
query: QAQuery | null
|
||||
loading: boolean
|
||||
error: string | null
|
||||
revision: number
|
||||
onRetry: () => void
|
||||
}) {
|
||||
const [quality, setQuality] = useState<QualitySummary | null>(null),
|
||||
[usage, setUsage] = useState<QAUsage | null>(null),
|
||||
[failure, setFailure] = useState(''),
|
||||
[monthly, setMonthly] = useState(false)
|
||||
useEffect(() => {
|
||||
setQuality(null)
|
||||
setUsage(null)
|
||||
setFailure('')
|
||||
if (!query) return
|
||||
const abort = new AbortController()
|
||||
void fetchQADashboardQuality(query, abort.signal)
|
||||
.then((v) => {
|
||||
if (!abort.signal.aborted) setQuality(v)
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!abort.signal.aborted) setFailure(e instanceof Error ? e.message : '质量统计读取失败')
|
||||
})
|
||||
void fetchQAUsage(query, abort.signal)
|
||||
.then((v) => {
|
||||
if (!abort.signal.aborted) setUsage(v)
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!abort.signal.aborted) setFailure(e instanceof Error ? e.message : '区域统计读取失败')
|
||||
})
|
||||
return () => abort.abort()
|
||||
}, [query, revision])
|
||||
const mismatch = !!page && !!quality && page.total !== quality.summary.total
|
||||
return (
|
||||
<div className="qa-dashboard-scroll">
|
||||
<QADashboardView
|
||||
page={page}
|
||||
query={query}
|
||||
quality={quality}
|
||||
usage={usage}
|
||||
loading={loading}
|
||||
error={error || failure || (mismatch ? '统计范围已更新,请重新查询' : '')}
|
||||
onRetry={onRetry}
|
||||
/>
|
||||
<details className="qa-monthly-disclosure" onToggle={(e) => setMonthly(e.currentTarget.open)}>
|
||||
<summary>个人月明细</summary>
|
||||
{monthly ? <QAMonthly /> : null}
|
||||
</details>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -22,7 +22,7 @@ describe('local Q&A synchronization strip', () => {
|
||||
expect(html).toContain('本地数据库')
|
||||
expect(html).toContain('首次同步尚未完成')
|
||||
expect(html).toContain('立即同步')
|
||||
expect(html).toContain('每 5 分钟')
|
||||
expect(html).not.toContain('每 5 分钟后台同步 · 查询不请求远端')
|
||||
})
|
||||
it('keeps the last-good dataset visibly stale after a failed sync', () => {
|
||||
const status = {
|
||||
@@ -38,7 +38,7 @@ describe('local Q&A synchronization strip', () => {
|
||||
const html = renderToStaticMarkup(<QAMirrorSyncView status={status} error="" submitting={false} onSync={vi.fn()} />)
|
||||
expect(html).toContain('639')
|
||||
expect(html).toContain('保留上次成功数据')
|
||||
expect(html).toContain('最近成功同步')
|
||||
expect(html).not.toContain('不承诺实时源快照')
|
||||
})
|
||||
it('distinguishes authorization blocking from an ordinary network failure', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
|
||||
@@ -9,7 +9,6 @@ interface ViewProps {
|
||||
submitting: boolean
|
||||
onSync: () => void
|
||||
}
|
||||
const stamp = (v: string) => new Date(v).toLocaleString('zh-CN', { hour12: false })
|
||||
export function QAMirrorSyncView(p: ViewProps) {
|
||||
const s = p.status
|
||||
const active = mirrorSyncActive(s)
|
||||
@@ -17,7 +16,7 @@ export function QAMirrorSyncView(p: ViewProps) {
|
||||
<section className="qa-mirror-sync" aria-label="问答本地数据库与同步状态">
|
||||
<div className="qa-mirror-sync-line">
|
||||
<strong>本地数据库</strong>
|
||||
<span>每 5 分钟后台同步 · 查询不请求远端</span>
|
||||
|
||||
{s?.ready ? <span>已同步 {s.records} 条</span> : null}
|
||||
<button type="button" onClick={p.onSync} disabled={p.submitting || !s?.worker_ready || active}>
|
||||
{p.submitting ? '正在入队…' : active ? '后台同步中…' : '立即同步'}
|
||||
@@ -30,7 +29,7 @@ export function QAMirrorSyncView(p: ViewProps) {
|
||||
? '源端权限校验未通过,本地读取已阻断;修复授权后可重新同步。'
|
||||
: !s.ready
|
||||
? '首次同步尚未完成,暂不把未同步数据视为空结果。'
|
||||
: `最近成功同步:${stamp(s.last_success_at!)};页面基于该本地副本,不承诺实时源快照。`}
|
||||
: ''}
|
||||
{s?.job && active ? (
|
||||
<span>
|
||||
{' '}
|
||||
|
||||
@@ -14,9 +14,17 @@ describe('personal monthly view', () => {
|
||||
onPage={() => {}}
|
||||
/>
|
||||
)
|
||||
for (const text of ['本源零记录', '当月进度', '姓名未同步', '不是考核名单', '当前通讯录', '未关联'])
|
||||
expect(html).toContain(text)
|
||||
for (const text of ['本源零记录', '当月进度', '姓名未同步', '当前通讯录', '未关联']) expect(html).toContain(text)
|
||||
expect(html).not.toContain('<script>')
|
||||
for (const text of [
|
||||
'不是考核名单',
|
||||
'本次读取:',
|
||||
'0 仅表示本源未关联到提问',
|
||||
'成功/失败不是答案正确性结论',
|
||||
'上方全名册指标不随人员筛选变化',
|
||||
])
|
||||
expect(html).not.toContain(text)
|
||||
expect(html).toContain('qa-ops-page-bar')
|
||||
expect(html).not.toContain('达标率')
|
||||
expect(html).not.toContain('绩效合格')
|
||||
})
|
||||
|
||||
+10
-14
@@ -36,24 +36,20 @@ export function QAMonthlyView({ data, loading, error, onRetry, onPage }: ViewPro
|
||||
<span>仅 DobotAI 2.0 · 北京时间</span>
|
||||
</div>
|
||||
<p className="qa-ops-muted">
|
||||
全名册:{data.roster_people} 人 · 已关联提问 {data.used_people} 人 · 本源零记录 {data.zero_people}{' '}
|
||||
人。名册来自当前通讯录,不是在职证明,也不是考核名单。
|
||||
当前通讯录:{data.roster_people} 人 · 已关联提问 {data.used_people} 人 · 本源零记录 {data.zero_people} 人
|
||||
</p>
|
||||
<p className="qa-ops-muted">
|
||||
本月范围内 {data.questions} 条问答,已关联 {data.linked_questions} 条,未关联 {data.unresolved_questions}{' '}
|
||||
条。0 仅表示本源未关联到提问,不等于实际未使用;成功/失败不是答案正确性结论。
|
||||
本月问答 {data.questions} 条 · 已关联 {data.linked_questions} 条 · 未关联 {data.unresolved_questions} 条
|
||||
</p>
|
||||
{data.missing_names > 0 ? (
|
||||
<p className="qa-ops-warning">
|
||||
{data.missing_names} 人姓名未同步,请重新同步通讯录;不根据姓名猜身份,不用原始标识代替姓名。
|
||||
</p>
|
||||
<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>
|
||||
@@ -61,7 +57,6 @@ export function QAMonthlyView({ data, loading, error, onRetry, onPage }: ViewPro
|
||||
<span>
|
||||
符合人员筛选 {data.total} 人 · 第 {data.page} 页
|
||||
</span>
|
||||
<span>上方全名册指标不随人员筛选变化</span>
|
||||
</div>
|
||||
{data.rows.length ? (
|
||||
<div className="qa-ops-table-scroll" aria-label="个人月明细表格滚动区" tabIndex={0}>
|
||||
@@ -78,7 +73,7 @@ export function QAMonthlyView({ data, loading, error, onRetry, onPage }: ViewPro
|
||||
<tr key={row.key}>
|
||||
<td>{row.name || '姓名未同步'}</td>
|
||||
<td>{row.departments.join(';') || '无部门记录'}</td>
|
||||
<td>{usageLabels[row.region || row.state]}</td>
|
||||
<td>{usageLabels[row.region || row.state] ?? (row.region || row.state)}</td>
|
||||
<td>{row.questions}</td>
|
||||
<td>{row.succeeded}</td>
|
||||
<td>{row.failed}</td>
|
||||
@@ -89,10 +84,9 @@ export function QAMonthlyView({ data, loading, error, onRetry, onPage }: ViewPro
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<p className="qa-ops-empty">没有符合人员筛选的记录,请调整条件;这不是通讯录为空。</p>
|
||||
<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)}>
|
||||
@@ -123,6 +117,7 @@ export function QAMonthly() {
|
||||
const [request, setRequest] = useState<MonthlyQuery>({ month: draft.month })
|
||||
const [data, setData] = useState<MonthlyPeople | null>(null),
|
||||
[options, setOptions] = useState<MonthlyPeople['department_options']>([]),
|
||||
[regionOptions, setRegionOptions] = useState<string[]>([]),
|
||||
[loading, setLoading] = useState(false),
|
||||
[error, setError] = useState('')
|
||||
useEffect(() => {
|
||||
@@ -135,6 +130,7 @@ export function QAMonthly() {
|
||||
if (!controller.signal.aborted) {
|
||||
setData(next)
|
||||
setOptions(next.department_options)
|
||||
setRegionOptions(next.organization.region_names ?? [])
|
||||
}
|
||||
})
|
||||
.catch((reason) => {
|
||||
@@ -202,9 +198,9 @@ export function QAMonthly() {
|
||||
区域 / 状态
|
||||
<select value={draft.region} disabled={loading} onChange={(e) => change('region', e.target.value)}>
|
||||
<option value="">全部区域 / 状态</option>
|
||||
{['国内工业', 'APAC', 'EMEA', 'America', 'unassigned', 'cross_region'].map((key) => (
|
||||
{[...regionOptions, 'unassigned', 'cross_region'].map((key) => (
|
||||
<option key={key} value={key}>
|
||||
{usageLabels[key]}
|
||||
{usageLabels[key] ?? key}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { QAOperationsView } from './QAOperations'
|
||||
import { QAOperationsTabs, QAOperationsView } from './QAOperations'
|
||||
import type { QARecord, QARecordPage } from './qaOps'
|
||||
import { restoreWorkspace } from './workspace'
|
||||
|
||||
@@ -50,6 +50,19 @@ const props = {
|
||||
}
|
||||
|
||||
describe('QA operations workbench', () => {
|
||||
it('uses the four requested destinations in their fixed order', () => {
|
||||
const html = renderToStaticMarkup(<QAOperationsTabs view="records" onChange={vi.fn()} />)
|
||||
const labels = ['问题流水', '问题统计看板', '区域配置', '周报生成']
|
||||
for (const label of labels) expect(html).toContain(label)
|
||||
for (let i = 1; i < labels.length; i++) expect(html.indexOf(labels[i - 1])).toBeLessThan(html.indexOf(labels[i]))
|
||||
expect(html).not.toContain('部门/区域保留源快照')
|
||||
})
|
||||
it('removes explanatory banners without hiding errors or any required column', () => {
|
||||
const html = renderToStaticMarkup(<QAOperationsView {...props} />)
|
||||
expect(html).not.toContain('本次读取')
|
||||
expect(html).not.toContain('固定显示完整字段')
|
||||
expect(html).not.toContain('DobotAI 2.0 / 钉钉')
|
||||
})
|
||||
it('shows all required columns even when empty and keeps false/downvotes visible', () => {
|
||||
const html = renderToStaticMarkup(<QAOperationsView {...props} />)
|
||||
expect(html).toContain('原始问题')
|
||||
|
||||
+106
-138
@@ -5,9 +5,9 @@ import { fetchQARecord, fetchAllQARecords, fetchQAStatus, qaCellValue, qaColumns
|
||||
import type { QAQuery, QARecord, QARecordPage, QAStatus } from './qaOps'
|
||||
import './qaOps.css'
|
||||
import { QARegions } from './QARegions'
|
||||
import { QAUsage } from './QAUsage'
|
||||
import { QAMonthly } from './QAMonthly'
|
||||
import { QAQualityEditor, QAQualityCounts } from './QAQuality'
|
||||
import { QADashboard } from './QADashboard'
|
||||
import { QAWeekly } from './QAWeekly'
|
||||
import { QAQualityEditor } from './QAQuality'
|
||||
import { qualityLabels } from './qaQuality'
|
||||
import { usageLabels } from './qaUsage'
|
||||
import { QAWeekPicker } from './QAWeekPicker'
|
||||
@@ -15,6 +15,25 @@ import { QAAnswerMarkdown } from './QAAnswerMarkdown'
|
||||
import { QAMirrorSync } from './QAMirrorSync'
|
||||
import { currentQAWeek, qaDateTimeToISO, qaWeekQueryRange } from './qaWeeks'
|
||||
|
||||
export type QAOpsView = 'records' | 'dashboard' | 'regions' | 'weekly'
|
||||
export function QAOperationsTabs({ view, onChange }: { view: QAOpsView; onChange: (view: QAOpsView) => void }) {
|
||||
return (
|
||||
<nav className="qa-region-tabs" aria-label="问答运营视图">
|
||||
{(
|
||||
[
|
||||
['records', '问题流水'],
|
||||
['dashboard', '问题统计看板'],
|
||||
['regions', '区域配置'],
|
||||
['weekly', '周报生成'],
|
||||
] as const
|
||||
).map(([id, label]) => (
|
||||
<button key={id} type="button" aria-pressed={view === id} onClick={() => onChange(id)}>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
interface ViewProps {
|
||||
onQualitySaved?: (record: QARecord) => void
|
||||
onReloadDetail?: () => void
|
||||
@@ -30,7 +49,6 @@ interface ViewProps {
|
||||
progress?: { loaded: number; total: number }
|
||||
onRetry: () => void
|
||||
}
|
||||
const stateLabels = { disabled: '未配置', unavailable: '连接不可用', blocked: '接入被阻断', connected: '已连接' }
|
||||
const warningLabels: Record<string, string> = {
|
||||
database_temp_enabled: '数据库仍允许临时对象:未视为完全只读验收通过',
|
||||
database_transport_unencrypted: '数据库连接未启用 TLS:上线前须完成传输安全审核',
|
||||
@@ -59,17 +77,8 @@ export function QAOperationsView(props: ViewProps) {
|
||||
? `共 ${page.total} 条 · 已展示 ${page.items.length} 条`
|
||||
: '尚未读取问答'}
|
||||
</span>
|
||||
<span className="qa-ops-source">
|
||||
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] ?? '数据源有待审核的安全告警'}
|
||||
@@ -138,12 +147,7 @@ export function QAOperationsView(props: ViewProps) {
|
||||
) : page && !props.loading && !props.error ? (
|
||||
<p className="qa-ops-empty">没有符合条件的问答,请调整时间范围或关键词。</p>
|
||||
) : null}
|
||||
{page ? (
|
||||
<footer className="qa-ops-page-bar">
|
||||
<span>本次读取:{stamp(page.as_of)} · 固定显示完整字段,左右滚动查看;— 表示暂无数据</span>
|
||||
<span>{page.items.length === page.total ? '已全部展示' : '全量读取尚未完成'}</span>
|
||||
</footer>
|
||||
) : null}
|
||||
|
||||
{showDrawer ? (
|
||||
<>
|
||||
<button
|
||||
@@ -299,8 +303,7 @@ function initialDraft() {
|
||||
}
|
||||
|
||||
export function QAOperations() {
|
||||
const [view, setView] = useState<'records' | 'regions' | 'usage'>('records')
|
||||
const [usageMode, setUsageMode] = useState<'regions' | 'monthly'>('regions')
|
||||
const [view, setView] = useState<QAOpsView>('records')
|
||||
const auth = useOptionalAuth()
|
||||
const canRead = auth?.identity?.role === 'admin'
|
||||
const [draft, setDraft] = useState(initialDraft)
|
||||
@@ -331,7 +334,7 @@ export function QAOperations() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!query || !canRead) return
|
||||
if (view !== 'records') {
|
||||
if (view !== 'records' && view !== 'dashboard') {
|
||||
setLoading(false)
|
||||
detailRequest.current?.abort()
|
||||
setDetail(null)
|
||||
@@ -414,13 +417,11 @@ export function QAOperations() {
|
||||
setDetailLoading(false)
|
||||
returnFocus.current?.focus()
|
||||
}
|
||||
const queryView = view === 'records' || view === 'dashboard'
|
||||
return (
|
||||
<section className="qa-ops" aria-label="问答运营">
|
||||
<header className="qa-ops-header">
|
||||
<h2>
|
||||
问答运营 <span>/ {view === 'regions' ? '区域归属' : view === 'usage' ? '使用统计' : '问答记录'}</span>
|
||||
</h2>
|
||||
<p>本地问答查询;远端只读后台同步,原始记录与人工复核分开保留。</p>
|
||||
<h2>问答运营</h2>
|
||||
</header>
|
||||
{!canRead ? (
|
||||
<p className="error-banner" role="alert">
|
||||
@@ -428,78 +429,48 @@ export function QAOperations() {
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<QAMirrorSync
|
||||
onChanged={() => {
|
||||
if (detail || detailLoading) {
|
||||
setMirrorChanged(true)
|
||||
return
|
||||
}
|
||||
setQuery((q) => (q ? { ...q } : q))
|
||||
setRevision((v) => v + 1)
|
||||
setQualityRevision((v) => v + 1)
|
||||
}}
|
||||
/>
|
||||
{mirrorChanged ? (
|
||||
<p className="qa-ops-warning">本地副本已更新;当前详情和未保存复核不会被覆盖,关闭详情后刷新列表。</p>
|
||||
) : null}
|
||||
<nav className="qa-region-tabs" aria-label="问答运营视图">
|
||||
<button type="button" aria-pressed={view === 'records'} onClick={() => setView('records')}>
|
||||
问答记录
|
||||
</button>
|
||||
<button type="button" aria-pressed={view === 'usage'} onClick={() => setView('usage')}>
|
||||
使用统计
|
||||
</button>
|
||||
<button type="button" aria-pressed={view === 'regions'} onClick={() => setView('regions')}>
|
||||
区域使用
|
||||
</button>
|
||||
</nav>
|
||||
{view === '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 />
|
||||
) : (
|
||||
<QAOperationsTabs view={view} onChange={setView} />
|
||||
{queryView ? (
|
||||
<>
|
||||
<QAMirrorSync
|
||||
onChanged={() => {
|
||||
if (detail || detailLoading) {
|
||||
setMirrorChanged(true)
|
||||
return
|
||||
}
|
||||
setQuery((q) => (q ? { ...q } : q))
|
||||
setRevision((v) => v + 1)
|
||||
setQualityRevision((v) => v + 1)
|
||||
}}
|
||||
/>
|
||||
{mirrorChanged ? <p className="qa-ops-warning">数据已更新,关闭详情后刷新。</p> : null}
|
||||
<form className="qa-ops-query" onSubmit={submit}>
|
||||
{view === 'records' ? (
|
||||
<QAWeekPicker
|
||||
year={draft.year}
|
||||
week={draft.week}
|
||||
onCurrentWeek={() => {
|
||||
const current = initialDraft()
|
||||
setDraft({ ...current, keyword: draft.keyword })
|
||||
setQuery({
|
||||
start: qaDateTimeToISO(current.start),
|
||||
end: qaDateTimeToISO(current.end),
|
||||
keyword: draft.keyword,
|
||||
cursor: '',
|
||||
})
|
||||
}}
|
||||
onChange={(year, week) => {
|
||||
setDraft((old) => {
|
||||
if (week === null) return { ...old, year, week }
|
||||
const { start, end } = qaWeekQueryRange(year, week)
|
||||
return { ...old, year, week, start, end }
|
||||
})
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<QAWeekPicker
|
||||
year={draft.year}
|
||||
week={draft.week}
|
||||
onCurrentWeek={() => {
|
||||
const current = initialDraft()
|
||||
setDraft({ ...current, keyword: draft.keyword })
|
||||
setQuery({
|
||||
start: qaDateTimeToISO(current.start),
|
||||
end: qaDateTimeToISO(current.end),
|
||||
keyword: draft.keyword,
|
||||
cursor: '',
|
||||
})
|
||||
}}
|
||||
onChange={(year, week) =>
|
||||
setDraft((old) =>
|
||||
week === null ? { ...old, year, week } : { ...old, ...qaWeekQueryRange(year, week) }
|
||||
)
|
||||
}
|
||||
/>
|
||||
<label>
|
||||
开始时间(北京时间)
|
||||
<input
|
||||
type="datetime-local"
|
||||
required
|
||||
value={draft.start}
|
||||
onChange={(event) => setDraft({ ...draft, start: event.target.value, week: null })}
|
||||
onChange={(e) => setDraft({ ...draft, start: e.target.value, week: null })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
@@ -508,7 +479,7 @@ export function QAOperations() {
|
||||
type="datetime-local"
|
||||
required
|
||||
value={draft.end}
|
||||
onChange={(event) => setDraft({ ...draft, end: event.target.value, week: null })}
|
||||
onChange={(e) => setDraft({ ...draft, end: e.target.value, week: null })}
|
||||
/>
|
||||
</label>
|
||||
<label className="qa-ops-keyword">
|
||||
@@ -518,59 +489,56 @@ export function QAOperations() {
|
||||
maxLength={200}
|
||||
placeholder="检索原始问题"
|
||||
value={draft.keyword}
|
||||
onChange={(event) => setDraft({ ...draft, keyword: event.target.value })}
|
||||
onChange={(e) => setDraft({ ...draft, keyword: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" disabled={loading}>
|
||||
查询
|
||||
</button>
|
||||
</form>
|
||||
<p className="qa-ops-slice-note">
|
||||
部门/区域保留源快照,缺失时按当前通讯录补全;使用统计不是绩效结论。外语翻译与AI评估仍暂缓,空值不默认填“否”。
|
||||
</p>
|
||||
{view === 'records' ? <QAQualityCounts query={query} revision={qualityRevision} /> : null}
|
||||
{view === 'usage' ? (
|
||||
<QAUsage query={query} />
|
||||
) : (
|
||||
<QAOperationsView
|
||||
page={page}
|
||||
status={status}
|
||||
error={error}
|
||||
loading={loading}
|
||||
detail={detail}
|
||||
detailLoading={detailLoading}
|
||||
detailError={detailError}
|
||||
onReloadDetail={() => {
|
||||
if (detail) void select(detail.id)
|
||||
}}
|
||||
onQualitySaved={(fresh) => {
|
||||
if (fresh.id !== detail?.id) return
|
||||
setDetail(fresh)
|
||||
setPage((old) => {
|
||||
if (!old) return old
|
||||
const all = new Set(old.columns)
|
||||
const f = fresh.quality?.effective
|
||||
if (f) {
|
||||
if (f.coverage) all.add('coverage')
|
||||
if (f.correctness) all.add('is_correct')
|
||||
for (const key of ['product_category', 'problem_type', 'root_cause'] as const)
|
||||
if (f[key]) all.add(key)
|
||||
}
|
||||
return {
|
||||
...old,
|
||||
items: old.items.map((item) => (item.id === fresh.id ? fresh : item)),
|
||||
columns: qaColumns.filter((c) => all.has(c.key)).map((c) => c.key),
|
||||
}
|
||||
})
|
||||
setQualityRevision((v) => v + 1)
|
||||
}}
|
||||
onSelect={(id) => void select(id)}
|
||||
onCloseDetail={close}
|
||||
progress={progress}
|
||||
onRetry={() => setRevision((value) => value + 1)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
{view === 'regions' ? (
|
||||
<QARegions />
|
||||
) : view === 'weekly' ? (
|
||||
<QAWeekly query={query} />
|
||||
) : view === 'dashboard' ? (
|
||||
<QADashboard
|
||||
page={page}
|
||||
query={query}
|
||||
loading={loading}
|
||||
error={error}
|
||||
revision={qualityRevision}
|
||||
onRetry={() => {
|
||||
setRevision((v) => v + 1)
|
||||
setQualityRevision((v) => v + 1)
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<QAOperationsView
|
||||
page={page}
|
||||
status={status}
|
||||
error={error}
|
||||
loading={loading}
|
||||
detail={detail}
|
||||
detailLoading={detailLoading}
|
||||
detailError={detailError}
|
||||
onReloadDetail={() => {
|
||||
if (detail) void select(detail.id)
|
||||
}}
|
||||
onQualitySaved={(fresh) => {
|
||||
if (fresh.id !== detail?.id) return
|
||||
setDetail(fresh)
|
||||
setPage((old) =>
|
||||
old ? { ...old, items: old.items.map((item) => (item.id === fresh.id ? fresh : item)) } : old
|
||||
)
|
||||
setQualityRevision((v) => v + 1)
|
||||
}}
|
||||
onSelect={(id) => void select(id)}
|
||||
onCloseDetail={close}
|
||||
progress={progress}
|
||||
onRetry={() => setRevision((v) => v + 1)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -38,7 +38,13 @@ describe('manual quality operations', () => {
|
||||
<QAQualitySummaryView data={parseQualitySummary(summaryFixture)} error="" loading={false} onRefresh={() => {}} />
|
||||
)
|
||||
expect(ok).toContain('完整筛选范围')
|
||||
expect(ok).toContain('AI 评估未接入')
|
||||
expect(ok).not.toContain('AI 评估未接入')
|
||||
expect(ok).not.toContain('读取:')
|
||||
expect(ok).toContain('质量统计')
|
||||
const empty = renderToStaticMarkup(
|
||||
<QAQualitySummaryView data={null} error="" loading={false} onRefresh={() => {}} />
|
||||
)
|
||||
expect(empty).not.toContain('按当前完整时间/关键词范围留档,不按当前页估算。')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -407,7 +407,7 @@ export function QAQualitySummaryView({ data, loading, error, onRefresh }: Summar
|
||||
return (
|
||||
<section className="qa-quality-summary" aria-label="质量数量">
|
||||
<button type="button" disabled={loading} onClick={onRefresh}>
|
||||
{loading ? '正在复检留档…' : '复检留档与质量数量'}
|
||||
{loading ? '正在统计…' : '质量统计'}
|
||||
</button>
|
||||
{error ? (
|
||||
<p role="alert" className="error-banner">
|
||||
@@ -460,12 +460,7 @@ export function QAQualitySummaryView({ data, loading, error, onRefresh }: Summar
|
||||
</p>
|
||||
<p className="qa-ops-muted">统计规则:{data.summary.rates.policy_version}</p>
|
||||
</details>
|
||||
<p className="qa-ops-muted">
|
||||
AI 评估未接入;人工待确认是已复核中的子集,规则命中可与人工结论不同。读取:{stamp(data.as_of)}
|
||||
</p>
|
||||
</>
|
||||
) : !error && !loading ? (
|
||||
<span className="qa-ops-muted">按当前完整时间/关键词范围留档,不按当前页估算。</span>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
|
||||
@@ -51,6 +51,30 @@ const props = {
|
||||
onRemoveMissing: vi.fn(),
|
||||
}
|
||||
describe('region mapping workbench', () => {
|
||||
it('separates multiselect from bulk application and renders hierarchy and editable region names', () => {
|
||||
const custom = {
|
||||
...state,
|
||||
regions: [{ id: 'APAC', name: '国外工业Amercia' }],
|
||||
view: { ...state.view, regions: { APAC: 1 } },
|
||||
}
|
||||
const html = renderToStaticMarkup(<RegionMappingView {...props} state={custom} />)
|
||||
for (const label of [
|
||||
'区域设置',
|
||||
'添加区域',
|
||||
'一级部门',
|
||||
'二级部门',
|
||||
'三级部门',
|
||||
'四级及更深',
|
||||
'批量归属',
|
||||
'全选当前列表',
|
||||
'取消本次勾选',
|
||||
'国外工业Amercia',
|
||||
])
|
||||
expect(html).toContain(label)
|
||||
expect(html).toMatch(/disabled=""[^>]*>批量归属/)
|
||||
expect(html).not.toContain('将 示例公司/')
|
||||
})
|
||||
|
||||
it('shows real synchronization stages without inventing progress and protects dirty drafts', () => {
|
||||
const syncStatus = {
|
||||
configured: true,
|
||||
@@ -80,14 +104,14 @@ describe('region mapping workbench', () => {
|
||||
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] ?? ''
|
||||
const statusRule = css.match(/\.qa-region-table td\.qa-region-basis\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('配置区域归属不等于纳入绩效考核')
|
||||
expect(html).not.toContain('<script>test</script>')
|
||||
expect(html).not.toContain('达标率')
|
||||
expect(html).toMatch(/disabled=""[^>]*>保存归属/)
|
||||
|
||||
+217
-45
@@ -1,11 +1,24 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { changeRegionRule, fetchOrganization, previewOrganization, regionNames, saveOrganization } from './qaOrg'
|
||||
import type { Organization, RegionRule } from './qaOrg'
|
||||
import {
|
||||
changeRegionRule,
|
||||
fetchOrganization,
|
||||
previewOrganization,
|
||||
organizationRegions,
|
||||
parseRegionDefinitions,
|
||||
saveOrganization,
|
||||
} from './qaOrg'
|
||||
import type { Organization, RegionRule, RegionDefinition } from './qaOrg'
|
||||
import './qaRegions.css'
|
||||
import { applyBulkRegionRules, departmentLevels } from './qaRegionSelection'
|
||||
import { completedSyncAction, directorySyncActive, fetchDirectorySync, startDirectorySync } from './qaOrgSync'
|
||||
import type { DirectorySyncStatus } from './qaOrgSync'
|
||||
import { newOperationID } from './operationKey'
|
||||
interface Props {
|
||||
regions?: RegionDefinition[]
|
||||
selectedIDs?: string[]
|
||||
onCatalog?: (regions: RegionDefinition[]) => void
|
||||
onSelect?: (ids: string[]) => void
|
||||
onApply?: () => void
|
||||
syncStatus?: DirectorySyncStatus | null
|
||||
syncError?: string
|
||||
syncSubmitting?: boolean
|
||||
@@ -28,10 +41,35 @@ interface Props {
|
||||
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())) ?? []
|
||||
const [newName, setNewName] = useState(''),
|
||||
[level, setLevel] = useState(''),
|
||||
[catalogError, setCatalogError] = useState('')
|
||||
const display = p.preview ?? p.state,
|
||||
available = p.state?.state === 'ready'
|
||||
const regions = p.regions ?? organizationRegions(p.state),
|
||||
selected = p.selectedIDs ?? []
|
||||
const all = display?.view.departments ?? [],
|
||||
nodes = new Map(all.map((d) => [d.id, d]))
|
||||
const rows = all.map((d) => ({ department: d, levels: departmentLevels(all, d.id, nodes) }))
|
||||
const departments = rows.filter(
|
||||
({ department: d, levels }) =>
|
||||
d.path.toLowerCase().includes(p.search.toLowerCase()) && (!level || levels.length === Number(level))
|
||||
)
|
||||
const maximum = rows.reduce((n, r) => Math.max(n, r.levels.length), 0)
|
||||
const label = (id: string, catalog = regions) => catalog.find((r) => r.id === id)?.name ?? id
|
||||
const choose = (id: string, checked: boolean) =>
|
||||
p.onSelect?.(checked ? [...new Set([...selected, id])] : selected.filter((x) => x !== id))
|
||||
const add = () => {
|
||||
if (!newName.trim()) return
|
||||
const next = [...regions, { id: 'region-' + newOperationID(), name: newName.trim() }]
|
||||
try {
|
||||
p.onCatalog?.(parseRegionDefinitions(next))
|
||||
setNewName('')
|
||||
setCatalogError('')
|
||||
} catch {
|
||||
setCatalogError('区域名称无效,请核对长度、重名或保留名称')
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section className="qa-regions" aria-label="区域归属配置">
|
||||
<div className="qa-region-heading">
|
||||
@@ -85,9 +123,6 @@ export function RegionMappingView(p: Props) {
|
||||
{p.state.revision_id || '尚未保存'}
|
||||
</p>
|
||||
) : null}
|
||||
<p className="qa-ops-muted">
|
||||
父部门包含子部门,子部门单独配置优先。配置区域归属不等于纳入绩效考核;跨区域多部门人员先待核对。
|
||||
</p>
|
||||
{p.error ? (
|
||||
<p role="alert" className="error-banner">
|
||||
{p.error}
|
||||
@@ -97,16 +132,69 @@ export function RegionMappingView(p: Props) {
|
||||
{!p.state ? (
|
||||
<p role="status">{p.busy ? '正在读取通讯录…' : '尚未读取通讯录'}</p>
|
||||
) : !available ? (
|
||||
<p className="qa-ops-empty">尚无完整通讯录快照。先接入已验证的全量同步结果,不能使用按需人员缓存或编造部门。</p>
|
||||
<p className="qa-ops-empty">暂无通讯录,请先同步。</p>
|
||||
) : (
|
||||
<>
|
||||
<section className="qa-region-catalog" aria-label="区域设置">
|
||||
<h4>区域设置</h4>
|
||||
{catalogError ? (
|
||||
<p role="alert" className="error-banner">
|
||||
{catalogError}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="qa-region-names">
|
||||
{regions.map((r) => (
|
||||
<label key={r.id}>
|
||||
区域名称
|
||||
<input
|
||||
aria-label={`区域名称 ${r.id}`}
|
||||
value={r.name}
|
||||
maxLength={100}
|
||||
disabled={p.busy}
|
||||
onChange={(e) =>
|
||||
p.onCatalog?.(regions.map((x) => (x.id === r.id ? { ...x, name: e.target.value } : x)))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
add()
|
||||
}}
|
||||
className="qa-region-add"
|
||||
>
|
||||
<input
|
||||
aria-label="新区域名称"
|
||||
value={newName}
|
||||
maxLength={100}
|
||||
disabled={p.busy}
|
||||
placeholder="输入业务区域名称"
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
disabled={
|
||||
p.busy || !newName.trim() || regions.length >= 100 || regions.some((r) => r.name === newName.trim())
|
||||
}
|
||||
>
|
||||
添加区域
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
<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>
|
||||
))}
|
||||
{regions.length ? (
|
||||
regions.map((r) => (
|
||||
<option key={r.id} value={r.id}>
|
||||
{r.name}
|
||||
</option>
|
||||
))
|
||||
) : (
|
||||
<option value="">请先添加区域</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
@@ -118,6 +206,47 @@ export function RegionMappingView(p: Props) {
|
||||
placeholder="输入部门名称或完整路径"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
部门层级
|
||||
<select aria-label="部门层级" value={level} onChange={(e) => setLevel(e.target.value)}>
|
||||
<option value="">全部层级</option>
|
||||
{Array.from({ length: maximum }, (_, i) => (
|
||||
<option key={i} value={i + 1}>
|
||||
第 {i + 1} 级
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div className="qa-region-bulk">
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label="全选当前列表"
|
||||
disabled={p.busy || !departments.length}
|
||||
checked={departments.length > 0 && departments.every((r) => selected.includes(r.department.id))}
|
||||
onChange={(e) => {
|
||||
const visible = new Set(departments.map((r) => r.department.id))
|
||||
p.onSelect?.(
|
||||
e.target.checked
|
||||
? [...new Set([...selected, ...visible])]
|
||||
: selected.filter((id) => !visible.has(id))
|
||||
)
|
||||
}}
|
||||
/>
|
||||
全选当前列表
|
||||
</label>
|
||||
<span>已勾选 {selected.length} 个部门</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={p.busy || !selected.length || !regions.some((r) => r.id === p.selectedRegion)}
|
||||
onClick={p.onApply}
|
||||
>
|
||||
批量归属
|
||||
</button>
|
||||
<button type="button" disabled={p.busy || !selected.length} onClick={() => p.onSelect?.([])}>
|
||||
取消本次勾选
|
||||
</button>
|
||||
<button type="button" disabled={p.busy || !p.dirty} onClick={p.onPreview}>
|
||||
预览影响
|
||||
</button>
|
||||
@@ -129,18 +258,16 @@ export function RegionMappingView(p: Props) {
|
||||
<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]}
|
||||
{organizationRegions(display).map((r) => (
|
||||
<span key={r.id}>
|
||||
{r.name}:{display.view.regions[r.id]}
|
||||
</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}
|
||||
{p.dirty && !p.preview ? <p className="qa-ops-muted">人数仍为已保存结果;请预览后保存。</p> : null}
|
||||
{display?.view.missing_departments.length ? (
|
||||
<div role="alert" className="qa-ops-warning">
|
||||
部分已配置部门不在当前通讯录中,原规则保留,需核对:
|
||||
@@ -158,43 +285,71 @@ export function RegionMappingView(p: Props) {
|
||||
<table className="qa-region-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>直接配置</th>
|
||||
<th>选择</th>
|
||||
<th>一级部门</th>
|
||||
<th>二级部门</th>
|
||||
<th>三级部门</th>
|
||||
<th>四级及更深</th>
|
||||
<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>
|
||||
))}
|
||||
{departments.map(({ department: d, levels }) => {
|
||||
const direct = p.rules.find((r) => r.department_id === d.id)
|
||||
return (
|
||||
<tr key={d.id} data-department-id={d.id}>
|
||||
<td>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={`选择部门 ${d.path}`}
|
||||
checked={selected.includes(d.id)}
|
||||
disabled={p.busy}
|
||||
onChange={(e) => choose(d.id, e.target.checked)}
|
||||
/>
|
||||
</td>
|
||||
<td>{levels[0] || '—'}</td>
|
||||
<td>{levels[1] || '—'}</td>
|
||||
<td>{levels[2] || '—'}</td>
|
||||
<td>{levels.slice(3).join(' / ') || '—'}</td>
|
||||
<td>{d.path}</td>
|
||||
<td>
|
||||
{direct ? (
|
||||
<>
|
||||
<span>{label(direct.region)}</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`清除直接配置 ${d.path}`}
|
||||
disabled={p.busy}
|
||||
onClick={() => p.onToggle(d.id, false)}
|
||||
>
|
||||
清除
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
'—'
|
||||
)}
|
||||
</td>
|
||||
<td>{d.region ? label(d.region, organizationRegions(display)) : '未归属'}</td>
|
||||
<td className="qa-region-basis">
|
||||
{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)))
|
||||
function signature(rules: RegionRule[], regions: RegionDefinition[]) {
|
||||
return JSON.stringify({ rules: [...rules].sort((a, b) => a.department_id.localeCompare(b.department_id)), regions })
|
||||
}
|
||||
export function QARegions() {
|
||||
const [syncStatus, setSyncStatus] = useState<DirectorySyncStatus | null>(null),
|
||||
@@ -208,7 +363,9 @@ export function QARegions() {
|
||||
const [state, setState] = useState<Organization | null>(null),
|
||||
[preview, setPreview] = useState<Organization | null>(null),
|
||||
[rules, setRules] = useState<RegionRule[]>([])
|
||||
const [region, setRegion] = useState<string>(regionNames[0]),
|
||||
const [regions, setRegions] = useState<RegionDefinition[]>([]),
|
||||
[selected, setSelected] = useState<string[]>([])
|
||||
const [region, setRegion] = useState<string>(''),
|
||||
[search, setSearch] = useState(''),
|
||||
[busy, setBusy] = useState(false),
|
||||
[error, setError] = useState(''),
|
||||
@@ -217,6 +374,11 @@ export function QARegions() {
|
||||
const accept = (value: Organization) => {
|
||||
setState(value)
|
||||
setRules(value.rules)
|
||||
setRegions(organizationRegions(value))
|
||||
setRegion((current) =>
|
||||
organizationRegions(value).some((r) => r.id === current) ? current : (organizationRegions(value)[0]?.id ?? '')
|
||||
)
|
||||
setSelected([])
|
||||
setPreview(null)
|
||||
}
|
||||
const load = async () => {
|
||||
@@ -243,7 +405,7 @@ export function QARegions() {
|
||||
void load()
|
||||
return () => request.current?.abort()
|
||||
}, [])
|
||||
const dirty = Boolean(state && signature(rules) !== signature(state.rules))
|
||||
const dirty = Boolean(state && signature(rules, regions) !== signature(state.rules, organizationRegions(state)))
|
||||
dirtyRef.current = dirty
|
||||
const loadRef = useRef(load)
|
||||
loadRef.current = load
|
||||
@@ -325,8 +487,8 @@ export function QARegions() {
|
||||
setNotice('')
|
||||
try {
|
||||
const value = await (save
|
||||
? saveOrganization(state, rules, controller.signal)
|
||||
: previewOrganization(state, rules, controller.signal))
|
||||
? saveOrganization({ ...state, regions: parseRegionDefinitions(regions) }, rules, controller.signal)
|
||||
: previewOrganization({ ...state, regions: parseRegionDefinitions(regions) }, rules, controller.signal))
|
||||
if (!controller.signal.aborted) {
|
||||
if (save) {
|
||||
const readback = await fetchOrganization(controller.signal)
|
||||
@@ -347,6 +509,16 @@ export function QARegions() {
|
||||
}
|
||||
return (
|
||||
<RegionMappingView
|
||||
regions={regions}
|
||||
selectedIDs={selected}
|
||||
onCatalog={(next) => {
|
||||
setRegions(next)
|
||||
setPreview(null)
|
||||
setNotice('')
|
||||
setError('')
|
||||
}}
|
||||
onSelect={setSelected}
|
||||
onApply={() => edit(applyBulkRegionRules(rules, selected, region))}
|
||||
syncStatus={syncStatus}
|
||||
syncError={syncError}
|
||||
syncSubmitting={syncSubmitting}
|
||||
|
||||
@@ -20,6 +20,16 @@ const usage = parseQAUsage({
|
||||
rows: [{ key: 'unmatched', questions: 2, succeeded: 1, failed: 1, other: 0, users: null, roster_people: null }],
|
||||
})
|
||||
describe('usage statistics evidence', () => {
|
||||
it('renders a custom label without inheriting Object prototype properties', () => {
|
||||
const custom = {
|
||||
...usage,
|
||||
organization: { ...usage.organization, region_names: ['toString'] },
|
||||
rows: usage.rows.map((r) => ({ ...r, key: 'toString' })),
|
||||
}
|
||||
const html = renderToStaticMarkup(<QAUsageView data={custom} loading={false} error="" onRetry={() => {}} />)
|
||||
expect(html).toContain('toString')
|
||||
})
|
||||
|
||||
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('按当前通讯录回看')
|
||||
|
||||
+1
-1
@@ -57,7 +57,7 @@ export function QAUsageView({ data, loading, error, onRetry }: Props) {
|
||||
<tbody>
|
||||
{data.rows.map((row) => (
|
||||
<tr key={row.key}>
|
||||
<td>{usageLabels[row.key]}</td>
|
||||
<td>{usageLabels[row.key] ?? row.key}</td>
|
||||
<td>{row.questions}</td>
|
||||
<td>{row.succeeded}</td>
|
||||
<td>{row.failed}</td>
|
||||
|
||||
@@ -15,8 +15,7 @@ describe('QA week picker', () => {
|
||||
expect(html).toContain('value="40" selected=""')
|
||||
expect(html).toContain('第40周(09-28 到 10-04)')
|
||||
expect(html).toContain('第53周(2026-12-28 到 2027-01-03)')
|
||||
expect(html).toContain('北京时间')
|
||||
expect(html).toContain('周一至周日')
|
||||
expect(html).not.toContain('北京时间 · 周一至周日 · 本周截至当前')
|
||||
})
|
||||
it('preserves custom range mode and does not offer invalid week 53', () => {
|
||||
const html = renderToStaticMarkup(<QAWeekPicker year={2027} week={null} onChange={vi.fn()} />)
|
||||
|
||||
@@ -50,7 +50,6 @@ export function QAWeekPicker({ year, week, onChange, onCurrentWeek }: Props) {
|
||||
<button className="qa-week-current" type="button" onClick={onCurrentWeek}>
|
||||
本周
|
||||
</button>
|
||||
<span className="qa-ops-muted">北京时间 · 周一至周日 · 本周截至当前</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { QAQuery } from './qaOps'
|
||||
import { fetchAllQARecords } from './qaOps'
|
||||
import { fetchQADashboardQuality } from './qaDashboard'
|
||||
import { fetchQAMirrorStatus } from './qaMirror'
|
||||
import { buildQAWeeklyDraft, downloadQAWeekly } from './qaWeekly'
|
||||
import type { QAWeeklyDraft } from './qaWeekly'
|
||||
import { QAAnswerMarkdown } from './QAAnswerMarkdown'
|
||||
export function QAWeekly({ query }: { query: QAQuery | null }) {
|
||||
const [draft, setDraft] = useState<QAWeeklyDraft | null>(null),
|
||||
[loading, setLoading] = useState(false),
|
||||
[error, setError] = useState('')
|
||||
const request = useRef<AbortController | null>(null)
|
||||
useEffect(() => {
|
||||
request.current?.abort()
|
||||
setDraft(null)
|
||||
setError('')
|
||||
setLoading(false)
|
||||
return () => request.current?.abort()
|
||||
}, [query])
|
||||
const generate = async () => {
|
||||
if (!query || loading) return
|
||||
request.current?.abort()
|
||||
const controller = new AbortController()
|
||||
request.current = controller
|
||||
setLoading(true)
|
||||
setDraft(null)
|
||||
setError('')
|
||||
try {
|
||||
const before = await fetchQAMirrorStatus(controller.signal)
|
||||
if (!before.ready || before.blocked) throw Error('本地同步未就绪,暂不能生成周报')
|
||||
const [page, quality] = await Promise.all([
|
||||
fetchAllQARecords(query, controller.signal),
|
||||
fetchQADashboardQuality(query, controller.signal),
|
||||
])
|
||||
const after = await fetchQAMirrorStatus(controller.signal)
|
||||
if (!after.ready || after.blocked || before.revision !== after.revision || page.local_revision !== after.revision)
|
||||
throw Error('本地副本在生成期间已更新,请重新生成')
|
||||
const result = buildQAWeeklyDraft(page, query, quality, new Date().toISOString())
|
||||
if (!controller.signal.aborted) setDraft(result)
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted) setError(e instanceof Error ? e.message : '周报生成失败')
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
}
|
||||
}
|
||||
const suffix = query ? new Date(Date.parse(query.start) + 8 * 60 * 60 * 1000).toISOString().slice(0, 10) : 'draft'
|
||||
return (
|
||||
<section className="qa-weekly" aria-label="周报生成">
|
||||
<header className="qa-weekly-toolbar">
|
||||
<div>
|
||||
<h3>周报生成</h3>
|
||||
{query ? (
|
||||
<span>
|
||||
{new Date(query.start).toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' })} 至{' '}
|
||||
{new Date(Date.parse(query.end) - 1).toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' })}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<button type="button" onClick={() => void generate()} disabled={loading || !query}>
|
||||
{loading ? '正在生成…' : '生成周报草稿'}
|
||||
</button>
|
||||
{draft ? (
|
||||
<>
|
||||
<span className="qa-weekly-badge">草稿 · {draft.questions} 条</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
downloadQAWeekly(draft.markdown, `DobotAI-问答周报-${suffix}.md`, 'text/markdown;charset=utf-8')
|
||||
}
|
||||
>
|
||||
下载 MD
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => downloadQAWeekly(draft.csv, `DobotAI-问题明细-${suffix}.csv`, 'text/csv;charset=utf-8')}
|
||||
>
|
||||
下载明细 CSV
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
</header>
|
||||
{error ? (
|
||||
<p role="alert" className="error-banner">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
{draft ? (
|
||||
<article className="qa-weekly-preview">
|
||||
<QAAnswerMarkdown answer={draft.markdown} />
|
||||
</article>
|
||||
) : (
|
||||
<div className="qa-weekly-empty">{loading ? '正在汇总本地问答…' : '尚未生成周报。'}</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
.qa-dashboard-scroll {
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
flex: 1;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
.qa-dashboard {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
.qa-dashboard-metrics {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
border: 1px solid var(--border-base);
|
||||
background: var(--bg-panel);
|
||||
}
|
||||
.qa-dashboard-metrics > div {
|
||||
padding: 18px 22px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
border-right: 1px solid var(--border-base);
|
||||
}
|
||||
.qa-dashboard-metrics > div:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
.qa-dashboard-metrics span {
|
||||
color: var(--ink-mute);
|
||||
font-size: 12px;
|
||||
}
|
||||
.qa-dashboard-metrics strong {
|
||||
color: var(--ink-strong);
|
||||
font-size: 30px;
|
||||
font-weight: 650;
|
||||
font-variant-numeric: tabular-nums;
|
||||
letter-spacing: -0.04em;
|
||||
}
|
||||
.qa-dashboard-metrics small {
|
||||
font-size: 11px;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.qa-dashboard-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.6fr) minmax(260px, 1fr);
|
||||
gap: 14px;
|
||||
}
|
||||
.qa-chart {
|
||||
min-width: 0;
|
||||
padding: 18px 20px;
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border-base);
|
||||
}
|
||||
.qa-chart-full {
|
||||
grid-column: 1/-1;
|
||||
}
|
||||
.qa-chart h3 {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
margin: 0 0 20px;
|
||||
color: var(--ink-strong);
|
||||
}
|
||||
.qa-chart-bars {
|
||||
display: grid;
|
||||
gap: 13px;
|
||||
}
|
||||
.qa-chart-bar {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(70px, 120px) minmax(0, 1fr) 40px;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
font-size: 12px;
|
||||
}
|
||||
.qa-chart-bar > span {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.qa-chart-bar b {
|
||||
text-align: right;
|
||||
font-weight: 500;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.qa-chart-track {
|
||||
height: 7px;
|
||||
background: var(--bg-canvas, #f1f5f9);
|
||||
overflow: hidden;
|
||||
border-radius: 2px;
|
||||
}
|
||||
.qa-chart-track i {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: #377bc9;
|
||||
border-radius: 2px;
|
||||
}
|
||||
.qa-chart-empty {
|
||||
padding: 28px 0;
|
||||
text-align: center;
|
||||
color: var(--ink-mute);
|
||||
font-size: 12px;
|
||||
}
|
||||
.qa-daily-chart {
|
||||
display: flex;
|
||||
gap: clamp(6px, 1.5vw, 22px);
|
||||
height: 180px;
|
||||
align-items: stretch;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.qa-daily-chart > div {
|
||||
flex: 1;
|
||||
min-width: 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
font-size: 11px;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.qa-daily-chart > div > div {
|
||||
height: 125px;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
border-bottom: 1px solid var(--border-base);
|
||||
}
|
||||
.qa-daily-chart i {
|
||||
display: block;
|
||||
width: 100%;
|
||||
background: #377bc9;
|
||||
border-radius: 2px 2px 0 0;
|
||||
min-height: 0;
|
||||
}
|
||||
.qa-daily-chart b {
|
||||
font-size: 11px;
|
||||
color: var(--ink-strong);
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-weight: 500;
|
||||
}
|
||||
.qa-dashboard-region-table {
|
||||
margin-top: 18px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.qa-dashboard-region-table table {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
}
|
||||
.qa-dashboard-region-table th,
|
||||
.qa-dashboard-region-table td {
|
||||
padding: 8px 10px;
|
||||
text-align: left;
|
||||
white-space: normal;
|
||||
}
|
||||
.qa-monthly-disclosure {
|
||||
margin-top: 14px;
|
||||
border-top: 1px solid var(--border-base);
|
||||
padding: 14px 0;
|
||||
}
|
||||
.qa-monthly-disclosure > summary {
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.qa-monthly-disclosure .qa-monthly {
|
||||
min-height: 400px;
|
||||
max-height: 650px;
|
||||
margin-top: 12px;
|
||||
overflow: auto;
|
||||
}
|
||||
@media (max-width: 900px) {
|
||||
.qa-dashboard-grid {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
.qa-chart-full {
|
||||
grid-column: auto;
|
||||
}
|
||||
.qa-dashboard-metrics > div {
|
||||
padding: 14px;
|
||||
}
|
||||
.qa-dashboard-metrics strong {
|
||||
font-size: 25px;
|
||||
}
|
||||
}
|
||||
@media (max-width: 560px) {
|
||||
.qa-dashboard-metrics {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.qa-dashboard-metrics > div:nth-child(2) {
|
||||
border-right: 0;
|
||||
}
|
||||
.qa-dashboard-metrics > div:nth-child(-n + 2) {
|
||||
border-bottom: 1px solid var(--border-base);
|
||||
}
|
||||
.qa-chart {
|
||||
padding: 16px 12px;
|
||||
}
|
||||
.qa-chart-bar {
|
||||
grid-template-columns: minmax(65px, 100px) minmax(0, 1fr) 30px;
|
||||
}
|
||||
}
|
||||
|
||||
.qa-weekly {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
}
|
||||
.qa-weekly-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
padding: 16px;
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border-base);
|
||||
}
|
||||
.qa-weekly-toolbar > div {
|
||||
margin-right: auto;
|
||||
}
|
||||
.qa-weekly-toolbar h3 {
|
||||
font-size: 15px;
|
||||
margin: 0 0 6px;
|
||||
}
|
||||
.qa-weekly-toolbar span {
|
||||
font-size: 12px;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
.qa-weekly-badge {
|
||||
padding: 4px 7px;
|
||||
border: 1px solid var(--border-base);
|
||||
}
|
||||
.qa-weekly-preview {
|
||||
padding: 20px;
|
||||
background: var(--bg-panel);
|
||||
border: 1px solid var(--border-base);
|
||||
min-width: 0;
|
||||
}
|
||||
.qa-weekly-empty {
|
||||
padding: 50px 20px;
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
color: var(--ink-mute);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { QARecord, QAQuery } from './qaOps'
|
||||
import { getPayload } from './qaOps'
|
||||
import { parseQualitySummary } from './qaQuality'
|
||||
export type QACountPoint = { label: string; count: number }
|
||||
const day = 24 * 60 * 60 * 1000,
|
||||
offset = 8 * 60 * 60 * 1000
|
||||
export function qaDailySeries(items: QARecord[], query: QAQuery): QACountPoint[] {
|
||||
const start = Date.parse(query.start),
|
||||
end = Date.parse(query.end)
|
||||
if (!Number.isFinite(start) || !Number.isFinite(end) || start >= end || end - start > 90 * day)
|
||||
throw Error('统计时间范围无效')
|
||||
const counts = new Map<string, number>()
|
||||
for (let t = Math.floor((start + offset) / day) * day; t <= Math.floor((end - 1 + offset) / day) * day; t += day)
|
||||
counts.set(new Date(t).toISOString().slice(0, 10), 0)
|
||||
for (const item of items) {
|
||||
const stamp = Date.parse(item.asked_at)
|
||||
if (stamp >= start && stamp < end) {
|
||||
const key = new Date(stamp + offset).toISOString().slice(0, 10)
|
||||
counts.set(key, (counts.get(key) || 0) + 1)
|
||||
}
|
||||
}
|
||||
return [...counts].map(([label, count]) => ({ label, count }))
|
||||
}
|
||||
export function qaCategorySeries(items: QARecord[], key: 'product_category' | 'problem_type'): QACountPoint[] {
|
||||
const counts = new Map<string, number>()
|
||||
for (const item of items) {
|
||||
const label =
|
||||
(item.quality?.state === 'stale' ? '' : item.quality?.effective[key] || item[key] || '').trim() || '未分类'
|
||||
counts.set(label, (counts.get(label) || 0) + 1)
|
||||
}
|
||||
return [...counts]
|
||||
.map(([label, count]) => ({ label, count }))
|
||||
.sort((a, b) => b.count - a.count || a.label.localeCompare(b.label, 'zh-CN'))
|
||||
}
|
||||
export async function fetchQADashboardQuality(query: QAQuery, signal?: AbortSignal) {
|
||||
const value = parseQualitySummary(
|
||||
await getPayload('/api/v1/qa-ops/quality/query', signal, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-quality' },
|
||||
body: JSON.stringify({ start: query.start, end: query.end, keyword: query.keyword }),
|
||||
})
|
||||
)
|
||||
if (
|
||||
Date.parse(value.start) !== Date.parse(query.start) ||
|
||||
Date.parse(value.end) !== Date.parse(query.end) ||
|
||||
value.keyword !== query.keyword
|
||||
)
|
||||
throw Error('质量统计与当前查询范围不一致')
|
||||
return value
|
||||
}
|
||||
@@ -2,6 +2,18 @@ import { describe, it, expect, vi } from 'vitest'
|
||||
import { parseQAMonthly, fetchQAMonthly, beijingMonth } from './qaMonthly'
|
||||
import { monthlyFixture } from './qaMonthly.fixture'
|
||||
describe('personal natural-month contracts', () => {
|
||||
it('accepts renamed custom regions only from the shared organization catalog', () => {
|
||||
const custom = {
|
||||
...monthlyFixture,
|
||||
organization: { ...monthlyFixture.organization, region_names: ['国内教育'] },
|
||||
rows: monthlyFixture.rows.map((r, i) => (i === 0 ? { ...r, region: '国内教育' } : r)),
|
||||
}
|
||||
expect(parseQAMonthly(custom).rows[0].region).toBe('国内教育')
|
||||
expect(() =>
|
||||
parseQAMonthly({ ...custom, organization: { ...custom.organization, region_names: ['别的区域'] } })
|
||||
).toThrow()
|
||||
})
|
||||
|
||||
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)
|
||||
|
||||
@@ -60,7 +60,6 @@ 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)
|
||||
@@ -117,7 +116,7 @@ export function parseQAMonthly(value: unknown): MonthlyPeople {
|
||||
keys.has(key) ||
|
||||
name.length > 1000 ||
|
||||
!['matched', 'unassigned', 'cross_region'].includes(state) ||
|
||||
(state === 'matched' && !regions.includes(region)) ||
|
||||
(state === 'matched' && !(organization.region_names ?? []).includes(region)) ||
|
||||
(state !== 'matched' && region !== '')
|
||||
)
|
||||
fail()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { parseQAQuality } from './qaQuality'
|
||||
import { regionNames, parseRegionDefinitions } from './qaOrg'
|
||||
import type { QAQuality } from './qaQuality'
|
||||
export const qaColumns = [
|
||||
{ key: 'question_chinese', label: '中文问题' },
|
||||
@@ -20,6 +21,7 @@ export const qaColumns = [
|
||||
|
||||
export type QAColumn = (typeof qaColumns)[number]['key']
|
||||
export interface QAOrganizationVersion {
|
||||
region_names?: string[]
|
||||
state: 'ready' | 'empty'
|
||||
directory_id: string
|
||||
directory_source: string
|
||||
@@ -40,7 +42,14 @@ export interface QARecordOrganization {
|
||||
export function parseQAOrganizationVersion(value: unknown): QAOrganizationVersion {
|
||||
const v = object(value)
|
||||
if (!['ready', 'empty'].includes(text(v.state)) || v.basis !== 'current_directory') return invalid()
|
||||
const region_names =
|
||||
v.region_names === undefined
|
||||
? [...regionNames]
|
||||
: Array.isArray(v.region_names)
|
||||
? parseRegionDefinitions(v.region_names.map((name) => ({ id: name, name }))).map((r) => r.name)
|
||||
: invalid()
|
||||
const result = {
|
||||
region_names,
|
||||
state: v.state as QAOrganizationVersion['state'],
|
||||
directory_id: text(v.directory_id),
|
||||
directory_source: text(v.directory_source),
|
||||
|
||||
@@ -30,6 +30,35 @@ export const directoryFixture = {
|
||||
},
|
||||
}
|
||||
describe('department region configuration', () => {
|
||||
it('uses configurable stable region IDs rather than a four-name whitelist', () => {
|
||||
const catalog = [
|
||||
{ id: 'education', name: '国内教育' },
|
||||
{ id: 'west', name: '国外工业Amercia' },
|
||||
]
|
||||
const state = parseOrganization({
|
||||
...directoryFixture,
|
||||
regions: catalog,
|
||||
rules: [{ department_id: 'root', region: 'education' }],
|
||||
view: {
|
||||
...directoryFixture.view,
|
||||
departments: [{ ...directoryFixture.view.departments[0], region: 'education', explicit: true }],
|
||||
regions: { education: 1, west: 0 },
|
||||
unassigned_people: 0,
|
||||
},
|
||||
})
|
||||
expect(state.regions).toEqual(catalog)
|
||||
expect(state.rules[0].region).toBe('education')
|
||||
expect(state.view.regions.education).toBe(1)
|
||||
})
|
||||
|
||||
it('rejects undeclared region counts rather than silently dropping them', () => {
|
||||
expect(() =>
|
||||
parseOrganization({
|
||||
...directoryFixture,
|
||||
view: { ...directoryFixture.view, regions: { ...directoryFixture.view.regions, undeclared: 0 } },
|
||||
})
|
||||
).toThrow()
|
||||
})
|
||||
it('parses an honest dated snapshot without exposing employee identities', () => {
|
||||
const state = parseOrganization(directoryFixture)
|
||||
expect(state.directory_source).toBe('weekly_report_snapshot')
|
||||
|
||||
+53
-7
@@ -1,4 +1,45 @@
|
||||
export const regionNames = ['国内工业', 'APAC', 'EMEA', 'America'] as const
|
||||
export interface RegionDefinition {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
export const defaultRegions = (): RegionDefinition[] => regionNames.map((name) => ({ id: name, name }))
|
||||
const reservedRegions = [
|
||||
'unassigned',
|
||||
'cross_region',
|
||||
'unmatched',
|
||||
'identity_conflict',
|
||||
'no_identity',
|
||||
'directory_missing',
|
||||
'__proto__',
|
||||
'constructor',
|
||||
'prototype',
|
||||
]
|
||||
export function parseRegionDefinitions(raw: unknown): RegionDefinition[] {
|
||||
if (!Array.isArray(raw) || raw.length > 100) return invalid()
|
||||
const ids = new Set<string>(),
|
||||
names = new Set<string>()
|
||||
return raw.map((item) => {
|
||||
const r = obj(item),
|
||||
id = str(r.id),
|
||||
name = str(r.name)
|
||||
for (const value of [id, name])
|
||||
if (
|
||||
!value ||
|
||||
value.trim() !== value ||
|
||||
new TextEncoder().encode(value).length > 256 ||
|
||||
/[\x00\r\n]/.test(value) ||
|
||||
reservedRegions.includes(value)
|
||||
)
|
||||
return invalid()
|
||||
if (ids.has(id) || names.has(name)) return invalid()
|
||||
ids.add(id)
|
||||
names.add(name)
|
||||
return { id, name }
|
||||
})
|
||||
}
|
||||
export const organizationRegions = (state: Organization | null): RegionDefinition[] =>
|
||||
state?.regions ?? defaultRegions()
|
||||
export interface RegionRule {
|
||||
department_id: string
|
||||
region: string
|
||||
@@ -13,6 +54,7 @@ export interface DepartmentRegion {
|
||||
inherited_from: string
|
||||
}
|
||||
export interface Organization {
|
||||
regions?: RegionDefinition[]
|
||||
state: 'empty' | 'ready'
|
||||
directory_id: string
|
||||
directory_source: string
|
||||
@@ -49,7 +91,9 @@ export function instant(value: unknown): string | null {
|
||||
export function parseOrganization(value: unknown): Organization {
|
||||
const s = obj(value),
|
||||
v = obj(s.view),
|
||||
regions = obj(v.regions)
|
||||
regions = obj(v.regions),
|
||||
definitions = s.regions === undefined ? defaultRegions() : parseRegionDefinitions(s.regions),
|
||||
regionIDs = definitions.map((r) => r.id)
|
||||
if (
|
||||
(s.state !== 'empty' && s.state !== 'ready') ||
|
||||
!Array.isArray(s.rules) ||
|
||||
@@ -60,13 +104,12 @@ export function parseOrganization(value: unknown): Organization {
|
||||
const rules = s.rules.map((raw) => {
|
||||
const r = obj(raw)
|
||||
const region = str(r.region)
|
||||
if (!regionNames.some((x) => x === region)) return invalid()
|
||||
if (!regionIDs.includes(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()
|
||||
if (typeof d.explicit !== 'boolean' || (d.region !== '' && !regionIDs.includes(String(d.region)))) return invalid()
|
||||
return {
|
||||
id: str(d.id),
|
||||
parent_id: str(d.parent_id),
|
||||
@@ -86,9 +129,12 @@ export function parseOrganization(value: unknown): Organization {
|
||||
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.keys(regions).length !== regionIDs.length || Object.keys(regions).some((id) => !regionIDs.includes(id)))
|
||||
return invalid()
|
||||
const regionCounts = Object.fromEntries(regionIDs.map((r) => [r, count(regions[r])]))
|
||||
if (Object.values(regionCounts).reduce((a, b) => a + b, 0) + unassigned + conflicting !== total) return invalid()
|
||||
const result: Organization = {
|
||||
regions: definitions,
|
||||
state: s.state,
|
||||
directory_id: str(s.directory_id),
|
||||
directory_source: str(s.directory_source),
|
||||
@@ -140,13 +186,13 @@ export const previewOrganization = (state: Organization, rules: RegionRule[], si
|
||||
requestOrganization(
|
||||
'/preview',
|
||||
'POST',
|
||||
{ directory_id: state.directory_id, base_revision: state.revision_id, rules },
|
||||
{ directory_id: state.directory_id, base_revision: state.revision_id, regions: organizationRegions(state), 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 },
|
||||
{ directory_id: state.directory_id, base_revision: state.revision_id, regions: organizationRegions(state), rules },
|
||||
signal
|
||||
)
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { applyBulkRegionRules, departmentLevels } from './qaRegionSelection'
|
||||
import type { DepartmentRegion } from './qaOrg'
|
||||
describe('department multi-selection', () => {
|
||||
it('applies only explicitly selected IDs without deleting child overrides or mutating saved rules', () => {
|
||||
const saved = [
|
||||
{ department_id: 'child', region: 'west' },
|
||||
{ department_id: 'sibling', region: 'education' },
|
||||
]
|
||||
const draft = applyBulkRegionRules(saved, ['parent', 'other', 'parent'], 'education')
|
||||
expect(draft).toEqual([
|
||||
...saved,
|
||||
{ department_id: 'parent', region: 'education' },
|
||||
{ department_id: 'other', region: 'education' },
|
||||
])
|
||||
expect(saved).toHaveLength(2)
|
||||
expect(applyBulkRegionRules(draft, [], 'west')).toEqual(draft)
|
||||
})
|
||||
it('derives every hierarchy level from parent IDs, not slashes in names or a three-level cutoff', () => {
|
||||
const departments = Array.from({ length: 5 }, (_, i) => ({
|
||||
id: String(i),
|
||||
parent_id: i ? String(i - 1) : '',
|
||||
name: `部门/${i}`,
|
||||
path: '',
|
||||
region: '',
|
||||
explicit: false,
|
||||
inherited_from: '',
|
||||
})) as DepartmentRegion[]
|
||||
expect(departmentLevels(departments, '4')).toEqual(departments.map((d) => d.name))
|
||||
expect(() =>
|
||||
departmentLevels([...departments, { ...departments[0], id: 'cycle', parent_id: 'cycle' }], 'cycle')
|
||||
).toThrow()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { DepartmentRegion, RegionRule } from './qaOrg'
|
||||
export function applyBulkRegionRules(rules: RegionRule[], ids: string[], region: string): RegionRule[] {
|
||||
const selected = new Set(ids)
|
||||
if (!selected.size) return [...rules]
|
||||
if (!region) throw new Error('请先选择区域')
|
||||
return [
|
||||
...rules.filter((r) => !selected.has(r.department_id)),
|
||||
...Array.from(selected, (department_id) => ({ department_id, region })),
|
||||
]
|
||||
}
|
||||
export function departmentLevels(
|
||||
departments: DepartmentRegion[],
|
||||
id: string,
|
||||
nodes = new Map(departments.map((d) => [d.id, d]))
|
||||
): string[] {
|
||||
const seen = new Set<string>(),
|
||||
names: string[] = []
|
||||
let current = id
|
||||
while (current) {
|
||||
const node = nodes.get(current)
|
||||
if (!node || seen.has(current) || names.length > 100) throw new Error('通讯录部门层级无效,请重新同步')
|
||||
seen.add(current)
|
||||
names.unshift(node.name)
|
||||
current = node.parent_id
|
||||
}
|
||||
return names
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { it, expect } from 'vitest'
|
||||
import { parseQAUsage } from './qaUsage'
|
||||
it('keeps custom region usage instead of rejecting or silently dropping its counts', () => {
|
||||
const wire = {
|
||||
organization: {
|
||||
state: 'ready',
|
||||
directory_id: 'd',
|
||||
directory_source: 'weekly_report_live',
|
||||
synced_at: '2026-10-17T00:00:00Z',
|
||||
revision_id: 'r',
|
||||
basis: 'current_directory',
|
||||
region_names: ['国内教育'],
|
||||
},
|
||||
as_of: '2026-10-17T01:00:00Z',
|
||||
start: '2026-10-16T00:00:00Z',
|
||||
end: '2026-10-17T00:00:00Z',
|
||||
keyword: '',
|
||||
questions: 2,
|
||||
identified_users: 1,
|
||||
rows: [{ key: '国内教育', questions: 2, succeeded: 1, failed: 1, other: 0, users: 1, roster_people: 2 }],
|
||||
}
|
||||
expect(parseQAUsage(wire).rows[0].key).toBe('国内教育')
|
||||
expect(() => parseQAUsage({ ...wire, organization: { ...wire.organization, region_names: ['其他'] } })).toThrow()
|
||||
})
|
||||
+73
-3
@@ -59,6 +59,8 @@
|
||||
border-collapse: collapse;
|
||||
text-align: left;
|
||||
font-size: 13px;
|
||||
table-layout: fixed;
|
||||
min-width: 960px;
|
||||
}
|
||||
.qa-region-table th,
|
||||
.qa-region-table td {
|
||||
@@ -74,11 +76,10 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
.qa-region-table td:nth-child(2) {
|
||||
min-width: 240px;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.qa-region-table td:nth-child(3),
|
||||
.qa-region-table td:nth-child(4) {
|
||||
.qa-region-table td.qa-region-basis {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.qa-region-table input[type='checkbox'] {
|
||||
@@ -111,6 +112,75 @@
|
||||
outline: 2px solid #1765c1;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.qa-region-catalog {
|
||||
border-bottom: 1px solid var(--line, #d8e1eb);
|
||||
padding-bottom: 14px;
|
||||
min-width: 0;
|
||||
}
|
||||
.qa-region-catalog h4 {
|
||||
margin: 0 0 10px;
|
||||
}
|
||||
.qa-region-names {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
.qa-region-names label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
color: var(--text-muted, #5e6d82);
|
||||
font-size: 12px;
|
||||
min-width: 0;
|
||||
}
|
||||
.qa-region-catalog input {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
box-sizing: border-box;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--line, #d8e1eb);
|
||||
border-radius: 5px;
|
||||
background: var(--panel, #fff);
|
||||
color: inherit;
|
||||
}
|
||||
.qa-region-add,
|
||||
.qa-region-bulk {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 12px;
|
||||
align-items: center;
|
||||
}
|
||||
.qa-region-add {
|
||||
margin-top: 10px;
|
||||
}
|
||||
.qa-region-add input {
|
||||
max-width: 320px;
|
||||
}
|
||||
.qa-region-bulk label {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
.qa-region-tree-scroll {
|
||||
max-height: 60vh;
|
||||
}
|
||||
.qa-region-table th {
|
||||
white-space: normal;
|
||||
}
|
||||
.qa-region-table th:first-child {
|
||||
width: 36px;
|
||||
}
|
||||
.qa-region-table th:nth-child(6) {
|
||||
width: 23%;
|
||||
}
|
||||
.qa-region-table th:last-child {
|
||||
width: 65px;
|
||||
}
|
||||
.qa-region-table td button {
|
||||
padding: 3px 6px;
|
||||
font-size: 11px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
@media (max-width: 700px) {
|
||||
.qa-region-filters {
|
||||
align-items: stretch;
|
||||
|
||||
+15
-5
@@ -30,7 +30,7 @@ const stamp = (v: unknown) => {
|
||||
const s = text(v)
|
||||
return !Number.isNaN(Date.parse(s)) ? s : bad()
|
||||
}
|
||||
export const usageLabels: Record<string, string> = {
|
||||
export const usageLabels: Record<string, string> = Object.assign(Object.create(null), {
|
||||
国内工业: '国内工业',
|
||||
APAC: 'APAC',
|
||||
EMEA: 'EMEA',
|
||||
@@ -41,14 +41,24 @@ export const usageLabels: Record<string, string> = {
|
||||
identity_conflict: '身份冲突',
|
||||
no_identity: '身份信息缺失',
|
||||
directory_missing: '尚无完整通讯录',
|
||||
}
|
||||
})
|
||||
export function parseQAUsage(value: unknown): QAUsage {
|
||||
const v = obj(value)
|
||||
const v = obj(value),
|
||||
organization = parseQAOrganizationVersion(v.organization)
|
||||
const allowed = new Set([
|
||||
...(organization.region_names ?? []),
|
||||
'unassigned',
|
||||
'cross_region',
|
||||
'unmatched',
|
||||
'identity_conflict',
|
||||
'no_identity',
|
||||
'directory_missing',
|
||||
])
|
||||
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()
|
||||
if (!allowed.has(key)) return bad()
|
||||
const row = {
|
||||
key,
|
||||
questions: count(r.questions),
|
||||
@@ -62,7 +72,7 @@ export function parseQAUsage(value: unknown): QAUsage {
|
||||
return row
|
||||
})
|
||||
const result = {
|
||||
organization: parseQAOrganizationVersion(v.organization),
|
||||
organization,
|
||||
as_of: stamp(v.as_of),
|
||||
start: stamp(v.start),
|
||||
end: stamp(v.end),
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { createElement } from 'react'
|
||||
import { QAAnswerMarkdown } from './QAAnswerMarkdown'
|
||||
import { buildQAWeeklyDraft } from './qaWeekly'
|
||||
import type { QARecordPage, QAQuery } from './qaOps'
|
||||
import type { QualitySummary } from './qaQuality'
|
||||
const query: QAQuery = { start: '2026-10-11T16:00:00Z', end: '2026-10-18T10:00:00Z', keyword: '', cursor: '' }
|
||||
const page = {
|
||||
items: [
|
||||
{
|
||||
id: 'fixture',
|
||||
status: 'succeeded',
|
||||
time_source: 'request_message.created_at',
|
||||
asker: 'fixture person',
|
||||
trigger_person: '',
|
||||
department: '',
|
||||
region: '',
|
||||
references: [],
|
||||
media: [],
|
||||
source_coverage: { verdict: '', reason_code: '', evaluator_version: '' },
|
||||
question: '=HYPERLINK("https://example.invalid")',
|
||||
answer: '暂无已发布',
|
||||
asked_at: '2026-10-14T00:00:00Z',
|
||||
coverage: {
|
||||
verdict: 'uncovered',
|
||||
state: 'checked',
|
||||
rule_version: 'governance-answer-substring-v1',
|
||||
matched_text: '暂无已发布',
|
||||
},
|
||||
feedback: { asker_value: '', up: 0, down: 0 },
|
||||
},
|
||||
],
|
||||
columns: [],
|
||||
total: 1,
|
||||
has_more: false,
|
||||
next_cursor: '',
|
||||
as_of: query.end,
|
||||
local_revision: 1,
|
||||
} as QARecordPage
|
||||
const quality = {
|
||||
start: query.start,
|
||||
end: query.end,
|
||||
keyword: '',
|
||||
as_of: query.end,
|
||||
scope: 'whole_filter',
|
||||
ai_state: 'not_configured',
|
||||
summary: {
|
||||
total: 1,
|
||||
reviewed: 0,
|
||||
unreviewed: 1,
|
||||
stale: 0,
|
||||
pending_confirmation: 0,
|
||||
rule_uncovered: 1,
|
||||
rates: {
|
||||
policy_version: 'quality-rates-human-first-v1',
|
||||
coverage: { numerator: 0, denominator: 1, percent: 0 },
|
||||
correctness: { numerator: 0, denominator: 0, percent: null },
|
||||
breakdown: {
|
||||
covered: 0,
|
||||
uncovered: 1,
|
||||
partial: 0,
|
||||
pending: 0,
|
||||
unassessed: 0,
|
||||
excluded: 0,
|
||||
stale: 0,
|
||||
covered_correct: 0,
|
||||
covered_incorrect: 0,
|
||||
covered_pending: 0,
|
||||
covered_unassessed: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
} as QualitySummary
|
||||
describe('weekly draft export', () => {
|
||||
it('builds preview and downloadable evidence from the same complete query without invented correctness', () => {
|
||||
const d = buildQAWeeklyDraft(page, query, quality, '2026-10-18T10:00:00Z')
|
||||
expect(d.questions).toBe(1)
|
||||
expect(d.revision).toBe(1)
|
||||
expect(d.markdown).toContain('周报(草稿)')
|
||||
expect(d.markdown).toContain('正确率:—')
|
||||
expect(renderToStaticMarkup(createElement(QAAnswerMarkdown, { answer: d.markdown }))).toContain('<table')
|
||||
expect(d.csv.charCodeAt(0)).toBe(0xfeff)
|
||||
expect(d.markdown.split(String.fromCharCode(10)).length).toBeGreaterThan(10)
|
||||
expect(d.csv.split(String.fromCharCode(13, 10)).length).toBe(2)
|
||||
expect(d.csv).toContain('原始问题')
|
||||
expect(d.csv).toContain("'=HYPERLINK")
|
||||
})
|
||||
it('escapes source question Markdown and line breaks rather than injecting a report link or row', () => {
|
||||
const input = {
|
||||
...page,
|
||||
items: page.items.map((r) => ({
|
||||
...r,
|
||||
question: '中文 [链接](https://example.invalid) **危险**' + String.fromCharCode(10) + '第二行',
|
||||
})),
|
||||
}
|
||||
const d = buildQAWeeklyDraft(input, query, quality, query.end)
|
||||
const html = renderToStaticMarkup(createElement(QAAnswerMarkdown, { answer: d.markdown }))
|
||||
expect(html).not.toContain('>链接</a>')
|
||||
expect(html).not.toContain('<strong>危险</strong>')
|
||||
expect(d.markdown).not.toContain(String.fromCharCode(10) + '第二行')
|
||||
})
|
||||
it('refuses incomplete ranges or statistics from another scope', () => {
|
||||
expect(() => buildQAWeeklyDraft({ ...page, has_more: true }, query, quality, query.end)).toThrow()
|
||||
expect(() => buildQAWeeklyDraft(page, query, { ...quality, keyword: 'other' }, query.end)).toThrow()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { QARecordPage, QAQuery } from './qaOps'
|
||||
import { qaCellValue, qaColumns } from './qaOps'
|
||||
import type { QualitySummary, QualityRate } from './qaQuality'
|
||||
import { qaDailySeries, qaCategorySeries } from './qaDashboard'
|
||||
export interface QAWeeklyDraft {
|
||||
markdown: string
|
||||
csv: string
|
||||
questions: number
|
||||
revision: number
|
||||
generatedAt: string
|
||||
}
|
||||
const stamp = (v: string) => new Date(v).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
|
||||
const rate = (v: QualityRate) =>
|
||||
v.percent === null ? '—' : `${v.percent.toFixed(1)}%(${v.numerator} / ${v.denominator})`
|
||||
const cell = (v: unknown) =>
|
||||
String(v ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/[\`*_[\]|]/g, '\\$&')
|
||||
.replace(/[\r\n]+/g, ' ')
|
||||
function csvCell(value: unknown) {
|
||||
const v = String(value ?? '')
|
||||
const safe = /^[\t\r\n]|^\s*[=+\-@]/.test(v) ? "'" + v : v
|
||||
return '"' + safe.replace(/"/g, '""') + '"'
|
||||
}
|
||||
export function buildQAWeeklyDraft(
|
||||
page: QARecordPage,
|
||||
query: QAQuery,
|
||||
quality: QualitySummary,
|
||||
generatedAt: string
|
||||
): QAWeeklyDraft {
|
||||
if (
|
||||
page.has_more ||
|
||||
page.items.length !== page.total ||
|
||||
new Set(page.items.map((i) => i.id)).size !== page.total ||
|
||||
quality.summary.total !== page.total ||
|
||||
Date.parse(quality.start) !== Date.parse(query.start) ||
|
||||
Date.parse(quality.end) !== Date.parse(query.end) ||
|
||||
quality.keyword !== query.keyword ||
|
||||
!Number.isFinite(Date.parse(generatedAt))
|
||||
)
|
||||
throw Error('周报范围或完整性不一致,请重新生成')
|
||||
const groups: Record<string, number> = {
|
||||
covered: 0,
|
||||
uncovered: 0,
|
||||
partial: 0,
|
||||
pending: 0,
|
||||
unassessed: 0,
|
||||
excluded: 0,
|
||||
stale: 0,
|
||||
}
|
||||
for (const r of page.items) {
|
||||
const state =
|
||||
r.quality?.state === 'stale' ? 'stale' : r.quality?.effective.coverage || r.coverage?.verdict || 'unassessed'
|
||||
const key = state === 'unknown' ? 'unassessed' : state
|
||||
if (!(key in groups)) throw Error('周报存在未知覆盖状态')
|
||||
groups[key]++
|
||||
}
|
||||
for (const [key, count] of Object.entries(groups))
|
||||
if (quality.summary.rates.breakdown[key as keyof typeof quality.summary.rates.breakdown] !== count)
|
||||
throw Error('复核结果在生成期间发生变化,请重新生成')
|
||||
const s = quality.summary
|
||||
const daily = qaDailySeries(page.items, query)
|
||||
.map((p) => `| ${p.label} | ${p.count} |`)
|
||||
.join('\n')
|
||||
const products = qaCategorySeries(page.items, 'product_category')
|
||||
.map((p) => `| ${cell(p.label)} | ${p.count} |`)
|
||||
.join('\n')
|
||||
const gaps = page.items.filter(
|
||||
(r) => (r.quality?.effective.coverage || r.coverage?.verdict) === 'uncovered' && r.quality?.state !== 'stale'
|
||||
)
|
||||
const md =
|
||||
[
|
||||
'# DobotAI 问答运营周报(草稿)',
|
||||
`统计范围:${stamp(query.start)} 至 ${stamp(query.end)}(结束不含)`,
|
||||
query.keyword ? `关键词:${cell(query.keyword)}` : '',
|
||||
`生成:${stamp(generatedAt)}`,
|
||||
`本地数据版本:${page.local_revision ?? '—'}`,
|
||||
'## 问答概览',
|
||||
`- 问题总量:${page.total}`,
|
||||
`- 知识覆盖率:${rate(s.rates.coverage)}`,
|
||||
`- 回答正确率:${rate(s.rates.correctness)}`,
|
||||
`- 已人工复核:${s.reviewed}`,
|
||||
`- 待重新核对:${s.stale}`,
|
||||
`- 人工待确认:${s.pending_confirmation}`,
|
||||
'## 质量分布',
|
||||
'| 已覆盖 | 未覆盖 | 部分覆盖 | 待确认 | 未评估 | 不计入 | 待重新核对 |',
|
||||
'| --- | --- | --- | --- | --- | --- | --- |',
|
||||
`| ${groups.covered} | ${groups.uncovered} | ${groups.partial} | ${groups.pending} | ${groups.unassessed} | ${groups.excluded} | ${groups.stale} |`,
|
||||
'## 每日提问',
|
||||
'| 日期 | 问题量 |',
|
||||
'| --- | ---: |',
|
||||
daily,
|
||||
'## 产品分类',
|
||||
'| 分类 | 问题量 |',
|
||||
'| --- | ---: |',
|
||||
products,
|
||||
'## 未覆盖问题',
|
||||
gaps.length ? '| 提问时间 | 问题 | 产品分类 |' : '当前无有效未覆盖记录',
|
||||
gaps.length ? '| --- | --- | --- |' : '',
|
||||
...gaps.map(
|
||||
(r) =>
|
||||
`| ${stamp(r.asked_at)} | ${cell(qaCellValue(r, 'question_chinese') || r.question)} | ${cell(r.quality?.effective.product_category || r.product_category || '—')} |`
|
||||
),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n\n') + '\n'
|
||||
const csv =
|
||||
'\ufeff' +
|
||||
[
|
||||
qaColumns.map((c) => csvCell(c.label)).join(','),
|
||||
...page.items.map((row) => qaColumns.map((c) => csvCell(qaCellValue(row, c.key))).join(',')),
|
||||
].join('\r\n')
|
||||
return {
|
||||
markdown: md.replace(/\|\n\n\|/g, '|\n|'),
|
||||
csv,
|
||||
questions: page.total,
|
||||
revision: page.local_revision ?? 0,
|
||||
generatedAt,
|
||||
}
|
||||
}
|
||||
export function downloadQAWeekly(content: string, filename: string, type: string) {
|
||||
const url = URL.createObjectURL(new Blob([content], { type }))
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = filename
|
||||
document.body.append(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
}
|
||||
Reference in New Issue
Block a user