Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4a2b2b7d84 | |||
| a9870beade |
@@ -76,6 +76,29 @@
|
||||
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯,
|
||||
> 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。
|
||||
|
||||
## 开发快照 snapshot/v0.1.38 - 2026-10-19
|
||||
|
||||
### Added
|
||||
|
||||
- 区域统计新增可展开部门树:部门、访问人数、访问比例、访问次数、最近提问时间五列,访问人数附当前通讯录总人数;整支含自身和全部子部门,按稳定人员身份去重,调岗依当前归属,零分母显示“—”,收起不重算数字。
|
||||
- 统计仅读独立治理总表中的提问事件,支持累计与北京时间自然月;单并发后台聚合、请求合并和60秒缓存,目录或区域配置版本变化立即隔离旧缓存;加载/失败不伪装零数据,不占用代理转发链路。
|
||||
|
||||
### Changed
|
||||
|
||||
- 原“区域配置”入口改为“区域统计”,区域设置保留自定义区域新增/改名、未使用区域删除、部门映射预览与双版本锁保存;勾选父部门联选全部后代,取消子支时解除祖先整支选中,防止未选部门被父级新规则误覆盖。
|
||||
- 统计与区域设置共享选择;搜索、按区域查看及展开收起只改变可见行,既有总表、原始问答、历史趋势、模型任务与生产数据不修改。
|
||||
|
||||
## 开发快照 snapshot/v0.1.37 - 2026-10-19
|
||||
|
||||
### Added
|
||||
|
||||
- 统计看板的覆盖率、正确率趋势支持独立持久保存的用户历史报表值,按北京时间ISO自然周展示、精确到两位小数并注明来源;和系统冻结使用分开的曲线,不伪造记录数、分子分母或冻结时间。
|
||||
|
||||
### Changed
|
||||
|
||||
- 历史汇总只影响两个趋势图,不覆盖当前周质量或原始问答;关键词筛选不挪用无明细的历史汇总,所选截止后的数据不提前展示,缺失周留空。页面和完整PNG共用相同绘图数据。
|
||||
- 增加治理侧迁移57:历史统计独立表保留来源指纹与导入审计,禁止原位覆盖/删除,存在历史数据时拒绝破坏性down;普通来源同步不能覆盖该表,不修改DobotAI生产或既有冻结证据。
|
||||
|
||||
## 开发快照 snapshot/v0.1.36 - 2026-10-19
|
||||
|
||||
### Added
|
||||
|
||||
+103
-1
@@ -44,6 +44,66 @@
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"/api/v1/qa-ops/departments/statistics": {
|
||||
"post": {
|
||||
"operationId": "qaDepartmentStatistics",
|
||||
"summary": "部门树访问统计,当前通讯录整支人员去重",
|
||||
"description": "仅独立治理总表,不读取生产或更改原问答;后台单聚合并发,响应202或60秒缓存结果。当前目录和区域配置版本加入缓存键;父行包含自身及全部后代,人员按当前稳定身份去重,调岗归当前部门;零分母比例为null,最近提问时间来自真实事件。访问指已入总表的提问事件,不含未记录的网页浏览。管理员同源只读POST,操作头qa-department-statistics。",
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"period"
|
||||
],
|
||||
"properties": {
|
||||
"period": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"all",
|
||||
"month"
|
||||
]
|
||||
},
|
||||
"month": {
|
||||
"type": "string",
|
||||
"pattern": "^[0-9]{4}-[0-9]{2}$"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录"
|
||||
},
|
||||
"403": {
|
||||
"description": "仅管理员同源读取"
|
||||
},
|
||||
"409": {
|
||||
"description": "质量输入指纹变化,拒绝混合数据"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"503": {
|
||||
"description": "本地副本或一致性投影不可用,不返回伪零"
|
||||
},
|
||||
"202": {
|
||||
"description": "后台聚合中;同条件合并单次执行,请按Retry-After轮询,不返回虚构零数据"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/qa-ops/ai/settings": {"get": {"operationId": "getQAAISettings", "tags": ["QA operations"], "summary": "读取独立模型配置的安全状态,不返回密钥", "description": "管理员会话限定、固定治理租户、禁止共享缓存;不修改DobotAI源数据库。", "responses": {"200": {"description": "成功;返回实际持久化状态,不将进度100%当成全成功", "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"data": {"$ref": "#/components/schemas/QAAISafeSettings"}}, "required": ["data"]}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员;写操作要求同源与明确意图"}, "409": {"description": "版本、范围或操作收据冲突,未覆盖现有结论"}, "422": {"description": "供应商明确拒绝或结构不合格,不伪造结果"}, "500": {"$ref": "#/components/responses/InternalError"}, "503": {"description": "存储、密钥或执行配置不可用;不返回伪零"}}}, "post": {"operationId": "saveQAAISettings", "tags": ["QA operations"], "summary": "验证并加密保存独立模型配置;不启动历史或自动任务", "description": "管理员会话限定、固定治理租户、禁止共享缓存;不修改DobotAI源数据库。", "responses": {"200": {"description": "成功;返回实际持久化状态,不将进度100%当成全成功", "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"data": {"$ref": "#/components/schemas/QAAISafeSettings"}}, "required": ["data"]}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员;写操作要求同源与明确意图"}, "409": {"description": "版本、范围或操作收据冲突,未覆盖现有结论"}, "422": {"description": "供应商明确拒绝或结构不合格,不伪造结果"}, "500": {"$ref": "#/components/responses/InternalError"}, "503": {"description": "存储、密钥或执行配置不可用;不返回伪零"}}, "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"const": "qa-ai"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/QAAISaveSettings"}}}}}},
|
||||
"/api/v1/qa-ops/ai/settings/test": {"post": {"operationId": "testQAAISettings", "tags": ["QA operations"], "summary": "发送最小非公司数据真实模型探测;不保存配置", "description": "管理员会话限定、固定治理租户、禁止共享缓存;不修改DobotAI源数据库。", "responses": {"200": {"description": "成功;返回实际持久化状态,不将进度100%当成全成功", "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"data": {"$ref": "#/components/schemas/QAAISafeSettings"}}, "required": ["data"]}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员;写操作要求同源与明确意图"}, "409": {"description": "版本、范围或操作收据冲突,未覆盖现有结论"}, "422": {"description": "供应商明确拒绝或结构不合格,不伪造结果"}, "500": {"$ref": "#/components/responses/InternalError"}, "503": {"description": "存储、密钥或执行配置不可用;不返回伪零"}}, "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"const": "qa-ai"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/QAAISaveSettings"}}}}}},
|
||||
"/api/v1/qa-ops/ai/automation": {"post": {"operationId": "setQAAIAutomation", "tags": ["QA operations"], "summary": "按任务启停增量;首次排除历史,关闭停止新增与未开始任务", "description": "管理员会话限定、固定治理租户、禁止共享缓存;不修改DobotAI源数据库。", "responses": {"200": {"description": "成功;返回实际持久化状态,不将进度100%当成全成功", "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"data": {"$ref": "#/components/schemas/QAAISafeSettings"}}, "required": ["data"]}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员;写操作要求同源与明确意图"}, "409": {"description": "版本、范围或操作收据冲突,未覆盖现有结论"}, "422": {"description": "供应商明确拒绝或结构不合格,不伪造结果"}, "500": {"$ref": "#/components/responses/InternalError"}, "503": {"description": "存储、密钥或执行配置不可用;不返回伪零"}}, "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"const": "qa-ai"}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"kind": {"type": "string", "enum": ["evaluation", "translation"]}, "enabled": {"type": "boolean"}}, "required": ["kind", "enabled"]}}}}}},
|
||||
@@ -56,7 +116,7 @@
|
||||
"get": {"tags":["QA operations"],"operationId":"getQAOrganizationSync","summary":"管理员读取通讯录同步执行器状态及最近任务的安全汇总,不返回人员名单或运行配置","responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"状态存储不可用,不伪装为空记录"}}},
|
||||
"post": {"tags":["QA operations"],"operationId":"startQAOrganizationSync","summary":"管理员同源发起持久化通讯录同步;重复请求重放同一任务,进行中任务合并;失败保留现有快照","parameters":[{"$ref":"#/components/parameters/IdempotencyKey"},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-organization"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false}}}},"responses":{"202":{"$ref":"#/components/responses/OperationEnvelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员同源操作"},"409":{"description":"操作标识与原请求冲突"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"同步未接线、执行器离线或入队失败;未创建新任务"}}}
|
||||
},
|
||||
"/api/v1/qa-ops/dashboard": {"post":{"operationId":"readQAOperationsDashboard","tags":["QA operations"],"summary":"管理员只读正式总表一致性看板:累计、所选周、新增/有效质量/类别及截止月区域统计;历史质量仅真实冻结快照,缺失留空","description":"同一只读可重复读事务读取独立正式总表有效字段、质量及组织版本。不访问源端,不冻结或写入指标;区域分母为当前配置通讯录去重人数而非在职/绩效名单。冻结记录按保存的原始标量分子分母及问题文字支持字面关键词筛选,不用当前评估回填历史。","parameters":[{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-dashboard"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["start","end"],"properties":{"start":{"type":"string","format":"date-time"},"end":{"type":"string","format":"date-time"},"keyword":{"type":"string","maxLength":200}}}}}},"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员同源读取"},"409":{"description":"质量输入指纹变化,拒绝混合数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"本地副本或一致性投影不可用,不返回伪零"}}}},
|
||||
"/api/v1/qa-ops/dashboard": {"post":{"operationId":"readQAOperationsDashboard","tags":["QA operations"],"summary":"管理员只读正式总表一致性看板:累计、所选周、新增/有效质量/类别及截止月区域统计;历史趋势区分用户提供百分比与真实冻结快照,缺失留空","description":"同一只读可重复读事务读取独立正式总表有效字段、质量及组织版本。不访问源端,不冻结或写入指标;区域分母为当前配置通讯录去重人数而非在职/绩效名单。冻结记录按保存的原始标量分子分母及问题文字支持字面关键词筛选,不用当前评估回填历史。reported_weeks 独立返回用户提供的历史百分比(QAReportedHistoricalRate),没有分子分母或冻结时间;只含所选截止前已结束周,关键词非空时为空,原冻结记录与当前指标保持不变。","parameters":[{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-dashboard"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["start","end"],"properties":{"start":{"type":"string","format":"date-time"},"end":{"type":"string","format":"date-time"},"keyword":{"type":"string","maxLength":200}}}}}},"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员同源读取"},"409":{"description":"质量输入指纹变化,拒绝混合数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"本地副本或一致性投影不可用,不返回伪零"}}}},
|
||||
"/api/v1/qa-ops/organization": {
|
||||
"get": {
|
||||
"tags": ["QA operations"],
|
||||
@@ -4392,6 +4452,48 @@
|
||||
}
|
||||
},
|
||||
"schemas": {
|
||||
"QAReportedHistoricalRate": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"week",
|
||||
"week_start",
|
||||
"week_end",
|
||||
"coverage_percent",
|
||||
"correctness_percent",
|
||||
"source"
|
||||
],
|
||||
"properties": {
|
||||
"week": {
|
||||
"type": "string",
|
||||
"pattern": "^[0-9]{4}WK[0-9]{2}$"
|
||||
},
|
||||
"week_start": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"week_end": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"coverage_percent": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 100,
|
||||
"multipleOf": 0.01
|
||||
},
|
||||
"correctness_percent": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 100,
|
||||
"multipleOf": 0.01
|
||||
},
|
||||
"source": {
|
||||
"const": "user_provided_history"
|
||||
}
|
||||
},
|
||||
"description": "用户提供的历史报表百分比,不含也不推导分子、分母、记录数或冻结时点;不按现行规则重算,不用于关键词统计。"
|
||||
},
|
||||
"QAAISafeSettings": {"type": "object", "additionalProperties": false, "properties": {"revision": {"type": "integer", "minimum": 0}, "base_url": {"type": "string", "maxLength": 500, "description": "管理员配置的模型API地址,禁止地址内凭据、query或fragment"}, "model": {"type": "string", "maxLength": 200}, "key_configured": {"type": "boolean"}, "verification": {"enum": ["not_configured", "verified", "unverified", "rejected"]}, "checked_at": {"type": ["string", "null"], "format": "date-time"}, "automatic_evaluation": {"type": "boolean"}, "automatic_translation": {"type": "boolean"}, "storage_ready": {"type": "boolean"}}, "required": ["revision", "base_url", "model", "key_configured", "verification", "checked_at", "automatic_evaluation", "automatic_translation", "storage_ready"]},
|
||||
"QAAISaveSettings": {"type": "object", "additionalProperties": false, "properties": {"base_revision": {"type": "integer", "minimum": 0}, "base_url": {"type": "string", "maxLength": 500, "description": "管理员配置的模型API地址,禁止地址内凭据、query或fragment"}, "model": {"type": "string", "maxLength": 200}, "key_action": {"enum": ["keep", "replace", "clear"]}, "api_key": {"type": "string", "writeOnly": true, "maxLength": 4096, "description": "仅replace携带;keep/clear不可携带;HTTPS或本机回环传输;响应不返回"}}, "required": ["base_revision", "base_url", "model", "key_action"]},
|
||||
"QAAIBatch": {"type": "object", "additionalProperties": false, "properties": {"id": {"type": "string"}, "kind": {"type": "string", "enum": ["evaluation", "translation"]}, "state": {"enum": ["active", "paused"]}, "total": {"type": "integer", "minimum": 0}, "succeeded": {"type": "integer", "minimum": 0}, "failed": {"type": "integer", "minimum": 0}, "skipped": {"type": "integer", "minimum": 0}, "running": {"type": "integer", "minimum": 0}, "queued": {"type": "integer", "minimum": 0}, "retry": {"type": "integer", "minimum": 0}, "paused": {"type": "integer", "minimum": 0}, "created_at": {"type": "string", "format": "date-time"}}, "required": ["id", "kind", "state", "total", "succeeded", "failed", "skipped", "running", "queued", "retry", "paused", "created_at"]},
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type departmentStatisticsReader interface {
|
||||
ReadDepartmentStatistics(context.Context, qaopsmirror.DepartmentStatisticsQuery, time.Time) (qaopsmirror.DepartmentStatisticsResult, error)
|
||||
}
|
||||
|
||||
func qaDepartmentStatistics(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-department-statistics") {
|
||||
return
|
||||
}
|
||||
var q qaopsmirror.DepartmentStatisticsQuery
|
||||
if r.URL.RawQuery != "" || decodeQualityJSON(w, r, &q, "period") != nil {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
now := c.Now()
|
||||
if _, _, e := q.Bounds(now); e != nil {
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
reader, ok := c.QAOps.(departmentStatisticsReader)
|
||||
if !ok || c.QAOpsTenantKey == "" {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
data, e := reader.ReadDepartmentStatistics(r.Context(), q, now)
|
||||
if e != nil {
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
status := http.StatusOK
|
||||
if data.State == "pending" {
|
||||
status = http.StatusAccepted
|
||||
w.Header().Set("Retry-After", "1")
|
||||
}
|
||||
writeJSON(w, status, map[string]any{"data": data})
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type departmentStatisticsFixture struct {
|
||||
masterFixtureReader
|
||||
reads int
|
||||
}
|
||||
|
||||
func (f *departmentStatisticsFixture) ReadDepartmentStatistics(context.Context, qaopsmirror.DepartmentStatisticsQuery, time.Time) (qaopsmirror.DepartmentStatisticsResult, error) {
|
||||
f.reads++
|
||||
return qaopsmirror.DepartmentStatisticsResult{State: "pending", RetryAfter: 1}, nil
|
||||
}
|
||||
func TestDepartmentStatisticsRouteIsAsynchronousStrictAndAdminOnly(t *testing.T) {
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["dept-fixture-admin"] = "usr-boss"
|
||||
auth.sessions["dept-fixture-viewer"] = "usr-eye"
|
||||
reader := &departmentStatisticsFixture{}
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: reader, QAOpsTenantKey: "fixture-tenant", Now: func() time.Time { return time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC) }})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
body, token, intent, site string
|
||||
want int
|
||||
}{
|
||||
{`{"period":"all"}`, "dept-fixture-admin", "qa-department-statistics", "", 202},
|
||||
{`{"period":"month","month":"2026-10"}`, "dept-fixture-admin", "qa-department-statistics", "same-origin", 202},
|
||||
{`{"period":"all"}`, "", "qa-department-statistics", "", 401},
|
||||
{`{"period":"all"}`, "dept-fixture-viewer", "qa-department-statistics", "", 403},
|
||||
{`{"period":"all"}`, "dept-fixture-admin", "", "", 403},
|
||||
{`{"period":"all"}`, "dept-fixture-admin", "qa-department-statistics", "cross-site", 403},
|
||||
{`{"period":"all","tenant":"other"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
|
||||
{`{"period":"all","period":"all"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
|
||||
{`null`, "dept-fixture-admin", "qa-department-statistics", "", 400},
|
||||
{`{"period":"month","month":"2027-01"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
|
||||
{`{"period":"all","month":"2026-10"}`, "dept-fixture-admin", "qa-department-statistics", "", 400},
|
||||
} {
|
||||
r := httptest.NewRequest("POST", "/api/v1/qa-ops/departments/statistics", strings.NewReader(c.body))
|
||||
if c.token != "" {
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: c.token})
|
||||
}
|
||||
if c.intent != "" {
|
||||
r.Header.Set("X-Governance-Action", c.intent)
|
||||
}
|
||||
if c.site != "" {
|
||||
r.Header.Set("Sec-Fetch-Site", c.site)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != c.want {
|
||||
t.Fatalf("department statistics got %d want %d", w.Code, c.want)
|
||||
}
|
||||
if w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("employee department stats became publicly cacheable")
|
||||
}
|
||||
}
|
||||
if reader.reads != 2 {
|
||||
t.Fatal("malformed or unauthorized request reached aggregation", reader.reads)
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
|
||||
func masterNoStore(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/api/v1/qa-ops/master/") {
|
||||
if strings.HasPrefix(r.URL.Path, "/api/v1/qa-ops/master/") || strings.HasPrefix(r.URL.Path, "/api/v1/qa-ops/departments/") {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Pragma", "no-cache")
|
||||
}
|
||||
|
||||
@@ -181,6 +181,7 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
registerQAAIRoutes(mux, config)
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/departments/statistics", func(w http.ResponseWriter, r *http.Request) { qaDepartmentStatistics(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/dashboard", func(w http.ResponseWriter, r *http.Request) { qaOperationsDashboard(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/quality/query", func(w http.ResponseWriter, r *http.Request) { qaQualityQuery(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/records/{id}/reviews", func(w http.ResponseWriter, r *http.Request) { qaQualityReview(w, r, config) })
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (SELECT 1 FROM qa_ops_reported_weekly_rates) THEN
|
||||
RAISE EXCEPTION 'cannot discard imported historical rates during rollback' USING ERRCODE='55000';
|
||||
END IF;
|
||||
END $$;
|
||||
DROP TABLE qa_ops_reported_weekly_rates;
|
||||
DROP FUNCTION qa_ops_reported_history_immutable();
|
||||
@@ -0,0 +1,21 @@
|
||||
-- Percent-only historical reports stay separate from computed/frozen evidence.
|
||||
CREATE TABLE qa_ops_reported_weekly_rates (
|
||||
tenant_key TEXT NOT NULL CHECK (tenant_key<>'' AND length(tenant_key)<=128),
|
||||
week_key TEXT NOT NULL CHECK (week_key ~ '^[0-9]{4}WK[0-9]{2}$'),
|
||||
week_start TIMESTAMPTZ NOT NULL,
|
||||
week_end TIMESTAMPTZ NOT NULL,
|
||||
coverage_bp INTEGER NOT NULL CHECK (coverage_bp BETWEEN 0 AND 10000),
|
||||
correctness_bp INTEGER NOT NULL CHECK (correctness_bp BETWEEN 0 AND 10000),
|
||||
source_sha256 TEXT NOT NULL CHECK (source_sha256 ~ '^[a-f0-9]{64}$'),
|
||||
imported_by TEXT NOT NULL CHECK (btrim(imported_by)<>''),
|
||||
imported_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||
PRIMARY KEY (tenant_key,week_key),
|
||||
UNIQUE (tenant_key,week_start),
|
||||
CHECK (week_end=week_start+interval '168 hours'),
|
||||
CHECK (extract(isodow FROM week_start AT TIME ZONE 'Asia/Shanghai')=1),
|
||||
CHECK ((week_start AT TIME ZONE 'Asia/Shanghai')::time=time '00:00:00'),
|
||||
CHECK (week_key=to_char(week_start AT TIME ZONE 'Asia/Shanghai','IYYY"WK"IW'))
|
||||
);
|
||||
CREATE FUNCTION qa_ops_reported_history_immutable() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN RAISE EXCEPTION 'reported historical rates are immutable; keep the original source' USING ERRCODE='55000'; END $$;
|
||||
CREATE TRIGGER qa_reported_history_immutable BEFORE UPDATE OR DELETE ON qa_ops_reported_weekly_rates FOR EACH ROW EXECUTE FUNCTION qa_ops_reported_history_immutable();
|
||||
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 56 {
|
||||
t.Fatalf("migration count = %d, want 56", len(migrations))
|
||||
if len(migrations) != 57 {
|
||||
t.Fatalf("migration count = %d, want 57", 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])
|
||||
|
||||
@@ -14,6 +14,15 @@ type DashboardDaily struct {
|
||||
Date string `json:"date"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
type DashboardReported struct {
|
||||
Week string `json:"week"`
|
||||
WeekStart time.Time `json:"week_start"`
|
||||
WeekEnd time.Time `json:"week_end"`
|
||||
CoveragePercent float64 `json:"coverage_percent"`
|
||||
CorrectnessPercent float64 `json:"correctness_percent"`
|
||||
Source string `json:"source"`
|
||||
}
|
||||
|
||||
type DashboardFrozen struct {
|
||||
WeekStart time.Time `json:"week_start"`
|
||||
WeekEnd time.Time `json:"week_end"`
|
||||
@@ -49,6 +58,7 @@ type Dashboard struct {
|
||||
Daily []DashboardDaily `json:"daily"`
|
||||
Regions []DashboardRegion `json:"regions"`
|
||||
FrozenWeeks []DashboardFrozen `json:"frozen_weeks"`
|
||||
ReportedWeeks []DashboardReported `json:"reported_weeks"`
|
||||
}
|
||||
|
||||
var dashboardLocation = time.FixedZone("Asia/Shanghai", 8*60*60)
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Supplied aggregates have neither row-level evidence nor a keyword denominator.
|
||||
func (s *Store) readReportedDashboard(ctx context.Context, tx pgx.Tx, keyword string, end time.Time) ([]DashboardReported, error) {
|
||||
out := []DashboardReported{}
|
||||
if keyword != "" {
|
||||
return out, nil
|
||||
}
|
||||
rows, err := tx.Query(ctx, `SELECT week_key,week_start,week_end,coverage_bp,correctness_bp FROM qa_ops_reported_weekly_rates WHERE tenant_key=$1 AND week_end<=$2 ORDER BY week_start`, s.tenant, end)
|
||||
if err != nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var p DashboardReported
|
||||
var coverage, correctness int
|
||||
if rows.Scan(&p.Week, &p.WeekStart, &p.WeekEnd, &coverage, &correctness) != nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
p.CoveragePercent = float64(coverage) / 100
|
||||
p.CorrectnessPercent = float64(correctness) / 100
|
||||
p.Source = "user_provided_history"
|
||||
out = append(out, p)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestReportedHistoryIsIndependentExactScopedAndImmutable(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
s := NewStore(p, "fixture-reported-history")
|
||||
insert := `INSERT INTO qa_ops_reported_weekly_rates(tenant_key,week_key,week_start,week_end,coverage_bp,correctness_bp,source_sha256,imported_by) VALUES($1,'2026WK40','2026-09-28T00:00:00+08:00','2026-10-05T00:00:00+08:00',5723,9234,$2,'fixture-admin')`
|
||||
if _, err := p.Exec(ctx, insert, s.tenant, strings.Repeat("a", 64)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start, _ := time.Parse(time.RFC3339, "2026-10-05T00:00:00+08:00")
|
||||
end := start.AddDate(0, 0, 7)
|
||||
read := func(tenant, keyword string, until time.Time) map[string]any {
|
||||
t.Helper()
|
||||
data, err := NewStore(p, tenant).ReadMasterDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: tenant, Start: until.AddDate(0, 0, -7), End: until}, Keyword: keyword})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ := json.Marshal(data)
|
||||
var wire map[string]any
|
||||
if json.Unmarshal(raw, &wire) != nil {
|
||||
t.Fatal("bad dashboard JSON")
|
||||
}
|
||||
return wire
|
||||
}
|
||||
data := read(s.tenant, "", end)
|
||||
history, ok := data["reported_weeks"].([]any)
|
||||
if !ok || len(history) != 1 {
|
||||
t.Fatalf("reported percent-only history was not exposed independently: present=%v", ok)
|
||||
}
|
||||
row := history[0].(map[string]any)
|
||||
if row["coverage_percent"] != 57.23 || row["correctness_percent"] != 92.34 || row["source"] != "user_provided_history" || row["week"] != "2026WK40" {
|
||||
t.Fatal("reported precision or provenance lost")
|
||||
}
|
||||
for _, forbidden := range []string{"numerator", "denominator", "records", "frozen_at"} {
|
||||
if _, exists := row[forbidden]; exists {
|
||||
t.Fatal("invented historical evidence", forbidden)
|
||||
}
|
||||
}
|
||||
if len(data["frozen_weeks"].([]any)) != 0 {
|
||||
t.Fatal("historical input manufactured frozen evidence")
|
||||
}
|
||||
for _, wire := range []map[string]any{read(s.tenant, "needle", end), read("fixture-other-tenant", "", end), read(s.tenant, "", start.Add(-time.Hour))} {
|
||||
if value, ok := wire["reported_weeks"].([]any); !ok || len(value) != 0 {
|
||||
t.Fatal("history leaked across keyword, tenant or closing cutoff")
|
||||
}
|
||||
}
|
||||
for _, query := range []string{`UPDATE qa_ops_reported_weekly_rates SET coverage_bp=123 WHERE tenant_key=$1`, `DELETE FROM qa_ops_reported_weekly_rates WHERE tenant_key=$1`} {
|
||||
tx, e := p.Begin(ctx)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_, e = tx.Exec(ctx, query, s.tenant)
|
||||
_ = tx.Rollback(ctx)
|
||||
var db *pgconn.PgError
|
||||
if !errors.As(e, &db) || db.Code != "55000" {
|
||||
t.Fatal("reported history could be overwritten or deleted")
|
||||
}
|
||||
}
|
||||
e := pg.RollbackLatestMigration(ctx, p)
|
||||
var failure *pgconn.PgError
|
||||
if !errors.As(e, &failure) || failure.Code != "55000" {
|
||||
t.Fatal("down did not explicitly protect historical data", e)
|
||||
}
|
||||
}
|
||||
@@ -256,6 +256,10 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
|
||||
return out, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
}
|
||||
out.ReportedWeeks, e = s.readReportedDashboard(ctx, tx, q.Keyword, q.Window.End)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type DepartmentStatisticsQuery struct {
|
||||
Period string `json:"period"`
|
||||
Month string `json:"month,omitempty"`
|
||||
}
|
||||
type DepartmentStatisticsSnapshot struct {
|
||||
Regions []qaopsorg.RegionDefinition `json:"regions"`
|
||||
qaopsorg.DepartmentStatistics
|
||||
Organization dobotaiops.OrganizationVersion `json:"organization"`
|
||||
Period string `json:"period"`
|
||||
Month string `json:"month"`
|
||||
Start *time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
type DepartmentStatisticsResult struct {
|
||||
CacheKey string `json:"cache_key"`
|
||||
State string `json:"state"`
|
||||
CacheHit bool `json:"cache_hit"`
|
||||
RetryAfter int `json:"retry_after"`
|
||||
Snapshot *DepartmentStatisticsSnapshot `json:"snapshot"`
|
||||
}
|
||||
type departmentStatisticsEntry struct {
|
||||
snapshot *DepartmentStatisticsSnapshot
|
||||
err error
|
||||
done bool
|
||||
expires time.Time
|
||||
}
|
||||
type departmentStatisticsCache struct {
|
||||
mu sync.Mutex
|
||||
entries map[string]*departmentStatisticsEntry
|
||||
slots chan struct{}
|
||||
}
|
||||
|
||||
func (c *departmentStatisticsCache) get(key string, now time.Time, load func(context.Context) (DepartmentStatisticsSnapshot, error)) (DepartmentStatisticsResult, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.entries == nil {
|
||||
c.entries = map[string]*departmentStatisticsEntry{}
|
||||
c.slots = make(chan struct{}, 1)
|
||||
}
|
||||
if entry := c.entries[key]; entry != nil && (!entry.done || now.Before(entry.expires)) {
|
||||
if entry.err != nil {
|
||||
return DepartmentStatisticsResult{}, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if entry.done {
|
||||
return DepartmentStatisticsResult{State: "ready", CacheKey: key, CacheHit: true, Snapshot: entry.snapshot}, nil
|
||||
}
|
||||
return DepartmentStatisticsResult{State: "pending", CacheKey: key, RetryAfter: 1}, nil
|
||||
}
|
||||
for k, v := range c.entries {
|
||||
if v.done && !now.Before(v.expires) {
|
||||
delete(c.entries, k)
|
||||
}
|
||||
}
|
||||
if len(c.entries) >= 32 {
|
||||
return DepartmentStatisticsResult{}, dobotaiops.ErrUnavailable
|
||||
}
|
||||
entry := &departmentStatisticsEntry{}
|
||||
c.entries[key] = entry
|
||||
go func() {
|
||||
started := time.Now()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
var data DepartmentStatisticsSnapshot
|
||||
var err error
|
||||
select {
|
||||
case c.slots <- struct{}{}:
|
||||
data, err = load(ctx)
|
||||
<-c.slots
|
||||
case <-ctx.Done():
|
||||
err = ctx.Err()
|
||||
}
|
||||
finished := now.Add(time.Since(started))
|
||||
data.GeneratedAt = finished
|
||||
data.ExpiresAt = finished.Add(time.Minute)
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
entry.done = true
|
||||
entry.err = err
|
||||
entry.expires = data.ExpiresAt
|
||||
if err != nil {
|
||||
entry.expires = finished.Add(5 * time.Second)
|
||||
} else {
|
||||
entry.snapshot = &data
|
||||
}
|
||||
}()
|
||||
return DepartmentStatisticsResult{State: "pending", CacheKey: key, RetryAfter: 1}, nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDepartmentStatisticsCacheIsBackgroundSingleFlightAndExpires(t *testing.T) {
|
||||
cache := &departmentStatisticsCache{}
|
||||
started := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
var calls atomic.Int64
|
||||
now := time.Now()
|
||||
load := func(ctx context.Context) (DepartmentStatisticsSnapshot, error) {
|
||||
if calls.Add(1) == 1 {
|
||||
close(started)
|
||||
}
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
return DepartmentStatisticsSnapshot{}, ctx.Err()
|
||||
}
|
||||
return DepartmentStatisticsSnapshot{Period: "all"}, nil
|
||||
}
|
||||
begin := time.Now()
|
||||
r, e := cache.get("tenant/directory-v1/revision-v1/all", now, load)
|
||||
if e != nil || r.State != "pending" || time.Since(begin) > 100*time.Millisecond {
|
||||
t.Fatal("first view performed/blocked aggregation instead of scheduling it", e, r.State)
|
||||
}
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("background aggregator did not run")
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 32; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
r, e := cache.get("tenant/directory-v1/revision-v1/all", now, load)
|
||||
if e != nil || r.State != "pending" {
|
||||
t.Error("concurrent read did not join background work")
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if calls.Load() != 1 {
|
||||
t.Fatal("identical requests spawned duplicate aggregation")
|
||||
}
|
||||
close(release)
|
||||
for deadline := time.Now().Add(time.Second); ; {
|
||||
r, e = cache.get("tenant/directory-v1/revision-v1/all", now, load)
|
||||
if r.State == "ready" {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("background result never published")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if e != nil || !r.CacheHit || r.Snapshot == nil || calls.Load() != 1 {
|
||||
t.Fatal("result cache was not reused")
|
||||
}
|
||||
r, e = cache.get("tenant/directory-v1/revision-v1/all", now.Add(61*time.Second), load)
|
||||
if e != nil || r.State != "pending" {
|
||||
t.Fatal("expired result was served as fresh")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDepartmentStatisticsReadsMasterAndInvalidatesCurrentDirectory(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
s := NewStore(p, "fixture-department-statistics")
|
||||
reader, ok := any(s).(interface {
|
||||
ReadDepartmentStatistics(context.Context, DepartmentStatisticsQuery, time.Time) (DepartmentStatisticsResult, error)
|
||||
})
|
||||
if !ok {
|
||||
t.Fatal("master-backed asynchronous department statistics reader is missing")
|
||||
}
|
||||
ctx := context.Background()
|
||||
org := qaopsorg.NewStore(p, s.tenant)
|
||||
directory := qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "root", Name: "Fixture Root"}, {ID: "child", ParentID: "root", Name: "Fixture Child"}, {ID: "other", ParentID: "root", Name: "Fixture Other"}, {ID: "empty", ParentID: "root", Name: "Fixture Empty"}}, People: []qaopsorg.Person{{ID: "person", UnionID: "union-person", DepartmentIDs: []string{"root", "child"}}, {ID: "second", DepartmentIDs: []string{"other"}}}}
|
||||
state, e := org.ReplaceDirectory(ctx, qaopsorg.Import{Source: "weekly_report_snapshot", SyncedAt: time.Now(), Complete: true, Directory: directory})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for i, identity := range []map[string]string{{"staff_id": "person"}, {"union_id": "union-person"}, {"staff_id": "second"}} {
|
||||
id := []string{"one", "two", "three"}[i]
|
||||
at := "2026-10-05T01:00:00+08:00"
|
||||
wire := map[string]any{"id": id, "asked_at": at, "question": "Fixture question " + id, "answer": "Fixture nonbusiness answer", "status": "succeeded", "asker": "Fixture display", "trigger_person": "", "department": "Former department must not decide current attribution", "references": []any{}, "media": []any{}}
|
||||
raw, _ := json.Marshal(wire)
|
||||
actor, _ := json.Marshal(identity)
|
||||
_, e = p.Exec(ctx, `INSERT INTO qa_ops_master_records(tenant_key,id,event_key,origin,asked_at,question,status,identity,quality_hash,payload)VALUES($1,$2,repeat('a',64),'dobotai_2_0',$3,'fixture','succeeded',$4,repeat('b',64),$5)`, s.tenant, id, at, string(actor), string(raw))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
now := time.Now()
|
||||
query := DepartmentStatisticsQuery{Period: "all"}
|
||||
wait := func() DepartmentStatisticsResult {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for {
|
||||
r, e := reader.ReadDepartmentStatistics(ctx, query, now)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if r.State == "ready" {
|
||||
return r
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("statistics did not finish in the background")
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
cctx, cancel := context.WithCancel(ctx)
|
||||
first, e := reader.ReadDepartmentStatistics(cctx, query, now)
|
||||
cancel()
|
||||
if e != nil || first.State != "pending" {
|
||||
t.Fatal("first request must enqueue background aggregation", e)
|
||||
}
|
||||
ready := wait()
|
||||
if ready.Snapshot.TotalVisits != 3 || ready.Snapshot.TotalPeople != 2 || ready.Snapshot.Organization.DirectoryID != state.DirectoryID {
|
||||
t.Fatal("statistics used mirror-only records or wrong roster")
|
||||
}
|
||||
rows := map[string]qaopsorg.DepartmentStatistic{}
|
||||
for _, r := range ready.Snapshot.Rows {
|
||||
rows[r.ID] = r
|
||||
}
|
||||
if rows["root"].Visitors != 2 || rows["root"].Visits != 3 || rows["child"].Visitors != 1 || rows["child"].Visits != 2 || rows["empty"].Ratio != nil {
|
||||
t.Fatal("subtree/alias/empty-denominator contract lost")
|
||||
}
|
||||
again, e := reader.ReadDepartmentStatistics(ctx, query, now.Add(time.Second))
|
||||
if e != nil || !again.CacheHit || again.Snapshot.GeneratedAt != ready.Snapshot.GeneratedAt {
|
||||
t.Fatal("same condition was recomputed within 60 seconds")
|
||||
}
|
||||
directory.People[0].DepartmentIDs = []string{"other"}
|
||||
state, e = org.ReplaceDirectory(ctx, qaopsorg.Import{Source: "weekly_report_snapshot", SyncedAt: time.Now(), Complete: true, Directory: directory})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
moved := wait()
|
||||
if moved.CacheKey == ready.CacheKey || moved.Snapshot.Organization.DirectoryID != state.DirectoryID {
|
||||
t.Fatal("directory changes did not invalidate cache")
|
||||
}
|
||||
for _, r := range moved.Snapshot.Rows {
|
||||
if r.ID == "child" && (r.TotalPeople != 0 || r.Visitors != 0 || r.Ratio != nil) {
|
||||
t.Fatal("transferred person remained in former department")
|
||||
}
|
||||
}
|
||||
_, e = org.SaveRules(ctx, qaopsorg.SaveRequest{DirectoryID: state.DirectoryID, BaseRevision: state.RevisionID, Rules: []qaopsorg.Rule{{DepartmentID: "other", Region: "APAC"}}}, "fixture-admin")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
updated := wait()
|
||||
if updated.CacheKey == moved.CacheKey {
|
||||
t.Fatal("saved regional configuration was hidden behind stale cached results")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (q DepartmentStatisticsQuery) Bounds(now time.Time) (*time.Time, time.Time, error) {
|
||||
if q.Period == "all" && q.Month == "" {
|
||||
return nil, now, nil
|
||||
}
|
||||
if q.Period != "month" {
|
||||
return nil, time.Time{}, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
zone := time.FixedZone("Asia/Shanghai", 8*3600)
|
||||
start, err := time.ParseInLocation("2006-01", q.Month, zone)
|
||||
if err != nil || start.Year() < 2000 || start.After(now) {
|
||||
return nil, time.Time{}, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
end := start.AddDate(0, 1, 0)
|
||||
if end.After(now) {
|
||||
end = now
|
||||
}
|
||||
return &start, end, nil
|
||||
}
|
||||
func (s *Store) ReadDepartmentStatistics(ctx context.Context, q DepartmentStatisticsQuery, now time.Time) (DepartmentStatisticsResult, error) {
|
||||
if !s.valid() {
|
||||
return DepartmentStatisticsResult{}, dobotaiops.ErrUnavailable
|
||||
}
|
||||
start, end, err := q.Bounds(now)
|
||||
if err != nil {
|
||||
return DepartmentStatisticsResult{}, err
|
||||
}
|
||||
var directory, revision string
|
||||
err = s.pool.QueryRow(ctx, `SELECT directory_id,COALESCE(revision_id,'')FROM qa_ops_organization_state WHERE tenant_key=$1`, s.tenant).Scan(&directory, &revision)
|
||||
if err != nil || directory == "" {
|
||||
return DepartmentStatisticsResult{}, dobotaiops.ErrUnavailable
|
||||
}
|
||||
raw, _ := json.Marshal([]string{s.tenant, directory, revision, q.Period, q.Month})
|
||||
digest := sha256.Sum256(raw)
|
||||
key := hex.EncodeToString(digest[:])
|
||||
return s.departmentStats.get(key, now, func(background context.Context) (DepartmentStatisticsSnapshot, error) {
|
||||
return s.loadDepartmentStatistics(background, q, start, end, directory, revision)
|
||||
})
|
||||
}
|
||||
func (s *Store) loadDepartmentStatistics(ctx context.Context, q DepartmentStatisticsQuery, start *time.Time, end time.Time, directory, revision string) (DepartmentStatisticsSnapshot, error) {
|
||||
out := DepartmentStatisticsSnapshot{Period: q.Period, Month: q.Month, Start: start, End: end}
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||
if err != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
if _, err = tx.Exec(ctx, `SET LOCAL statement_timeout='15s'`); err != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
p, err := qaopsorg.NewStore(s.pool, s.tenant).GetAttributionInTx(ctx, tx)
|
||||
if err != nil || p.Metadata.State != "ready" || p.Metadata.DirectoryID != directory || p.Metadata.RevisionID != revision {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
out.Regions = p.Metadata.RegionDefinitions()
|
||||
out.Organization = dobotaiops.OrganizationVersion{State: p.Metadata.State, DirectoryID: p.Metadata.DirectoryID, DirectorySource: p.Metadata.DirectorySource, SyncedAt: p.Metadata.DirectorySyncedAt, RevisionID: p.Metadata.RevisionID, Basis: "current_directory", RegionNames: p.Metadata.RegionLabels()}
|
||||
rows, err := tx.Query(ctx, `SELECT identity::text,COALESCE(payload->>'asker',''),COALESCE(NULLIF(local_fields->>'trigger_person',''),payload->>'trigger_person',''),count(*),max(asked_at),min(asked_at) FROM qa_ops_master_records WHERE tenant_key=$1 AND($2::timestamptz IS NULL OR asked_at>=$2)AND asked_at<$3 GROUP BY identity,COALESCE(payload->>'asker',''),COALESCE(NULLIF(local_fields->>'trigger_person',''),payload->>'trigger_person','') LIMIT 100001`, s.tenant, start, end)
|
||||
if err != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
activity := []qaopsorg.DepartmentActivity{}
|
||||
var earliest *time.Time
|
||||
for rows.Next() {
|
||||
var a qaopsorg.DepartmentActivity
|
||||
var raw string
|
||||
var identity dobotaiops.ActorIdentity
|
||||
var first time.Time
|
||||
if rows.Scan(&raw, &a.Asker, &a.Trigger, &a.Visits, &a.LastAskedAt, &first) != nil || json.Unmarshal([]byte(raw), &identity) != nil {
|
||||
rows.Close()
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
a.StaffID = identity.StaffID
|
||||
a.UnionID = identity.UnionID
|
||||
activity = append(activity, a)
|
||||
if earliest == nil || first.Before(*earliest) {
|
||||
at := first
|
||||
earliest = &at
|
||||
}
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil || len(activity) > 100000 {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
out.DepartmentStatistics, err = qaopsorg.AggregateDepartmentStatistics(p, activity)
|
||||
if err != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if q.Period == "all" {
|
||||
out.Start = earliest
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -17,10 +17,11 @@ const Interval = 5 * time.Minute
|
||||
const localBaseSQL = `WITH records AS (SELECT id,asked_at,question,status,identity,quality_hash,payload FROM qa_ops_mirror_records WHERE tenant_key=$1)`
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
tenant string
|
||||
mu sync.RWMutex
|
||||
safety dobotaiops.SourceSafety
|
||||
pool *pgxpool.Pool
|
||||
tenant string
|
||||
mu sync.RWMutex
|
||||
safety dobotaiops.SourceSafety
|
||||
departmentStats departmentStatisticsCache
|
||||
}
|
||||
|
||||
func NewStore(pool *pgxpool.Pool, tenant string) *Store { return &Store{pool: pool, tenant: tenant} }
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package qaopsorg
|
||||
|
||||
import "time"
|
||||
|
||||
type DepartmentActivity struct {
|
||||
StaffID, UnionID, Asker, Trigger string
|
||||
Visits int64
|
||||
LastAskedAt time.Time
|
||||
}
|
||||
type DepartmentStatistic struct {
|
||||
ID string `json:"id"`
|
||||
ParentID string `json:"parent_id"`
|
||||
Name string `json:"name"`
|
||||
Region string `json:"region"`
|
||||
Visitors int `json:"visitors"`
|
||||
TotalPeople int `json:"total_people"`
|
||||
Ratio *float64 `json:"ratio"`
|
||||
Visits int64 `json:"visits"`
|
||||
LastAskedAt *time.Time `json:"last_asked_at"`
|
||||
}
|
||||
type DepartmentStatistics struct {
|
||||
Rows []DepartmentStatistic `json:"rows"`
|
||||
TotalVisits int64 `json:"total_visits"`
|
||||
UnmappedVisits int64 `json:"unmapped_visits"`
|
||||
TotalPeople int `json:"total_people"`
|
||||
}
|
||||
|
||||
func AggregateDepartmentStatistics(p *Attribution, activity []DepartmentActivity) (DepartmentStatistics, error) {
|
||||
out := DepartmentStatistics{Rows: []DepartmentStatistic{}}
|
||||
if p == nil || p.Metadata.State != "ready" {
|
||||
return out, ErrUnavailable
|
||||
}
|
||||
indices := map[string]int{}
|
||||
nodes := map[string]DepartmentView{}
|
||||
visitors := map[string]map[string]bool{}
|
||||
for _, d := range p.Metadata.View.Departments {
|
||||
indices[d.ID] = len(out.Rows)
|
||||
nodes[d.ID] = d
|
||||
visitors[d.ID] = map[string]bool{}
|
||||
out.Rows = append(out.Rows, DepartmentStatistic{ID: d.ID, ParentID: d.ParentID, Name: d.Name, Region: d.Region})
|
||||
}
|
||||
branches := map[string][]string{}
|
||||
for _, person := range p.Members() {
|
||||
seen := map[string]bool{}
|
||||
for _, id := range person.DepartmentIDs {
|
||||
for id != "" && !seen[id] {
|
||||
node, ok := nodes[id]
|
||||
if !ok {
|
||||
return out, ErrUnavailable
|
||||
}
|
||||
seen[id] = true
|
||||
id = node.ParentID
|
||||
}
|
||||
}
|
||||
for id := range seen {
|
||||
out.Rows[indices[id]].TotalPeople++
|
||||
branches[person.PersonID] = append(branches[person.PersonID], id)
|
||||
}
|
||||
out.TotalPeople++
|
||||
}
|
||||
for _, a := range activity {
|
||||
if a.Visits <= 0 || a.LastAskedAt.IsZero() {
|
||||
return out, ErrInvalid
|
||||
}
|
||||
out.TotalVisits += a.Visits
|
||||
person := p.Resolve(a.StaffID, a.UnionID, a.Asker, a.Trigger)
|
||||
if len(branches[person.PersonID]) == 0 {
|
||||
out.UnmappedVisits += a.Visits
|
||||
continue
|
||||
}
|
||||
for _, id := range branches[person.PersonID] {
|
||||
row := &out.Rows[indices[id]]
|
||||
visitors[id][person.PersonID] = true
|
||||
row.Visits += a.Visits
|
||||
if row.LastAskedAt == nil || a.LastAskedAt.After(*row.LastAskedAt) {
|
||||
at := a.LastAskedAt
|
||||
row.LastAskedAt = &at
|
||||
}
|
||||
}
|
||||
}
|
||||
for i := range out.Rows {
|
||||
row := &out.Rows[i]
|
||||
row.Visitors = len(visitors[row.ID])
|
||||
if row.TotalPeople > 0 {
|
||||
percent := 100.0 * float64(row.Visitors) / float64(row.TotalPeople)
|
||||
row.Ratio = &percent
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDepartmentStatisticsDeduplicateSubtreePeopleAndUseCurrentMembership(t *testing.T) {
|
||||
directory := Directory{Departments: []Department{{ID: "root", Name: "Root"}, {ID: "child", ParentID: "root", Name: "Child"}, {ID: "former", ParentID: "root", Name: "Former"}, {ID: "current", ParentID: "root", Name: "Current"}, {ID: "empty", ParentID: "root", Name: "Empty"}}, People: []Person{{ID: "one", UnionID: "union-one", Name: "Fixture One", DepartmentIDs: []string{"root", "child"}}, {ID: "moved", Name: "Moved Fixture", DepartmentIDs: []string{"current"}}, {ID: "never", DepartmentIDs: []string{"child"}}}}
|
||||
p, err := BuildAttribution(State{State: "ready", DirectoryID: "fixture"}, directory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
earlier := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
|
||||
later := earlier.Add(time.Hour)
|
||||
out, err := AggregateDepartmentStatistics(p, []DepartmentActivity{{StaffID: "one", Visits: 2, LastAskedAt: earlier}, {UnionID: "union-one", Visits: 1, LastAskedAt: later}, {Asker: "Moved Fixture", Visits: 4, LastAskedAt: earlier}, {StaffID: "not-in-current-directory", Visits: 5, LastAskedAt: later}})
|
||||
if err != nil {
|
||||
t.Fatal("current-roster subtree aggregation is missing", err)
|
||||
}
|
||||
rows := map[string]DepartmentStatistic{}
|
||||
for _, row := range out.Rows {
|
||||
rows[row.ID] = row
|
||||
}
|
||||
root, child, current, former, empty := rows["root"], rows["child"], rows["current"], rows["former"], rows["empty"]
|
||||
if root.TotalPeople != 3 || root.Visitors != 2 || root.Visits != 7 || root.Ratio == nil || *root.Ratio != 100.0*2/3 || root.LastAskedAt == nil || !root.LastAskedAt.Equal(later) {
|
||||
t.Fatalf("subtree parent duplicated or event counts lost: %+v", root)
|
||||
}
|
||||
if child.TotalPeople != 2 || child.Visitors != 1 || child.Visits != 3 || child.Ratio == nil || *child.Ratio != 50 {
|
||||
t.Fatalf("parent/child alias not deduplicated: %+v", child)
|
||||
}
|
||||
if current.Visitors != 1 || current.Visits != 4 || former.Visitors != 0 || former.Visits != 0 {
|
||||
t.Fatal("historical events were attributed to an old department")
|
||||
}
|
||||
if empty.TotalPeople != 0 || empty.Ratio != nil || empty.LastAskedAt != nil {
|
||||
t.Fatal("zero denominator fabricated a percentage/time")
|
||||
}
|
||||
if out.TotalVisits != 12 || out.UnmappedVisits != 5 || out.TotalPeople != 3 {
|
||||
t.Fatalf("unmatched events hidden or fake membership: %+v", out)
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,29 @@ it('draws all eleven panels as a self-contained exportable SVG without HTML exec
|
||||
expect(html).toContain('data-frozen="missing"')
|
||||
expect(html).toContain('data-frozen="available"')
|
||||
})
|
||||
it('renders reported history in both existing trend panels with exact values and honest provenance', () => {
|
||||
const data = parseQADashboard({
|
||||
...dashboardFixture,
|
||||
reported_weeks: [
|
||||
{
|
||||
week: '2026WK40',
|
||||
week_start: '2026-09-28T00:00:00+08:00',
|
||||
week_end: '2026-10-05T00:00:00+08:00',
|
||||
coverage_percent: 57.23,
|
||||
correctness_percent: 92.34,
|
||||
source: 'user_provided_history',
|
||||
},
|
||||
],
|
||||
})
|
||||
const html = renderToStaticMarkup(<QADashboardDrawing data={data} width={1280} />)
|
||||
expect(html).toContain('57.23%')
|
||||
expect(html).toContain('92.34%')
|
||||
expect(html).toContain('用户提供历史统计')
|
||||
expect(html).toContain('未提供分子/分母')
|
||||
expect((html.match(/data-source="user_provided_history"/g) || []).length).toBe(2)
|
||||
expect((html.match(/data-panel=/g) || []).length).toBe(11)
|
||||
expect(html).toContain('data-frozen="available"')
|
||||
})
|
||||
it('reflows the same complete eleven panels at mobile width rather than clipping the canvas', () => {
|
||||
const html = renderToStaticMarkup(<QADashboardDrawing data={parseQADashboard(dashboardFixture)} width={350} />)
|
||||
expect((html.match(/data-panel=/g) || []).length).toBe(11)
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { ReactNode, Ref } from 'react'
|
||||
import type { QADashboardData, DashboardCount, DashboardRegion } from './qaDashboardData'
|
||||
import type { QualityRate } from './qaQuality'
|
||||
import { currentQAWeek } from './qaWeeks'
|
||||
import { historicalTrend } from './qaHistoricalTrend'
|
||||
interface Box {
|
||||
x: number
|
||||
y: number
|
||||
@@ -271,6 +272,8 @@ interface PlotPoint {
|
||||
value: number | null
|
||||
hint: string
|
||||
frozen?: boolean
|
||||
source?: 'user_provided_history' | 'system_frozen'
|
||||
week?: string
|
||||
}
|
||||
function Plot({
|
||||
box,
|
||||
@@ -295,18 +298,37 @@ function Plot({
|
||||
x = (i: number) =>
|
||||
points.length === 1 ? (left + right) / 2 : left + (i * (right - left)) / Math.max(1, points.length - 1),
|
||||
y = (n: number) => bottom - (n / max) * (bottom - top)
|
||||
let path = '',
|
||||
open = false
|
||||
for (let i = 0; i < points.length; i++) {
|
||||
const value = points[i].value
|
||||
if (value === null) {
|
||||
const color = (source: PlotPoint['source']) => (source === 'system_frozen' ? '#8b68c7' : blue)
|
||||
const paths = [...new Set(points.map((p) => p.source))].map((source) => {
|
||||
let path = '',
|
||||
open = false
|
||||
continue
|
||||
for (let i = 0; i < points.length; i++) {
|
||||
const point = points[i]
|
||||
if (point.value === null || point.source !== source) {
|
||||
open = false
|
||||
continue
|
||||
}
|
||||
path += `${open ? 'L' : 'M'} ${x(i)} ${y(point.value)} `
|
||||
open = true
|
||||
}
|
||||
path += `${open ? 'L' : 'M'} ${x(i)} ${y(value)} `
|
||||
open = true
|
||||
}
|
||||
return { source, path }
|
||||
})
|
||||
const every = Math.max(1, Math.ceil(points.length / (box.w < 420 ? 5 : 8)))
|
||||
const labelled = new Set<number>()
|
||||
points.forEach((point, i) => {
|
||||
if (
|
||||
point.value !== null &&
|
||||
(i === 0 ||
|
||||
points[i - 1]?.source !== point.source ||
|
||||
i === points.length - 1 ||
|
||||
points[i + 1]?.source !== point.source)
|
||||
)
|
||||
labelled.add(i)
|
||||
})
|
||||
points.forEach((_, i) => {
|
||||
if ((i % every === 0 || i === points.length - 1) && [...labelled].every((k) => Math.abs(x(k) - x(i)) >= 52))
|
||||
labelled.add(i)
|
||||
})
|
||||
return (
|
||||
<Panel box={box} title={title} en={en} id={id}>
|
||||
{Array.from({ length: 5 }, (_, i) => (
|
||||
@@ -318,30 +340,58 @@ function Plot({
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
{path ? <path d={path} fill="none" stroke={blue} strokeWidth={2} data-series={id} /> : null}
|
||||
{paths
|
||||
.filter((p) => p.path)
|
||||
.map((p, i) => (
|
||||
<path
|
||||
key={i}
|
||||
d={p.path}
|
||||
fill="none"
|
||||
stroke={color(p.source)}
|
||||
strokeWidth={2}
|
||||
data-series={id}
|
||||
data-series-source={p.source}
|
||||
/>
|
||||
))}
|
||||
{points.map((point, i) => (
|
||||
<g
|
||||
key={point.label}
|
||||
data-source={point.source}
|
||||
data-week={point.week}
|
||||
data-value={point.value ?? undefined}
|
||||
data-frozen={point.frozen === undefined ? undefined : point.frozen ? 'available' : 'missing'}
|
||||
>
|
||||
<title>{point.hint}</title>
|
||||
{point.value !== null ? (
|
||||
<>
|
||||
<circle cx={x(i)} cy={y(point.value)} r={3} fill="#fff" stroke={blue} strokeWidth={1.5} />
|
||||
{points.length <= 14 || i % every === 0 || i === points.length - 1 ? (
|
||||
<text x={x(i)} y={Math.max(top - 9, y(point.value) - 9)} fill={blue} fontSize={10} textAnchor="middle">
|
||||
{percent ? `${point.value.toFixed(1)}%` : number(point.value)}
|
||||
<circle cx={x(i)} cy={y(point.value)} r={3} fill="#fff" stroke={color(point.source)} strokeWidth={1.5} />
|
||||
{labelled.has(i) ? (
|
||||
<text
|
||||
x={x(i)}
|
||||
y={Math.max(top - 9, y(point.value) - 9)}
|
||||
fill={color(point.source)}
|
||||
fontSize={10}
|
||||
textAnchor="middle"
|
||||
>
|
||||
{percent ? `${point.value.toFixed(2)}%` : number(point.value)}
|
||||
</text>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
{i % every === 0 || i === points.length - 1 ? (
|
||||
{labelled.has(i) ? (
|
||||
<text x={x(i)} y={bottom + 22} textAnchor="middle" fill={muted} fontSize={10}>
|
||||
{point.label}
|
||||
</text>
|
||||
) : null}
|
||||
</g>
|
||||
))}
|
||||
{percent ? (
|
||||
<text x={16} y={box.h - 7} fontSize={9} fill={muted}>
|
||||
{points.some((p) => p.source === 'user_provided_history')
|
||||
? '蓝:用户提供(未提供分子/分母);紫:系统冻结'
|
||||
: '缺失周留空;系统冻结与当前实时结果分开'}
|
||||
</text>
|
||||
) : null}
|
||||
{!points.some((p) => p.value !== null) ? (
|
||||
<text x={(left + right) / 2} y={(top + bottom) / 2} fill={muted} textAnchor="middle" fontSize={12}>
|
||||
{percent ? '暂无冻结快照' : '暂无数据'}
|
||||
@@ -489,19 +539,7 @@ export function QADashboardDrawing({
|
||||
h: 270,
|
||||
},
|
||||
height = mobile ? cursor + 540 + gap + pad : cursor + 270 + pad
|
||||
const frozen = (correctness: boolean): PlotPoint[] =>
|
||||
data.frozen_weeks.map((p) => {
|
||||
const rate = correctness ? p.correctness : p.coverage,
|
||||
week = currentQAWeek(new Date(p.week_start))
|
||||
return {
|
||||
label: `${week.year}W${String(week.week).padStart(2, '0')}`,
|
||||
value: rate.percent,
|
||||
frozen: p.frozen_at !== null,
|
||||
hint: p.frozen_at
|
||||
? `${week.year}年第${week.week}周:${rate.numerator}/${rate.denominator};冻结于 ${p.frozen_at}`
|
||||
: `${week.year}年第${week.week}周:缺少当时冻结快照`,
|
||||
}
|
||||
})
|
||||
const frozen = (correctness: boolean): PlotPoint[] => historicalTrend(data, correctness)
|
||||
const month = new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7)
|
||||
return (
|
||||
<svg
|
||||
@@ -519,9 +557,7 @@ export function QADashboardDrawing({
|
||||
background: '#fff',
|
||||
}}
|
||||
>
|
||||
<title>
|
||||
问题统计看板 · {week.year}年第{week.week}周
|
||||
</title>
|
||||
<title>{`问题统计看板 · ${week.year}年第${week.week}周`}</title>
|
||||
<rect width={w} height={height} fill="#fff" />
|
||||
<text x={pad + 6} y={27} fontSize={mobile ? 17 : 21} fontWeight={700} fill={ink}>
|
||||
问题统计看板
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { it, expect } from 'vitest'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { DepartmentStatisticsView } from './QADepartmentStatistics'
|
||||
import { parseDepartmentStatistics } from './qaDepartmentStatistics'
|
||||
import { departmentStatisticsFixture } from './qaDepartmentStatistics.fixture'
|
||||
it('renders exactly five requested columns, a denominator and no fabricated zero ratio', () => {
|
||||
const data = parseDepartmentStatistics(departmentStatisticsFixture, { period: 'all' }).snapshot!
|
||||
const html = renderToStaticMarkup(<DepartmentStatisticsView data={data} />)
|
||||
const headers = [...html.matchAll(/<th[^>]*>([^<]+)<\/th>/g)].map((m) => m[1])
|
||||
expect(headers).toEqual(['部门', '访问人数', '访问比例', '访问次数', '最近提问时间'])
|
||||
expect(html).toContain('总人数')
|
||||
expect(html).toContain('66.7%')
|
||||
expect(html).toContain('50.0%')
|
||||
expect(html).not.toContain('覆盖服务')
|
||||
expect(html).toContain('data-ratio="unknown"')
|
||||
expect(html).not.toContain('NaN')
|
||||
})
|
||||
it('keeps parent values unchanged when child departments are collapsed', () => {
|
||||
const data = parseDepartmentStatistics(departmentStatisticsFixture, { period: 'all' }).snapshot!
|
||||
const html = renderToStaticMarkup(<DepartmentStatisticsView data={data} collapsed={new Set(['root'])} />)
|
||||
expect(html).toContain('data-department-id="root"')
|
||||
expect(html).not.toContain('data-department-id="child"')
|
||||
expect(html).toContain('66.7%')
|
||||
expect(html).toContain('总人数')
|
||||
})
|
||||
@@ -0,0 +1,307 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { DepartmentStatisticsSnapshot } from './qaDepartmentStatistics'
|
||||
import { fetchDepartmentStatistics } from './qaDepartmentStatistics'
|
||||
import { departmentTree, selectDepartmentBranch, subtreeIDs } from './qaRegionSelection'
|
||||
import { QARegions } from './QARegions'
|
||||
import './qaDepartmentStatistics.css'
|
||||
export interface DepartmentStatisticsViewProps {
|
||||
data: DepartmentStatisticsSnapshot
|
||||
selected?: string[]
|
||||
collapsed?: ReadonlySet<string>
|
||||
search?: string
|
||||
region?: string
|
||||
onSelect?: (ids: string[]) => void
|
||||
onCollapse?: (id: string) => void
|
||||
}
|
||||
export const departmentTime = (value: string) =>
|
||||
new Date(value).toLocaleString('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
hour12: false,
|
||||
})
|
||||
export function DepartmentStatisticsView(p: DepartmentStatisticsViewProps) {
|
||||
const selected = p.selected ?? [],
|
||||
collapsed = p.collapsed ?? new Set<string>(),
|
||||
rows = departmentTree(p.data.rows, collapsed, p.search ?? '', p.region ?? '')
|
||||
return (
|
||||
<section className="qa-department-list" aria-label="部门访问统计" data-generated-at={p.data.generated_at}>
|
||||
<div className="qa-department-table-scroll" tabIndex={0} aria-label="部门统计表格滚动区">
|
||||
<table className="qa-department-table">
|
||||
<colgroup>
|
||||
<col className="qa-department-name-column" />
|
||||
<col />
|
||||
<col />
|
||||
<col />
|
||||
<col className="qa-department-time-column" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>部门</th>
|
||||
<th>访问人数</th>
|
||||
<th>访问比例</th>
|
||||
<th title="已入总表的唯一提问事件,包含失败请求;不包含未采集的网页浏览">访问次数</th>
|
||||
<th>最近提问时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map(({ department: d, depth, hasChildren }) => {
|
||||
const branch = subtreeIDs(p.data.rows, [d.id]),
|
||||
checked = branch.every((id) => selected.includes(id)),
|
||||
partial = !checked && branch.some((id) => selected.includes(id)),
|
||||
label = p.data.regions.find((r) => r.id === d.region)?.name
|
||||
return (
|
||||
<tr
|
||||
key={d.id}
|
||||
data-department-id={d.id}
|
||||
data-visitors={d.visitors}
|
||||
data-total-people={d.total_people}
|
||||
data-visits={d.visits}
|
||||
data-latest={d.last_asked_at ?? ''}
|
||||
>
|
||||
<td>
|
||||
<div className="qa-department-name" style={{ paddingInlineStart: depth * 20 }}>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={`选择部门 ${d.name}及子部门`}
|
||||
checked={checked}
|
||||
ref={(node) => {
|
||||
if (node) node.indeterminate = partial
|
||||
}}
|
||||
onChange={(e) =>
|
||||
p.onSelect?.(selectDepartmentBranch(p.data.rows, selected, d.id, e.target.checked))
|
||||
}
|
||||
/>
|
||||
{hasChildren ? (
|
||||
<button
|
||||
type="button"
|
||||
className="qa-department-expand"
|
||||
aria-label={`${collapsed.has(d.id) ? '展开' : '收起'}部门 ${d.name}`}
|
||||
aria-expanded={!collapsed.has(d.id)}
|
||||
onClick={() => p.onCollapse?.(d.id)}
|
||||
>
|
||||
{collapsed.has(d.id) ? '›' : '⌄'}
|
||||
</button>
|
||||
) : (
|
||||
<span className="qa-department-expand-space" />
|
||||
)}
|
||||
<span className="qa-department-label">
|
||||
{d.name}
|
||||
{label ? <small className="qa-department-region">{label}</small> : null}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<span>{d.visitors.toLocaleString('zh-CN')}</span>
|
||||
<small className="qa-department-roster">总人数 {d.total_people.toLocaleString('zh-CN')}</small>
|
||||
</td>
|
||||
<td className="qa-department-ratio" data-ratio={d.ratio === null ? 'unknown' : d.ratio}>
|
||||
{d.ratio === null ? '—' : `${d.ratio.toFixed(1)}%`}
|
||||
</td>
|
||||
<td>{d.visits.toLocaleString('zh-CN')}</td>
|
||||
<td>{d.last_asked_at === null ? '—' : departmentTime(d.last_asked_at)}</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
{!rows.length ? <p className="qa-ops-empty">没有匹配的部门</p> : null}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
const currentMonth = () => {
|
||||
const parts = new Intl.DateTimeFormat('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
}).formatToParts(new Date())
|
||||
return `${parts.find((p) => p.type === 'year')!.value}-${parts.find((p) => p.type === 'month')!.value}`
|
||||
}
|
||||
export function QARegionalStatistics() {
|
||||
const [period, setPeriod] = useState<'all' | 'month'>('all'),
|
||||
[month, setMonth] = useState(currentMonth),
|
||||
[reload, setReload] = useState(0),
|
||||
[settings, setSettings] = useState(false)
|
||||
const [data, setData] = useState<DepartmentStatisticsSnapshot | null>(null),
|
||||
[error, setError] = useState(''),
|
||||
[busy, setBusy] = useState(true),
|
||||
[cached, setCached] = useState(false)
|
||||
const [selected, setSelected] = useState<string[]>([]),
|
||||
[collapsed, setCollapsed] = useState<Set<string>>(new Set()),
|
||||
[search, setSearch] = useState(''),
|
||||
[region, setRegion] = useState('')
|
||||
const key = useRef(''),
|
||||
condition = useRef(''),
|
||||
query = useMemo(
|
||||
() => (period === 'all' ? { period: 'all' as const } : { period: 'month' as const, month }),
|
||||
[period, month]
|
||||
)
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
const signature = JSON.stringify(query)
|
||||
if (condition.current !== signature) {
|
||||
setData(null)
|
||||
key.current = ''
|
||||
condition.current = signature
|
||||
}
|
||||
const poll = async () => {
|
||||
setBusy(true)
|
||||
setError('')
|
||||
try {
|
||||
const result = await fetchDepartmentStatistics(query, controller.signal)
|
||||
if (controller.signal.aborted) return
|
||||
if (key.current !== result.cache_key) {
|
||||
setData(null)
|
||||
key.current = result.cache_key
|
||||
}
|
||||
if (result.state === 'ready' && result.snapshot) {
|
||||
const fresh = result.snapshot
|
||||
setData(fresh)
|
||||
setCached(result.cache_hit)
|
||||
setBusy(false)
|
||||
const ids = new Set(fresh.rows.map((d) => d.id))
|
||||
setSelected((old) => old.filter((id) => ids.has(id)))
|
||||
setCollapsed((old) => new Set([...old].filter((id) => ids.has(id))))
|
||||
setRegion((old) => (fresh.regions.some((r) => r.id === old) ? old : ''))
|
||||
timer = setTimeout(() => void poll(), Math.max(1000, Date.parse(fresh.expires_at) - Date.now() + 100))
|
||||
} else timer = setTimeout(() => void poll(), result.retry_after * 1000)
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(e instanceof Error ? e.message : '区域统计读取失败')
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
void poll()
|
||||
return () => {
|
||||
controller.abort()
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}, [query, reload])
|
||||
return (
|
||||
<section className="qa-regional-statistics" aria-label="区域统计">
|
||||
<header className="qa-department-toolbar">
|
||||
<h3>区域统计</h3>
|
||||
<div className="qa-department-actions">
|
||||
<button type="button" disabled={busy} onClick={() => setReload((v) => v + 1)}>
|
||||
重新读取统计
|
||||
</button>
|
||||
<button type="button" aria-expanded={settings} onClick={() => setSettings((v) => !v)}>
|
||||
{settings ? '返回部门统计' : '区域设置'}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
<div hidden={!settings} className="qa-department-editor">
|
||||
<QARegions selection={selected} onSelectionChange={setSelected} onSaved={() => setReload((v) => v + 1)} />
|
||||
</div>
|
||||
<div hidden={settings}>
|
||||
<div className="qa-department-filters">
|
||||
<label>
|
||||
统计范围
|
||||
<select
|
||||
aria-label="部门统计范围"
|
||||
value={period}
|
||||
onChange={(e) => setPeriod(e.target.value as 'all' | 'month')}
|
||||
>
|
||||
<option value="all">累计提问访问</option>
|
||||
<option value="month">按自然月</option>
|
||||
</select>
|
||||
</label>
|
||||
{period === 'month' ? (
|
||||
<label>
|
||||
统计月份
|
||||
<input
|
||||
aria-label="部门统计月份"
|
||||
type="month"
|
||||
min="2000-01"
|
||||
max={currentMonth()}
|
||||
value={month}
|
||||
onChange={(e) => setMonth(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
) : null}
|
||||
<label>
|
||||
部门
|
||||
<input
|
||||
type="search"
|
||||
aria-label="搜索统计部门"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="搜索部门或完整路径"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
区域
|
||||
<select aria-label="筛选统计区域" value={region} onChange={(e) => setRegion(e.target.value)}>
|
||||
<option value="">全部区域</option>
|
||||
{data?.regions.map((r) => (
|
||||
<option key={r.id} value={r.id}>
|
||||
{r.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button type="button" disabled={!selected.length} onClick={() => setSettings(true)}>
|
||||
设置选中部门的区域{selected.length ? `(${selected.length})` : ''}
|
||||
</button>
|
||||
<button type="button" disabled={!selected.length} onClick={() => setSelected([])}>
|
||||
取消勾选
|
||||
</button>
|
||||
</div>
|
||||
<div className="qa-department-meta" role="status" aria-live="polite">
|
||||
{busy
|
||||
? data
|
||||
? '后台重新聚合中,暂保留上次结果…'
|
||||
: '正在后台聚合部门统计…'
|
||||
: data
|
||||
? `${cached ? '60秒缓存结果' : '统计已更新'} · 统计截至 ${departmentTime(data.end)} · 通讯录 ${data.organization.synced_at ? departmentTime(data.organization.synced_at) : '未同步'}`
|
||||
: ''}
|
||||
</div>
|
||||
{error ? (
|
||||
<div className="error-banner" role="alert">
|
||||
{error}
|
||||
{data ? ';当前为上一次结果,未替换成零数据' : ''}{' '}
|
||||
<button type="button" onClick={() => setReload((v) => v + 1)}>
|
||||
重试
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
{data ? (
|
||||
<>
|
||||
<DepartmentStatisticsView
|
||||
data={data}
|
||||
selected={selected}
|
||||
collapsed={collapsed}
|
||||
search={search}
|
||||
region={region}
|
||||
onSelect={setSelected}
|
||||
onCollapse={(id) =>
|
||||
setCollapsed((old) => {
|
||||
const next = new Set(old)
|
||||
if (next.has(id)) next.delete(id)
|
||||
else next.add(id)
|
||||
return next
|
||||
})
|
||||
}
|
||||
/>
|
||||
<p className="qa-department-note">
|
||||
每行含本部门及全部子部门,按当前通讯录人员去重;收起不改变统计。访问为已入总表的提问事件,区域筛选只改变可见部门。
|
||||
</p>
|
||||
{data.unmapped_visits > 0 ? (
|
||||
<p className="qa-department-note">
|
||||
另有 {data.unmapped_visits.toLocaleString('zh-CN')} 次提问未能归入当前通讯录部门,未虚构归属。
|
||||
</p>
|
||||
) : null}
|
||||
</>
|
||||
) : !busy && !error ? (
|
||||
<p className="qa-ops-empty">尚无统计结果,请重新读取。</p>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -117,7 +117,7 @@ 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 = ['问题流水', '问题统计看板', '区域配置', '周报生成']
|
||||
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('部门/区域保留源快照')
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useOptionalAuth } from './auth'
|
||||
import { fetchQARecord, fetchAllQARecords, fetchQAStatus, qaCellValue, qaColumns } from './qaOps'
|
||||
import type { QAQuery, QARecord, QARecordPage, QAStatus } from './qaOps'
|
||||
import './qaOps.css'
|
||||
import { QARegions } from './QARegions'
|
||||
import { QARegionalStatistics } from './QADepartmentStatistics'
|
||||
import { QADashboard } from './QADashboard'
|
||||
import { QAWeekly } from './QAWeekly'
|
||||
import { QAQualityEditor } from './QAQuality'
|
||||
@@ -26,7 +26,7 @@ export function QAOperationsTabs({ view, onChange }: { view: QAOpsView; onChange
|
||||
[
|
||||
['records', '问题流水'],
|
||||
['dashboard', '问题统计看板'],
|
||||
['regions', '区域配置'],
|
||||
['regions', '区域统计'],
|
||||
['weekly', '周报生成'],
|
||||
] as const
|
||||
).map(([id, label]) => (
|
||||
@@ -603,7 +603,7 @@ export function QAOperations() {
|
||||
</>
|
||||
) : null}
|
||||
{view === 'regions' ? (
|
||||
<QARegions />
|
||||
<QARegionalStatistics />
|
||||
) : view === 'weekly' ? (
|
||||
<QAWeekly query={query} />
|
||||
) : view === 'dashboard' ? (
|
||||
|
||||
@@ -51,6 +51,16 @@ const props = {
|
||||
onRemoveMissing: vi.fn(),
|
||||
}
|
||||
describe('region mapping workbench', () => {
|
||||
it('allows removing unused region definitions but protects regions referenced by department rules', () => {
|
||||
const regions = [
|
||||
{ id: 'APAC', name: 'Assigned' },
|
||||
{ id: 'spare', name: 'Spare' },
|
||||
]
|
||||
const html = renderToStaticMarkup(<RegionMappingView {...props} regions={regions} />)
|
||||
expect(html).toContain('删除区域 Spare')
|
||||
expect(html).toMatch(/aria-label="删除区域 Assigned"[^>]*disabled=""/)
|
||||
})
|
||||
|
||||
it('separates multiselect from bulk application and renders hierarchy and editable region names', () => {
|
||||
const custom = {
|
||||
...state,
|
||||
|
||||
+32
-11
@@ -9,7 +9,7 @@ import {
|
||||
} from './qaOrg'
|
||||
import type { Organization, RegionRule, RegionDefinition } from './qaOrg'
|
||||
import './qaRegions.css'
|
||||
import { applyBulkRegionRules, departmentLevels } from './qaRegionSelection'
|
||||
import { applyBulkRegionRules, departmentLevels, selectDepartmentBranch } from './qaRegionSelection'
|
||||
import { completedSyncAction, directorySyncActive, fetchDirectorySync, startDirectorySync } from './qaOrgSync'
|
||||
import type { DirectorySyncStatus } from './qaOrgSync'
|
||||
import { newOperationID } from './operationKey'
|
||||
@@ -57,8 +57,7 @@ export function RegionMappingView(p: Props) {
|
||||
)
|
||||
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 choose = (id: string, checked: boolean) => p.onSelect?.(selectDepartmentBranch(all, selected, id, checked))
|
||||
const add = () => {
|
||||
if (!newName.trim()) return
|
||||
const next = [...regions, { id: 'region-' + newOperationID(), name: newName.trim() }]
|
||||
@@ -155,6 +154,19 @@ export function RegionMappingView(p: Props) {
|
||||
p.onCatalog?.(regions.map((x) => (x.id === r.id ? { ...x, name: e.target.value } : x)))
|
||||
}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`删除区域 ${r.name}`}
|
||||
disabled={p.busy || p.rules.some((rule) => rule.region === r.id)}
|
||||
title={
|
||||
p.rules.some((rule) => rule.region === r.id)
|
||||
? '此区域仍有部门配置,请先移除对应配置'
|
||||
: '从草稿移除此区域,保存后生效'
|
||||
}
|
||||
onClick={() => p.onCatalog?.(regions.filter((item) => item.id !== r.id))}
|
||||
>
|
||||
删除区域
|
||||
</button>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
@@ -226,12 +238,10 @@ export function RegionMappingView(p: Props) {
|
||||
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))
|
||||
)
|
||||
let next = [...selected]
|
||||
for (const row of departments)
|
||||
next = selectDepartmentBranch(all, next, row.department.id, e.target.checked)
|
||||
p.onSelect?.(next)
|
||||
}}
|
||||
/>
|
||||
全选当前列表
|
||||
@@ -351,7 +361,11 @@ export function RegionMappingView(p: Props) {
|
||||
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() {
|
||||
export function QARegions({
|
||||
selection,
|
||||
onSelectionChange,
|
||||
onSaved,
|
||||
}: { selection?: string[]; onSelectionChange?: (ids: string[]) => void; onSaved?: () => void } = {}) {
|
||||
const [syncStatus, setSyncStatus] = useState<DirectorySyncStatus | null>(null),
|
||||
[syncError, setSyncError] = useState(''),
|
||||
[syncSubmitting, setSyncSubmitting] = useState(false)
|
||||
@@ -364,7 +378,12 @@ export function QARegions() {
|
||||
[preview, setPreview] = useState<Organization | null>(null),
|
||||
[rules, setRules] = useState<RegionRule[]>([])
|
||||
const [regions, setRegions] = useState<RegionDefinition[]>([]),
|
||||
[selected, setSelected] = useState<string[]>([])
|
||||
[localSelected, setLocalSelected] = useState<string[]>([])
|
||||
const selected = selection ?? localSelected,
|
||||
setSelected = (ids: string[]) => {
|
||||
setLocalSelected(ids)
|
||||
onSelectionChange?.(ids)
|
||||
}
|
||||
const [region, setRegion] = useState<string>(''),
|
||||
[search, setSearch] = useState(''),
|
||||
[busy, setBusy] = useState(false),
|
||||
@@ -496,6 +515,7 @@ export function QARegions() {
|
||||
accept(readback)
|
||||
if (readback.revision_id !== value.revision_id) throw new Error('保存后配置再次变化,已读取最新版本,请核对')
|
||||
setNotice('区域归属已保存并重新读取')
|
||||
onSaved?.()
|
||||
} else setPreview(value)
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -513,6 +533,7 @@ export function QARegions() {
|
||||
selectedIDs={selected}
|
||||
onCatalog={(next) => {
|
||||
setRegions(next)
|
||||
setRegion((old) => (next.some((r) => r.id === old) ? old : (next[0]?.id ?? '')))
|
||||
setPreview(null)
|
||||
setNotice('')
|
||||
setError('')
|
||||
|
||||
@@ -1,6 +1,36 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { parseQADashboard } from './qaDashboardData'
|
||||
import { dashboardFixture } from './qaDashboard.fixture'
|
||||
const reported = {
|
||||
week: '2026WK40',
|
||||
week_start: '2026-09-28T00:00:00+08:00',
|
||||
week_end: '2026-10-05T00:00:00+08:00',
|
||||
coverage_percent: 57.23,
|
||||
correctness_percent: 92.34,
|
||||
source: 'user_provided_history',
|
||||
}
|
||||
describe('reported historical rates', () => {
|
||||
it('keeps supplied percentages without inventing denominator or freeze time', () => {
|
||||
const result = parseQADashboard({ ...dashboardFixture, reported_weeks: [reported] })
|
||||
expect(result.reported_weeks).toEqual([reported])
|
||||
expect(result.frozen_weeks).toEqual(parseQADashboard(dashboardFixture).frozen_weeks)
|
||||
expect(result.quality).toEqual(parseQADashboard(dashboardFixture).quality)
|
||||
})
|
||||
it('rejects invalid, duplicate, future, wrongly labelled and keyword-scoped supplied history', () => {
|
||||
for (const input of [
|
||||
{ ...dashboardFixture, reported_weeks: [reported, reported] },
|
||||
{ ...dashboardFixture, reported_weeks: [{ ...reported, denominator: 100 }] },
|
||||
{ ...dashboardFixture, reported_weeks: [{ ...reported, coverage_percent: 100.01 }] },
|
||||
{ ...dashboardFixture, reported_weeks: [{ ...reported, correctness_percent: null }] },
|
||||
{ ...dashboardFixture, reported_weeks: [{ ...reported, source: 'frozen' }] },
|
||||
{ ...dashboardFixture, reported_weeks: [{ ...reported, week: '2026WK41' }] },
|
||||
{ ...dashboardFixture, reported_weeks: [{ ...reported, week_end: '2027-01-01T00:00:00+08:00' }] },
|
||||
{ ...dashboardFixture, keyword: 'needle', reported_weeks: [reported] },
|
||||
])
|
||||
expect(() => parseQADashboard(input)).toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('complete dashboard data contract', () => {
|
||||
it('keeps distinct cumulative, week, month and genuinely frozen periods', () => {
|
||||
const data = parseQADashboard(dashboardFixture)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { parseQAOrganizationVersion } from './qaOps'
|
||||
import { currentQAWeek } from './qaWeeks'
|
||||
import type { QAOrganizationVersion, QAQuery } from './qaOps'
|
||||
import { parseQualitySummary, parseQualityRate } from './qaQuality'
|
||||
import type { QualitySummary, QualityRate } from './qaQuality'
|
||||
@@ -6,6 +7,14 @@ export interface DashboardCount {
|
||||
label: string
|
||||
count: number
|
||||
}
|
||||
export interface DashboardReported {
|
||||
week: string
|
||||
week_start: string
|
||||
week_end: string
|
||||
coverage_percent: number
|
||||
correctness_percent: number
|
||||
source: 'user_provided_history'
|
||||
}
|
||||
export interface DashboardFrozen {
|
||||
week_start: string
|
||||
week_end: string
|
||||
@@ -41,6 +50,7 @@ export interface QADashboardData {
|
||||
daily: { date: string; count: number }[]
|
||||
regions: DashboardRegion[]
|
||||
frozen_weeks: DashboardFrozen[]
|
||||
reported_weeks: DashboardReported[]
|
||||
}
|
||||
const bad = (): never => {
|
||||
throw new Error('统计看板响应无效,未展示可能失真的指标')
|
||||
@@ -186,6 +196,43 @@ export function parseQADashboard(value: unknown): QADashboardData {
|
||||
(frozen_weeks.length && Date.parse(frozen_weeks[frozen_weeks.length - 1].week_end) < Date.parse(end))
|
||||
)
|
||||
return bad()
|
||||
const reported_weeks = list(v.reported_weeks === undefined ? [] : v.reported_weeks).map((raw, i) => {
|
||||
const p = obj(raw),
|
||||
week = text(p.week),
|
||||
begin = stamp(p.week_start),
|
||||
finish = stamp(p.week_end)
|
||||
const iso = currentQAWeek(new Date(begin))
|
||||
const percent = (value: unknown) =>
|
||||
typeof value === 'number' &&
|
||||
Number.isFinite(value) &&
|
||||
value >= 0 &&
|
||||
value <= 100 &&
|
||||
Math.abs(value * 100 - Math.round(value * 100)) < 1e-8
|
||||
? value
|
||||
: bad()
|
||||
if (
|
||||
Object.keys(p).some(
|
||||
(k) => !['week', 'week_start', 'week_end', 'coverage_percent', 'correctness_percent', 'source'].includes(k)
|
||||
) ||
|
||||
keyword !== '' ||
|
||||
p.source !== 'user_provided_history' ||
|
||||
week !== `${iso.year}WK${String(iso.week).padStart(2, '0')}` ||
|
||||
monday(Date.parse(begin)) !== Date.parse(begin) ||
|
||||
Date.parse(finish) - Date.parse(begin) !== 7 * dayMS ||
|
||||
Date.parse(finish) > Date.parse(end)
|
||||
)
|
||||
return bad()
|
||||
if (i > 0 && Date.parse(begin) <= Date.parse(text(obj(list(v.reported_weeks)[i - 1]).week_start))) return bad()
|
||||
return {
|
||||
week,
|
||||
week_start: begin,
|
||||
week_end: finish,
|
||||
coverage_percent: percent(p.coverage_percent),
|
||||
correctness_percent: percent(p.correctness_percent),
|
||||
source: 'user_provided_history' as const,
|
||||
}
|
||||
})
|
||||
if (reported_weeks.length > 5200) return bad()
|
||||
return {
|
||||
start,
|
||||
end,
|
||||
@@ -193,6 +240,7 @@ export function parseQADashboard(value: unknown): QADashboardData {
|
||||
as_of,
|
||||
week_start,
|
||||
month_start,
|
||||
reported_weeks,
|
||||
local_revision: count(v.local_revision),
|
||||
organization,
|
||||
total_issues,
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
.qa-regional-statistics {
|
||||
min-width: 0;
|
||||
color: #334155;
|
||||
}
|
||||
.qa-department-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin: 0 0 14px;
|
||||
}
|
||||
.qa-department-toolbar h3 {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
}
|
||||
.qa-department-actions,
|
||||
.qa-department-filters {
|
||||
display: flex;
|
||||
align-items: end;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
}
|
||||
.qa-department-filters {
|
||||
padding: 10px 0;
|
||||
}
|
||||
.qa-department-filters label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
}
|
||||
.qa-department-filters input,
|
||||
.qa-department-filters select {
|
||||
min-height: 34px;
|
||||
max-width: 240px;
|
||||
}
|
||||
.qa-department-meta,
|
||||
.qa-department-note {
|
||||
font-size: 12px;
|
||||
color: #718096;
|
||||
margin: 8px 0;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.qa-department-table-scroll {
|
||||
max-height: calc(100vh - 340px);
|
||||
min-height: 280px;
|
||||
overflow: auto;
|
||||
border: 1px solid #e5ebf2;
|
||||
border-radius: 5px;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
background: #fff;
|
||||
}
|
||||
.qa-department-table {
|
||||
width: 100%;
|
||||
min-width: 900px;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
font-size: 14px;
|
||||
}
|
||||
.qa-department-name-column {
|
||||
width: 43%;
|
||||
}
|
||||
.qa-department-time-column {
|
||||
width: 20%;
|
||||
}
|
||||
.qa-department-table th,
|
||||
.qa-department-table td {
|
||||
padding: 13px 12px;
|
||||
border-right: 1px solid #e8edf4;
|
||||
border-bottom: 1px solid #e8edf4;
|
||||
text-align: center;
|
||||
vertical-align: middle;
|
||||
white-space: nowrap;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.qa-department-table th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 2;
|
||||
background: #f8fafc;
|
||||
font-weight: 600;
|
||||
color: #60748c;
|
||||
}
|
||||
.qa-department-table td:first-child,
|
||||
.qa-department-table th:first-child {
|
||||
text-align: left;
|
||||
}
|
||||
.qa-department-table tbody tr:hover {
|
||||
background: #f7faff;
|
||||
}
|
||||
.qa-department-name {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
min-width: 0;
|
||||
}
|
||||
.qa-department-name input[type='checkbox'] {
|
||||
flex: none;
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
margin: 0;
|
||||
}
|
||||
.qa-department-expand,
|
||||
.qa-department-expand-space {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 20px;
|
||||
min-width: 20px;
|
||||
height: 24px;
|
||||
}
|
||||
.qa-department-expand {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #536c88;
|
||||
font-size: 20px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.qa-department-expand:focus-visible {
|
||||
outline: 2px solid #3b82f6;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.qa-department-label {
|
||||
min-width: 0;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.qa-department-region,
|
||||
.qa-department-roster {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
color: #8190a4;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.qa-department-ratio {
|
||||
font-weight: 650;
|
||||
}
|
||||
.qa-department-ratio[data-ratio='unknown'] {
|
||||
font-weight: 400;
|
||||
color: #8190a4;
|
||||
}
|
||||
.qa-department-editor {
|
||||
min-width: 0;
|
||||
}
|
||||
@media (max-width: 680px) {
|
||||
.qa-department-toolbar {
|
||||
align-items: flex-start;
|
||||
}
|
||||
.qa-department-actions {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.qa-department-actions button {
|
||||
font-size: 12px;
|
||||
padding: 6px 8px;
|
||||
}
|
||||
.qa-department-table-scroll {
|
||||
max-height: 65vh;
|
||||
}
|
||||
.qa-department-filters input {
|
||||
max-width: 180px;
|
||||
}
|
||||
.qa-department-filters {
|
||||
gap: 8px;
|
||||
}
|
||||
.qa-department-filters label {
|
||||
max-width: 100%;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
export const departmentStatisticsFixture = {
|
||||
state: 'ready',
|
||||
cache_key: 'a'.repeat(64),
|
||||
cache_hit: true,
|
||||
retry_after: 0,
|
||||
snapshot: {
|
||||
period: 'all',
|
||||
month: '',
|
||||
start: '2026-04-01T00:00:00+08:00',
|
||||
end: '2026-10-19T12:00:00+08:00',
|
||||
generated_at: '2026-10-19T12:00:01+08:00',
|
||||
expires_at: '2026-10-19T12:01:01+08:00',
|
||||
total_people: 3,
|
||||
total_visits: 6,
|
||||
unmapped_visits: 1,
|
||||
organization: {
|
||||
state: 'ready',
|
||||
directory_id: 'fixture-directory',
|
||||
directory_source: 'weekly_report_snapshot',
|
||||
synced_at: '2026-10-18T00:00:00+08:00',
|
||||
revision_id: 'fixture-revision',
|
||||
basis: 'current_directory',
|
||||
region_names: ['Education'],
|
||||
},
|
||||
regions: [{ id: 'edu', name: 'Education' }],
|
||||
rows: [
|
||||
{
|
||||
id: 'root',
|
||||
parent_id: '',
|
||||
name: 'Fixture Root',
|
||||
region: '',
|
||||
visitors: 2,
|
||||
total_people: 3,
|
||||
ratio: (100 * 2) / 3,
|
||||
visits: 5,
|
||||
last_asked_at: '2026-10-18T06:00:00+08:00',
|
||||
},
|
||||
{
|
||||
id: 'child',
|
||||
parent_id: 'root',
|
||||
name: 'Fixture Child',
|
||||
region: 'edu',
|
||||
visitors: 1,
|
||||
total_people: 2,
|
||||
ratio: 50,
|
||||
visits: 2,
|
||||
last_asked_at: '2026-10-17T06:00:00+08:00',
|
||||
},
|
||||
{
|
||||
id: 'empty',
|
||||
parent_id: 'root',
|
||||
name: 'Empty',
|
||||
region: '',
|
||||
visitors: 0,
|
||||
total_people: 0,
|
||||
ratio: null,
|
||||
visits: 0,
|
||||
last_asked_at: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { it, expect } from 'vitest'
|
||||
import { parseDepartmentStatistics } from './qaDepartmentStatistics'
|
||||
import { departmentStatisticsFixture as fixture } from './qaDepartmentStatistics.fixture'
|
||||
it('preserves source roster denominators, null zero-denominator ratio and exact cache identity', () => {
|
||||
const data = parseDepartmentStatistics(fixture, { period: 'all' })
|
||||
expect(data.snapshot?.rows[0].visitors).toBe(2)
|
||||
expect(data.snapshot?.rows[0].total_people).toBe(3)
|
||||
expect(data.snapshot?.rows[2].ratio).toBeNull()
|
||||
expect(data.cache_key).toBe(fixture.cache_key)
|
||||
})
|
||||
it('rejects fake zeros, invalid hierarchy, inconsistent ratios and wrong conditions', () => {
|
||||
for (const rows of [
|
||||
fixture.snapshot.rows.map((r) => (r.id === 'empty' ? { ...r, ratio: 0 } : r)),
|
||||
fixture.snapshot.rows.map((r) => (r.id === 'child' ? { ...r, parent_id: 'missing' } : r)),
|
||||
fixture.snapshot.rows.map((r) => (r.id === 'child' ? { ...r, visitors: 3 } : r)),
|
||||
fixture.snapshot.rows.map((r) => (r.id === 'child' ? { ...r, ratio: 70 } : r)),
|
||||
fixture.snapshot.rows.map((r) => (r.id === 'child' ? { ...r, last_asked_at: '2027-01-01T00:00:00Z' } : r)),
|
||||
])
|
||||
expect(() =>
|
||||
parseDepartmentStatistics({ ...fixture, snapshot: { ...fixture.snapshot, rows } }, { period: 'all' })
|
||||
).toThrow()
|
||||
expect(() => parseDepartmentStatistics(fixture, { period: 'month', month: '2026-10' })).toThrow()
|
||||
})
|
||||
@@ -0,0 +1,191 @@
|
||||
import type { QAOrganizationVersion } from './qaOps'
|
||||
import { parseQAOrganizationVersion } from './qaOps'
|
||||
import { parseRegionDefinitions } from './qaOrg'
|
||||
import { departmentTree } from './qaRegionSelection'
|
||||
import type { RegionDefinition } from './qaOrg'
|
||||
export interface DepartmentStatisticsQuery {
|
||||
period: 'all' | 'month'
|
||||
month?: string
|
||||
}
|
||||
export interface DepartmentStatistic {
|
||||
id: string
|
||||
parent_id: string
|
||||
name: string
|
||||
region: string
|
||||
visitors: number
|
||||
total_people: number
|
||||
ratio: number | null
|
||||
visits: number
|
||||
last_asked_at: string | null
|
||||
}
|
||||
export interface DepartmentStatisticsSnapshot {
|
||||
rows: DepartmentStatistic[]
|
||||
total_visits: number
|
||||
unmapped_visits: number
|
||||
total_people: number
|
||||
organization: QAOrganizationVersion
|
||||
regions: RegionDefinition[]
|
||||
period: 'all' | 'month'
|
||||
month: string
|
||||
start: string | null
|
||||
end: string
|
||||
generated_at: string
|
||||
expires_at: string
|
||||
}
|
||||
export interface DepartmentStatisticsResult {
|
||||
state: 'pending' | 'ready'
|
||||
cache_key: string
|
||||
cache_hit: boolean
|
||||
retry_after: number
|
||||
snapshot: DepartmentStatisticsSnapshot | null
|
||||
}
|
||||
const bad = (): never => {
|
||||
throw Error('区域统计响应无效,请重试或联系管理员')
|
||||
}
|
||||
const obj = (v: unknown): Record<string, unknown> =>
|
||||
v !== null && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : bad()
|
||||
const text = (v: unknown) => (typeof v === 'string' ? v : bad())
|
||||
const count = (v: unknown) => (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 ? v : bad())
|
||||
const instant = (v: unknown) => (typeof v === 'string' && Number.isFinite(Date.parse(v)) ? v : bad())
|
||||
export function parseDepartmentStatistics(raw: unknown, query: DepartmentStatisticsQuery): DepartmentStatisticsResult {
|
||||
const v = obj(raw),
|
||||
cache_key = text(v.cache_key)
|
||||
if (
|
||||
!/^[a-f0-9]{64}$/.test(cache_key) ||
|
||||
typeof v.cache_hit !== 'boolean' ||
|
||||
!['pending', 'ready'].includes(String(v.state))
|
||||
)
|
||||
return bad()
|
||||
if (v.state === 'pending') {
|
||||
if (v.snapshot !== null || v.retry_after !== 1) return bad()
|
||||
return { state: 'pending', cache_key, cache_hit: false, retry_after: 1, snapshot: null }
|
||||
}
|
||||
if (v.retry_after !== 0) return bad()
|
||||
const d = obj(v.snapshot),
|
||||
organization = parseQAOrganizationVersion(d.organization)
|
||||
if (!organization || organization.state !== 'ready' || !organization.directory_id || !organization.synced_at)
|
||||
return bad()
|
||||
const regions = parseRegionDefinitions(d.regions),
|
||||
regionIDs = new Set(regions.map((r) => r.id))
|
||||
if (
|
||||
d.period !== query.period ||
|
||||
d.month !== (query.month ?? '') ||
|
||||
!Array.isArray(d.rows) ||
|
||||
!d.rows.length ||
|
||||
d.rows.length > 20000
|
||||
)
|
||||
return bad()
|
||||
const end = instant(d.end),
|
||||
generated = instant(d.generated_at),
|
||||
expires = instant(d.expires_at),
|
||||
start = d.start === null ? null : instant(d.start)
|
||||
if (
|
||||
Date.parse(expires) - Date.parse(generated) !== 60000 ||
|
||||
Date.parse(end) > Date.parse(generated) ||
|
||||
(start !== null && Date.parse(start) >= Date.parse(end))
|
||||
)
|
||||
return bad()
|
||||
const total_people = count(d.total_people),
|
||||
total_visits = count(d.total_visits),
|
||||
unmapped_visits = count(d.unmapped_visits)
|
||||
if (unmapped_visits > total_visits) return bad()
|
||||
const rows: DepartmentStatistic[] = d.rows.map((raw) => {
|
||||
const r = obj(raw),
|
||||
id = text(r.id),
|
||||
parent_id = text(r.parent_id),
|
||||
name = text(r.name),
|
||||
region = text(r.region),
|
||||
visitors = count(r.visitors),
|
||||
total = count(r.total_people),
|
||||
visits = count(r.visits),
|
||||
last = r.last_asked_at === null ? null : instant(r.last_asked_at)
|
||||
if (
|
||||
!id ||
|
||||
!name ||
|
||||
(region !== '' && !regionIDs.has(region)) ||
|
||||
visitors > total ||
|
||||
total > total_people ||
|
||||
visits < visitors ||
|
||||
visits > total_visits - unmapped_visits ||
|
||||
(visits === 0) !== (visitors === 0) ||
|
||||
(visits === 0) !== (last === null) ||
|
||||
(last !== null &&
|
||||
(Date.parse(last) >= Date.parse(end) || (start !== null && Date.parse(last) < Date.parse(start))))
|
||||
)
|
||||
return bad()
|
||||
if (
|
||||
total === 0
|
||||
? r.ratio !== null
|
||||
: typeof r.ratio !== 'number' ||
|
||||
!Number.isFinite(r.ratio) ||
|
||||
Math.abs(r.ratio - (100 * visitors) / total) > 1e-8
|
||||
)
|
||||
return bad()
|
||||
return {
|
||||
id,
|
||||
parent_id,
|
||||
name,
|
||||
region,
|
||||
visitors,
|
||||
total_people: total,
|
||||
ratio: r.ratio as number | null,
|
||||
visits,
|
||||
last_asked_at: last,
|
||||
}
|
||||
})
|
||||
departmentTree(rows, new Set())
|
||||
const byID = new Map(rows.map((r) => [r.id, r]))
|
||||
for (const row of rows) {
|
||||
const parent = byID.get(row.parent_id)
|
||||
if (
|
||||
parent &&
|
||||
(parent.total_people < row.total_people ||
|
||||
parent.visitors < row.visitors ||
|
||||
parent.visits < row.visits ||
|
||||
(row.last_asked_at !== null &&
|
||||
(parent.last_asked_at === null || Date.parse(parent.last_asked_at) < Date.parse(row.last_asked_at))))
|
||||
)
|
||||
return bad()
|
||||
}
|
||||
return {
|
||||
state: 'ready',
|
||||
cache_key,
|
||||
cache_hit: v.cache_hit,
|
||||
retry_after: 0,
|
||||
snapshot: {
|
||||
rows,
|
||||
total_people,
|
||||
total_visits,
|
||||
unmapped_visits,
|
||||
organization,
|
||||
regions,
|
||||
period: query.period,
|
||||
month: query.month ?? '',
|
||||
start,
|
||||
end,
|
||||
generated_at: generated,
|
||||
expires_at: expires,
|
||||
},
|
||||
}
|
||||
}
|
||||
export async function fetchDepartmentStatistics(
|
||||
query: DepartmentStatisticsQuery,
|
||||
signal?: AbortSignal
|
||||
): Promise<DepartmentStatisticsResult> {
|
||||
const response = await fetch('/api/v1/qa-ops/departments/statistics', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
cache: 'no-store',
|
||||
signal,
|
||||
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-department-statistics' },
|
||||
body: JSON.stringify(query),
|
||||
})
|
||||
const raw: unknown = await response.json().catch(() => null)
|
||||
if (!response.ok) {
|
||||
const error = raw && typeof raw === 'object' ? (raw as Record<string, unknown>).error : undefined
|
||||
throw Error(typeof error === 'string' ? error : `区域统计读取失败(HTTP ${response.status})`)
|
||||
}
|
||||
const data = parseDepartmentStatistics(obj(raw).data, query)
|
||||
if ((response.status === 202) !== (data.state === 'pending')) return bad()
|
||||
return data
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { it, expect } from 'vitest'
|
||||
import { subtreeIDs, selectDepartmentBranch, departmentTree } from './qaRegionSelection'
|
||||
const nodes = [
|
||||
{ id: 'root', parent_id: '', name: 'Root' },
|
||||
{ id: 'child', parent_id: 'root', name: 'Child' },
|
||||
{ id: 'leaf', parent_id: 'child', name: 'Leaf' },
|
||||
{ id: 'other', parent_id: 'root', name: 'Other' },
|
||||
]
|
||||
it('selects a full branch and removes partial ancestors when a descendant is unchecked', () => {
|
||||
expect(new Set(subtreeIDs(nodes, ['child']))).toEqual(new Set(['child', 'leaf']))
|
||||
const selected = selectDepartmentBranch(nodes, [], 'root', true)
|
||||
expect(new Set(selected)).toEqual(new Set(nodes.map((d) => d.id)))
|
||||
expect(new Set(selectDepartmentBranch(nodes, selected, 'leaf', false))).toEqual(new Set(['other']))
|
||||
expect(selected).toHaveLength(4)
|
||||
})
|
||||
it('collapses hierarchy without dropping source rows or changing statistics', () => {
|
||||
const before = JSON.stringify(nodes)
|
||||
expect(departmentTree(nodes, new Set(['child'])).map((r) => r.department.id)).toEqual(['root', 'child', 'other'])
|
||||
expect(departmentTree(nodes, new Set(['root']), 'Leaf').map((r) => r.department.id)).toEqual([
|
||||
'root',
|
||||
'child',
|
||||
'leaf',
|
||||
])
|
||||
expect(JSON.stringify(nodes)).toBe(before)
|
||||
expect(() => departmentTree([{ id: 'bad', parent_id: 'bad', name: 'Cycle' }], new Set())).toThrow()
|
||||
})
|
||||
@@ -0,0 +1,27 @@
|
||||
import { it, expect } from 'vitest'
|
||||
import { parseQADashboard } from './qaDashboardData'
|
||||
import { dashboardFixture } from './qaDashboard.fixture'
|
||||
import { historicalTrend } from './qaHistoricalTrend'
|
||||
it('keeps absent weeks null, preserves supplied precision and never mutates real frozen evidence', () => {
|
||||
const input = parseQADashboard({
|
||||
...dashboardFixture,
|
||||
reported_weeks: [
|
||||
{
|
||||
week: '2026WK38',
|
||||
week_start: '2026-09-14T00:00:00+08:00',
|
||||
week_end: '2026-09-21T00:00:00+08:00',
|
||||
coverage_percent: 57.23,
|
||||
correctness_percent: 92.34,
|
||||
source: 'user_provided_history',
|
||||
},
|
||||
],
|
||||
})
|
||||
const before = JSON.stringify(input)
|
||||
const points = historicalTrend(input, false)
|
||||
expect(points.map((p) => p.week)).toEqual(['2026WK38', '2026WK39', '2026WK40', '2026WK41'])
|
||||
expect(points.map((p) => p.value)).toEqual([57.23, null, null, 50])
|
||||
expect(points[0].source).toBe('user_provided_history')
|
||||
expect(points[3].source).toBe('system_frozen')
|
||||
expect(historicalTrend(input, true)[0].value).toBe(92.34)
|
||||
expect(JSON.stringify(input)).toBe(before)
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { QADashboardData } from './qaDashboardData'
|
||||
import { currentQAWeek } from './qaWeeks'
|
||||
export interface HistoricalPlotPoint {
|
||||
label: string
|
||||
value: number | null
|
||||
hint: string
|
||||
frozen?: boolean
|
||||
source?: 'user_provided_history' | 'system_frozen'
|
||||
week?: string
|
||||
}
|
||||
// Never manufacture row counts or connect a line across missing weeks/policy changes.
|
||||
export function historicalTrend(data: QADashboardData, correctness: boolean): HistoricalPlotPoint[] {
|
||||
const frozen = new Map(data.frozen_weeks.map((p) => [Date.parse(p.week_start), p]))
|
||||
const reported = new Map(data.reported_weeks.map((p) => [Date.parse(p.week_start), p]))
|
||||
const starts = [...frozen.keys(), ...reported.keys()]
|
||||
if (!starts.length) return []
|
||||
const out: HistoricalPlotPoint[] = []
|
||||
for (let at = Math.min(...starts); at < Date.parse(data.end) && out.length < 5200; at += 7 * 86400000) {
|
||||
const w = currentQAWeek(new Date(at)),
|
||||
label = `${w.year}W${String(w.week).padStart(2, '0')}`,
|
||||
supplied = reported.get(at),
|
||||
point = frozen.get(at)
|
||||
if (supplied) {
|
||||
const value = correctness ? supplied.correctness_percent : supplied.coverage_percent
|
||||
out.push({
|
||||
label,
|
||||
week: supplied.week,
|
||||
value,
|
||||
source: 'user_provided_history',
|
||||
hint: `${supplied.week}:${value.toFixed(2)}%;用户提供历史统计,未提供分子/分母;不按当前规则重算`,
|
||||
})
|
||||
continue
|
||||
}
|
||||
const rate = point ? (correctness ? point.correctness : point.coverage) : null
|
||||
out.push({
|
||||
label,
|
||||
week: `${w.year}WK${String(w.week).padStart(2, '0')}`,
|
||||
value: rate?.percent ?? null,
|
||||
frozen: point?.frozen_at !== null && point?.frozen_at !== undefined,
|
||||
source: point?.frozen_at ? 'system_frozen' : undefined,
|
||||
hint: point?.frozen_at
|
||||
? `${label}:${rate?.percent?.toFixed(2) ?? '—'}%;${rate?.numerator}/${rate?.denominator};系统冻结于 ${point.frozen_at}`
|
||||
: `${label}:未提供历史统计,缺少当时冻结快照`,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -1,4 +1,92 @@
|
||||
import type { DepartmentRegion, RegionRule } from './qaOrg'
|
||||
export type DepartmentNode = { id: string; parent_id: string; name: string }
|
||||
export function subtreeIDs(nodes: DepartmentNode[], ids: string[]): string[] {
|
||||
const children = new Map<string, string[]>(),
|
||||
known = new Set(nodes.map((n) => n.id))
|
||||
for (const node of nodes) {
|
||||
const list = children.get(node.parent_id) ?? []
|
||||
list.push(node.id)
|
||||
children.set(node.parent_id, list)
|
||||
}
|
||||
const seen = new Set<string>(),
|
||||
queue = [...ids]
|
||||
while (queue.length) {
|
||||
const id = queue.pop()!
|
||||
if (!known.has(id)) throw Error('部门不在当前通讯录')
|
||||
if (seen.has(id)) continue
|
||||
seen.add(id)
|
||||
queue.push(...(children.get(id) ?? []))
|
||||
}
|
||||
return [...seen]
|
||||
}
|
||||
export function selectDepartmentBranch(
|
||||
nodes: DepartmentNode[],
|
||||
selected: string[],
|
||||
id: string,
|
||||
checked: boolean
|
||||
): string[] {
|
||||
const ids = subtreeIDs(nodes, [id]),
|
||||
next = new Set(selected)
|
||||
if (checked) ids.forEach((x) => next.add(x))
|
||||
else {
|
||||
ids.forEach((x) => next.delete(x))
|
||||
const parents = new Map(nodes.map((n) => [n.id, n.parent_id]))
|
||||
const seen = new Set<string>()
|
||||
let parent = parents.get(id)
|
||||
while (parent && !seen.has(parent)) {
|
||||
seen.add(parent)
|
||||
next.delete(parent)
|
||||
parent = parents.get(parent)
|
||||
}
|
||||
}
|
||||
return [...next]
|
||||
}
|
||||
export function departmentTree<T extends DepartmentNode>(
|
||||
nodes: T[],
|
||||
collapsed: ReadonlySet<string>,
|
||||
search = '',
|
||||
region = ''
|
||||
): Array<{ department: T; depth: number; hasChildren: boolean }> {
|
||||
const known = new Map(nodes.map((n) => [n.id, n])),
|
||||
children = new Map<string, T[]>()
|
||||
if (known.size !== nodes.length) throw Error('通讯录部门重复')
|
||||
for (const node of nodes) {
|
||||
if (node.parent_id && !known.has(node.parent_id)) throw Error('通讯录缺少父部门')
|
||||
const list = children.get(node.parent_id) ?? []
|
||||
list.push(node)
|
||||
children.set(node.parent_id, list)
|
||||
}
|
||||
for (const list of children.values())
|
||||
list.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN') || a.id.localeCompare(b.id))
|
||||
const all: Array<{ department: T; depth: number; hasChildren: boolean; parents: string[]; path: string }> = [],
|
||||
seen = new Set<string>()
|
||||
const walk = (parent: string, parents: string[], names: string[]) => {
|
||||
for (const node of children.get(parent) ?? []) {
|
||||
if (seen.has(node.id) || parents.length > 100) throw Error('通讯录部门层级无效')
|
||||
seen.add(node.id)
|
||||
all.push({
|
||||
department: node,
|
||||
depth: parents.length,
|
||||
hasChildren: !!children.get(node.id)?.length,
|
||||
parents,
|
||||
path: [...names, node.name].join('/'),
|
||||
})
|
||||
walk(node.id, [...parents, node.id], [...names, node.name])
|
||||
}
|
||||
}
|
||||
walk('', [], [])
|
||||
if (all.length !== nodes.length) throw Error('通讯录部门存在循环')
|
||||
if (search || region) {
|
||||
const matches = all.filter(
|
||||
(r) =>
|
||||
(!search || r.path.toLowerCase().includes(search.toLowerCase())) &&
|
||||
(!region || (r.department as DepartmentNode & { region?: string }).region === region)
|
||||
)
|
||||
const visible = new Set(matches.flatMap((r) => [r.department.id, ...r.parents]))
|
||||
return all.filter((r) => visible.has(r.department.id))
|
||||
}
|
||||
return all.filter((r) => !r.parents.some((id) => collapsed.has(id)))
|
||||
}
|
||||
export function applyBulkRegionRules(rules: RegionRule[], ids: string[], region: string): RegionRule[] {
|
||||
const selected = new Set(ids)
|
||||
if (!selected.size) return [...rules]
|
||||
|
||||
Reference in New Issue
Block a user