Compare commits

...

4 Commits

Author SHA1 Message Date
姚章浩 154b0b62ad feat(qaops): 完成区域统计与部门绑定六项联动
build / build (push) Successful in 1m20s
新增北京时间自然周校验与缓存隔离,默认展开到业务二级部门。
选中部门在统计页就地绑定;区域名称列表原位增删改,双版本锁、自动预览、独立读回及删除确认。
筛选和两张区域看板使用同一已保存目录,删除失效筛选回全部。

验证:完整 make verify、全 mirror 隔离 PostgreSQL race、自然周边界与缓存键负例通过;真实恢复库327部门逐行对拍及六项浏览器验收通过。
schema57无迁移,不改真实公司区域绑定或原始问答,不连接DobotAI生产源库;PNG导出本轮不冒充已验证。
2026-10-19 23:41:01 +08:00
姚章浩 9470a127f7 feat(qaops): 完成流水表六项体验与AI执行修正
build / build (push) Successful in 1m11s
统一AI分析入口及双任务安全确认,采用全量载入的可见行渲染,保留完整原文。
右侧非模态详情固定五项质量字段,清理冗余展示并对齐查询和同步按钮。
默认4并发由数据库准入与逐任务租约保护,保留共享限流冷却、截断归因和有界重试。
兼容真实引用标题字段,不伪造证据或准确率,不修改源生产问答与公司区域规则。

验证:完整make verify退出0,710项Go通过、124项已声明可选跳过且必需0跳过;
另全量mirror隔离PostgreSQL race退出0,AI单元race退出0。
真实本地浏览器通过六项交互、390px内滚动及显式AI部分失败/零缺口故障夹具。
治理原生备份已真实恢复,schema57、72表计数与29张QA内容哈希一致。
候选镜像、精确提交CI与正式上线验收待本次提交后执行,不宣称已部署。
2026-10-19 22:09:32 +08:00
姚章浩 4a2b2b7d84 feat(qaops): 增加部门树区域统计与父子联选
build / build (push) Successful in 1m5s
区域配置入口改为区域统计,五列表按当前通讯录整支人员去重;调岗依当前归属、零分母未知、最近真实提问时间和父行收起不重算。仅读治理正式总表,后台单并发/请求合并/60秒缓存,目录与配置版本隔离,客户端失败不伪零。

保留区域自定义目录与预览/双版本锁保存,父部门勾选联选全后代,取消子支清除祖先整支选择,避免隐式覆盖未选子级;允许删除无引用区域,已有引用不静默孤立。统计页与设置共享选择,统计支持累计与北京时间自然月;不新增迁移,不改DobotAI生产、代理、原问答、历史趋势或已有AI任务。

验证已执行:完整make verify退出0,705 Go/340前端通过、120项声明的可选集成跳过且必需0跳过;镜像全量隔离PG race退出0;新增去重/调岗/空分母、后台缓存/并发、HTTP授权/严格请求、真PG目录与配置失效、树选择/收起、五列与删除保护均先红后绿。旧导航测试按新名称更新后全量通过。上线前治理库备份与真实恢复72表/29张QA内容哈希一致,匹配独立主密钥受限备份。

当前尚待精确SHA CI、同镜像真实数据浏览器与正式读回,不把源码验证称为已上线。公司真实区域映射不在本轮擅改;只在隔离库验证保存。
2026-10-19 19:01:36 +08:00
姚章浩 a9870beade feat(qaops): 补充独立历史覆盖率与正确率趋势
build / build (push) Successful in 1m10s
用户提供的历史百分比独立持久化,按ISO自然周和截止范围读取,不伪造分子分母、记录数或冻结时间。现有两张趋势图与PNG共用来源分色/分段及两位小数;缺失周留空,关键词筛选不借用无明细历史,当前指标与原冻结证据不变。

验证:完整make verify退出0;镜像全量隔离PG race退出0,新增来源/精度/关键词/租户/截止/不可变和安全down回归先失败后通过。前端输入/来源及缺失周回归先红后绿。治理库上线前原生备份与真实恢复已完成,71表行数和28张QA表内容哈希一致,独立主密钥同时受限备份。

当前仅完成开发验证,真实数据候选浏览器验收、正式25周导入与应用上线需继续完成。不修改源生产数据库、原问答、已有模型自动开关或隧道;用户原始报表和图像只保存于私有证据目录,不入Git。
2026-10-19 17:55:15 +08:00
62 changed files with 3668 additions and 709 deletions
+50
View File
@@ -76,6 +76,56 @@
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯,
> 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。
## 开发快照 snapshot/v0.1.40 - 2026-10-19
### Added
- 区域统计明确支持按累计、北京时间自然月、北京时间自然周三种范围;自然周按周一至周日,可选择历史周,校验跨年周次、非法周和未来周,独立缓存包含周次及组织版本。
### Changed
- 部门树默认显示公司、中心及二级部门,更深层收起;保留手动展开与搜索,父行去重人数和提问次数不随收起变化。
- 选中部门后在当前统计页选择区域并绑定,复用预览、双版本锁和保存后独立读回,不跳转另一张映射表;父选仍覆盖后代,既有非选中部门规则保留。
- 区域设置重做为原页面内的名称列表面板,支持新增、改名、删除及未保存草稿保护。删除已绑定区域须确认解除直接绑定,目录与规则一次保存,不删除原问答;重复点击原删除位置只取消确认。
- 区域筛选及绑定选项取已保存目录,新增/改名/删除后刷新,删除当前筛选项回全部;问题统计看板的平均使用频率和使用覆盖率沿用同一已保存组织配置,保留自然月口径与零分母未知,不重新计算冻结历史。
## 开发快照 snapshot/v0.1.39 - 2026-10-19
### Changed
- “问题流水”改为“问题流水表”;详情从右侧非模态弹出,不再生成左侧遮罩或焦点陷阱。移除详情中的区域、组织关联/版本/快照、记录来源、问答状态与流程触发人员展示,原始数据与审计不删除。
- 是否覆盖、是否正确、产品分类、问题类型、根因分析置于详情顶部固定区域,正文独立滚动;查询与立即同步统一尺寸和基线。
- 字段评估与中文翻译统一为“AI分析”,分别预览缺口、确认后按实际需要创建两类持久任务;部分成功重试保留幂等标识,跳过已确认种类与零缺口种类,不覆盖人工或已有非空结论。
### Fixed
- 大流水表保留全量载入与无分页滚动,改为仅渲染可见行和缓冲行、稳定行引用及固定列宽;列表长文本限预览,详情与导出仍取完整原文,重复后台状态不再驱动整表刷新。
- AI执行改为数据库准入控制的默认4并发、独立任务租约与过期栅栏;慢模型调用不阻塞其他工作槽或自动扫描。429遵守共享有界冷却;输出截断单独归因,最多三次有界重试并逐次扩大输出预算,最终失败保留可见状态。
- 兼容源引用的knowledge_title字段,不将只有标题的引用伪造为正文证据;证据不足仍待确认,不将模型自报置信度当作准确率。修正人工复核区仍声称AI未接入的旧提示。
## 开发快照 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
+108 -1
View File
@@ -44,6 +44,71 @@
}
],
"paths": {
"/api/v1/qa-ops/departments/statistics": {
"post": {
"operationId": "qaDepartmentStatistics",
"summary": "部门树访问统计,当前通讯录整支人员去重",
"description": "仅独立治理总表,不读取生产或更改原问答;后台单聚合并发,响应202或60秒缓存结果。当前目录和区域配置版本加入缓存键;父行包含自身及全部后代,人员按当前稳定身份去重,调岗归当前部门;零分母比例为null,最近提问时间来自真实事件。访问指已入总表的提问事件,不含未记录的网页浏览。管理员同源只读POST,操作头qa-department-statistics。 统计范围all/month/week;week使用YYYY-Www的合法ISO自然周,按北京时间周一至次周一不含结束,当前周截到当前,禁止未来周或混用month/week。",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"additionalProperties": false,
"required": [
"period"
],
"properties": {
"period": {
"type": "string",
"enum": [
"all",
"month",
"week"
]
},
"month": {
"type": "string",
"pattern": "^[0-9]{4}-[0-9]{2}$"
},
"week": {
"type": "string",
"pattern": "^[0-9]{4}-W[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 +121,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 +4457,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)
}
}
+1 -1
View File
@@ -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")
}
+1
View File
@@ -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])
+23 -4
View File
@@ -9,6 +9,7 @@ import (
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
@@ -18,8 +19,9 @@ var ErrInvalid = errors.New("qa_ai_invalid_request")
var ErrConflict = errors.New("qa_ai_version_conflict")
type RemoteError struct {
Code string
Retryable bool
RetryAfter time.Duration
Code string
Retryable bool
}
func (e *RemoteError) Error() string { return "qa_ai_" + e.Code }
@@ -75,7 +77,21 @@ func (c Client) Call(ctx context.Context, base, model, key, system string, input
case response.StatusCode >= 300 && response.StatusCode < 400:
code = "redirect_rejected"
}
return Completion{}, &RemoteError{Code: code, Retryable: retry}
var delay time.Duration
if code == "rate_limited" {
if seconds, e := strconv.Atoi(response.Header.Get("Retry-After")); e == nil && seconds > 0 {
delay = time.Duration(seconds) * time.Second
} else if date, e := http.ParseTime(response.Header.Get("Retry-After")); e == nil {
delay = time.Until(date)
}
if delay < 15*time.Second {
delay = 15 * time.Second
}
if delay > 120*time.Second {
delay = 120 * time.Second
}
}
return Completion{}, &RemoteError{Code: code, Retryable: retry, RetryAfter: delay}
}
raw, err := io.ReadAll(io.LimitReader(response.Body, (4<<20)+1))
if err != nil || len(raw) > 4<<20 {
@@ -90,8 +106,11 @@ func (c Client) Call(ctx context.Context, base, model, key, system string, input
FinishReason string `json:"finish_reason"`
} `json:"choices"`
}
if json.Unmarshal(raw, &result) == nil && len(result.Choices) == 1 && result.Choices[0].FinishReason == "length" {
return Completion{}, &RemoteError{Code: "output_truncated", Retryable: true}
}
if json.Unmarshal(raw, &result) != nil || len(result.Choices) != 1 || result.Choices[0].FinishReason != "stop" || strings.TrimSpace(result.Choices[0].Message.Content) == "" {
return Completion{}, &RemoteError{Code: "incomplete_response"}
return Completion{}, &RemoteError{Code: "incomplete_response", Retryable: true}
}
return Completion{Content: result.Choices[0].Message.Content, Model: result.Model}, nil
}
+26
View File
@@ -3,6 +3,7 @@ package qaopsai
import (
"context"
"encoding/json"
"errors"
"net"
"net/http"
"net/http/httptest"
@@ -74,3 +75,28 @@ func TestClientRejectsPrivateEndpointsBeforeSendingSecrets(t *testing.T) {
}
}
}
func TestClientDistinguishesTruncatedOutputAndRetainsProviderCooldown(t *testing.T) {
for _, tc := range []struct {
name, body, code string
status int
delay time.Duration
}{
{"truncated", `{"model":"fixture","choices":[{"message":{"content":"{"},"finish_reason":"length"}]}`, "output_truncated", 200, 0},
{"rate-limit", `{}`, "rate_limited", 429, 45 * time.Second},
} {
t.Run(tc.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Retry-After", "45")
w.WriteHeader(tc.status)
_, _ = w.Write([]byte(tc.body))
}))
defer server.Close()
_, err := (Client{AllowPrivate: true}).Call(context.Background(), server.URL, "fixture", "fixture-only", "json", map[string]string{}, 64)
var remote *RemoteError
if !errors.As(err, &remote) || remote.Code != tc.code || !remote.Retryable || remote.RetryAfter != tc.delay {
t.Fatalf("lost retry classification/cooldown: %+v", err)
}
})
}
}
+38 -21
View File
@@ -17,6 +17,12 @@ type claimedWork struct {
Attempt, RetryBase int
}
func (s *Store) concurrency() int {
if s.options.Concurrency > 0 && s.options.Concurrency <= 16 {
return s.options.Concurrency
}
return 4
}
func (s *Store) claim(ctx context.Context) (*claimedWork, error) {
if !s.valid() {
return nil, ErrUnavailable
@@ -26,33 +32,37 @@ func (s *Store) claim(ctx context.Context) (*claimedWork, error) {
return nil, ErrUnavailable
}
defer tx.Rollback(context.Background())
_, err = tx.Exec(ctx, `INSERT INTO qa_ops_ai_runtime(tenant_key,heartbeat_at)VALUES($1,clock_timestamp())ON CONFLICT(tenant_key)DO UPDATE SET heartbeat_at=EXCLUDED.heartbeat_at`, s.tenant)
if err != nil {
if _, err = tx.Exec(ctx, `INSERT INTO qa_ops_ai_runtime(tenant_key,heartbeat_at)VALUES($1,clock_timestamp())ON CONFLICT(tenant_key)DO UPDATE SET heartbeat_at=EXCLUDED.heartbeat_at`, s.tenant); err != nil {
return nil, ErrUnavailable
}
var active string
var leased, waiting bool
err = tx.QueryRow(ctx, `SELECT active_work_id,COALESCE(lease_until>clock_timestamp(),false),next_request_at>clock_timestamp() FROM qa_ops_ai_runtime WHERE tenant_key=$1 FOR UPDATE`, s.tenant).Scan(&active, &leased, &waiting)
if err != nil {
var waiting bool
if tx.QueryRow(ctx, `SELECT next_request_at>clock_timestamp()FROM qa_ops_ai_runtime WHERE tenant_key=$1 FOR UPDATE`, s.tenant).Scan(&waiting) != nil {
return nil, ErrUnavailable
}
if leased || waiting {
if waiting {
if tx.Commit(ctx) != nil {
return nil, ErrUnavailable
}
return nil, nil
}
if active != "" {
_, err = tx.Exec(ctx, `UPDATE qa_ops_ai_work SET state=CASE WHEN attempt>=retry_base+3 THEN 'failed' ELSE 'retry' END,stage='lease_expired',error_code='worker_lease_expired',available_at=clock_timestamp(),lease_token='',lease_until=NULL,updated_at=clock_timestamp() WHERE tenant_key=$1 AND id=$2 AND state='running'`, s.tenant, active)
if err != nil {
// The tenant lock protects admission only; each outbound request retains its own fenced lease.
if _, err = tx.Exec(ctx, `UPDATE qa_ops_ai_work SET state=CASE WHEN attempt>=retry_base+3 THEN 'failed' ELSE 'retry' END,stage='lease_expired',error_code='worker_lease_expired',available_at=clock_timestamp(),lease_token='',lease_until=NULL,updated_at=clock_timestamp()WHERE tenant_key=$1 AND state='running' AND lease_until<=clock_timestamp()`, s.tenant); err != nil {
return nil, ErrUnavailable
}
var running int
if tx.QueryRow(ctx, `SELECT count(*)FROM qa_ops_ai_work WHERE tenant_key=$1 AND state='running'AND lease_until>clock_timestamp()`, s.tenant).Scan(&running) != nil {
return nil, ErrUnavailable
}
if running >= s.concurrency() {
if tx.Commit(ctx) != nil {
return nil, ErrUnavailable
}
return nil, nil
}
var out claimedWork
err = tx.QueryRow(ctx, `SELECT id,record_id,kind,trigger_mode,input_hash,master_revision,review_revision,config_revision,attempt,retry_base FROM qa_ops_ai_work WHERE tenant_key=$1 AND state IN ('queued','retry') AND available_at<=clock_timestamp() AND ((trigger_mode='manual' AND EXISTS(SELECT 1 FROM qa_ops_ai_batch_items i JOIN qa_ops_ai_batches b ON b.tenant_key=i.tenant_key AND b.id=i.batch_id WHERE i.tenant_key=qa_ops_ai_work.tenant_key AND i.work_id=qa_ops_ai_work.id AND b.state='active')) OR (trigger_mode='automatic' AND EXISTS(SELECT 1 FROM qa_ops_ai_settings s WHERE s.tenant_key=qa_ops_ai_work.tenant_key AND s.verification='verified' AND CASE WHEN kind='evaluation' THEN s.automatic_evaluation ELSE s.automatic_translation END))) ORDER BY CASE WHEN trigger_mode='manual' THEN 0 ELSE 1 END,available_at,created_at,id FOR UPDATE SKIP LOCKED LIMIT 1`, s.tenant).Scan(&out.ID, &out.RecordID, &out.Kind, &out.Mode, &out.InputHash, &out.MasterRevision, &out.ReviewRevision, &out.ConfigRevision, &out.Attempt, &out.RetryBase)
err = tx.QueryRow(ctx, `SELECT id,record_id,kind,trigger_mode,input_hash,master_revision,review_revision,config_revision,attempt,retry_base FROM qa_ops_ai_work w WHERE tenant_key=$1 AND state IN ('queued','retry')AND available_at<=clock_timestamp()AND NOT EXISTS(SELECT 1 FROM qa_ops_ai_work busy WHERE busy.tenant_key=w.tenant_key AND busy.record_id=w.record_id AND busy.kind=w.kind AND busy.state='running')AND((trigger_mode='manual'AND EXISTS(SELECT 1 FROM qa_ops_ai_batch_items i JOIN qa_ops_ai_batches b ON b.tenant_key=i.tenant_key AND b.id=i.batch_id WHERE i.tenant_key=w.tenant_key AND i.work_id=w.id AND b.state='active'))OR(trigger_mode='automatic'AND EXISTS(SELECT 1 FROM qa_ops_ai_settings s WHERE s.tenant_key=w.tenant_key AND s.verification='verified'AND CASE WHEN kind='evaluation' THEN s.automatic_evaluation ELSE s.automatic_translation END)))ORDER BY CASE WHEN trigger_mode='manual'THEN 0 ELSE 1 END,(SELECT count(*)FROM qa_ops_ai_work busy WHERE busy.tenant_key=w.tenant_key AND busy.kind=w.kind AND busy.state='running'),available_at,created_at,id FOR UPDATE SKIP LOCKED LIMIT 1`, s.tenant).Scan(&out.ID, &out.RecordID, &out.Kind, &out.Mode, &out.InputHash, &out.MasterRevision, &out.ReviewRevision, &out.ConfigRevision, &out.Attempt, &out.RetryBase)
if err == pgx.ErrNoRows {
_, err = tx.Exec(ctx, `UPDATE qa_ops_ai_runtime SET active_work_id='',lease_token='',lease_until=NULL WHERE tenant_key=$1`, s.tenant)
if err != nil || tx.Commit(ctx) != nil {
if tx.Commit(ctx) != nil {
return nil, ErrUnavailable
}
return nil, nil
@@ -65,12 +75,10 @@ func (s *Store) claim(ctx context.Context) (*claimedWork, error) {
return nil, err
}
out.Attempt++
_, err = tx.Exec(ctx, `UPDATE qa_ops_ai_work SET state='running',stage='preparing',attempt=$3,lease_token=$4,lease_until=clock_timestamp()+interval '180 seconds',started_at=clock_timestamp(),updated_at=clock_timestamp() WHERE tenant_key=$1 AND id=$2`, s.tenant, out.ID, out.Attempt, out.Token)
if err != nil {
if _, err = tx.Exec(ctx, `UPDATE qa_ops_ai_work SET state='running',stage='preparing',attempt=$3,lease_token=$4,lease_until=clock_timestamp()+interval '180 seconds',started_at=clock_timestamp(),updated_at=clock_timestamp()WHERE tenant_key=$1 AND id=$2`, s.tenant, out.ID, out.Attempt, out.Token); err != nil {
return nil, ErrUnavailable
}
_, err = tx.Exec(ctx, `UPDATE qa_ops_ai_runtime SET active_work_id=$2,lease_token=$3,lease_until=clock_timestamp()+interval '180 seconds' WHERE tenant_key=$1`, s.tenant, out.ID, out.Token)
if err != nil || tx.Commit(ctx) != nil {
if tx.Commit(ctx) != nil {
return nil, ErrUnavailable
}
return &out, nil
@@ -107,6 +115,9 @@ func referencesFor(record dobotaiops.Record) []Reference {
for _, item := range items {
ref := Reference{}
ref.Title, _ = item["title"].(string)
if strings.TrimSpace(ref.Title) == "" {
ref.Title, _ = item["knowledge_title"].(string)
}
for _, key := range []string{"excerpt", "snippet", "content", "text"} {
if text, ok := item[key].(string); ok && strings.TrimSpace(text) != "" {
ref.Excerpt = text
@@ -181,7 +192,7 @@ func (s *Store) execute(ctx context.Context, w claimedWork) error {
if err != nil {
return s.finish(w, nil, nil, "", "", &RemoteError{Code: "secret_storage_unavailable"})
}
completion, err := (Client{AllowPrivate: s.options.AllowPrivate, DNSOverTLS: s.options.DNSOverTLS}).Call(ctx, cfg.BaseURL, cfg.Model, key, system, modelInput, 4096)
completion, err := (Client{AllowPrivate: s.options.AllowPrivate, DNSOverTLS: s.options.DNSOverTLS}).Call(ctx, cfg.BaseURL, cfg.Model, key, system, modelInput, 4096<<min(w.Attempt-w.RetryBase-1, 2))
if err != nil {
return s.finish(w, nil, nil, "", "", err)
}
@@ -193,14 +204,14 @@ func (s *Store) execute(ctx context.Context, w claimedWork) error {
if w.Kind == "translation" {
chinese, e := DecodeTranslation(completion.Content, record.Question)
if e != nil {
return s.finish(w, nil, nil, completion.Model, "", &RemoteError{Code: "output_validation_failed"})
return s.finish(w, nil, nil, completion.Model, "", &RemoteError{Code: "output_validation_failed", Retryable: true})
}
fields["question_chinese"] = chinese
result = map[string]string{"question_chinese": chinese}
} else {
assessment, e := DecodeAssessment(completion.Content, input)
if e != nil {
return s.finish(w, nil, nil, completion.Model, "", &RemoteError{Code: "output_validation_failed"})
return s.finish(w, nil, nil, completion.Model, "", &RemoteError{Code: "output_validation_failed", Retryable: true})
}
for field, value := range assessment.Fields {
fields[field] = value.Value
@@ -267,6 +278,12 @@ func (s *Store) finish(w claimedWork, payload []byte, proposed map[string]string
}
}
delay := time.Duration(1<<uint(w.Attempt-w.RetryBase)) * time.Second
cooldown := time.Duration(0)
var remote *RemoteError
if errors.As(cause, &remote) && code == "rate_limited" {
cooldown = max(15*time.Second, remote.RetryAfter)
delay = max(delay, cooldown)
}
_, err = tx.Exec(ctx, `UPDATE qa_ops_ai_work SET state=$4,stage=$5,error_code=$6,skip_reason=$7,lease_token='',lease_until=NULL,finished_at=CASE WHEN $4 IN ('retry','paused') THEN NULL ELSE clock_timestamp() END,available_at=clock_timestamp()+$8::interval,updated_at=clock_timestamp() WHERE tenant_key=$1 AND id=$2 AND lease_token=$3`, s.tenant, w.ID, w.Token, status, stage, code, skip, delay.String())
if err != nil {
return ErrUnavailable
@@ -277,7 +294,7 @@ func (s *Store) finish(w claimedWork, payload []byte, proposed map[string]string
return ErrUnavailable
}
}
_, err = tx.Exec(ctx, `UPDATE qa_ops_ai_runtime SET active_work_id='',lease_token='',lease_until=NULL,next_request_at=clock_timestamp()+interval '1 second',heartbeat_at=clock_timestamp() WHERE tenant_key=$1 AND lease_token=$2`, s.tenant, w.Token)
_, err = tx.Exec(ctx, `UPDATE qa_ops_ai_runtime SET heartbeat_at=clock_timestamp(),next_request_at=CASE WHEN $2 THEN GREATEST(next_request_at,clock_timestamp()+$3::interval)ELSE next_request_at END WHERE tenant_key=$1`, s.tenant, code == "rate_limited", cooldown.String())
if err != nil || tx.Commit(ctx) != nil {
return ErrUnavailable
}
+32
View File
@@ -0,0 +1,32 @@
package qaopsai
import (
"context"
"encoding/json"
"knowledge-governance/internal/dobotaiops"
"testing"
"time"
)
func TestRunWithUnavailableStoreFailsClosed(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
defer func() {
if recover() != nil {
t.Fatal("unavailable worker panicked")
}
}()
called := false
(&Store{}).Run(ctx, func(err error) { called = err == ErrUnavailable })
if !called {
t.Fatal("unavailable worker failed silently")
}
}
func TestReferencesPreserveSourceKnowledgeTitleWithoutInventingEvidence(t *testing.T) {
r := dobotaiops.Record{References: json.RawMessage(`[{"knowledge_title":"MG400官方连接说明","id":"only-title"},{"title":"原始标题","knowledge_title":"不能覆盖","content":"逐字证据"}]`)}
refs := referencesFor(r)
if len(refs) != 2 || refs[0].Title != "MG400官方连接说明" || refs[0].Excerpt != "" || refs[1].Title != "原始标题" || refs[1].Excerpt != "逐字证据" {
t.Fatalf("source citation titles lost or title-only treated as evidence: %+v", refs)
}
}
+47 -17
View File
@@ -2,39 +2,69 @@ package qaopsai
import (
"context"
"sync"
"time"
)
// This loop owns only the AI subqueue. Long HTTP calls never occupy a source-sync transaction/job.
// Admission is fenced in PostgreSQL; slow model calls do not serialize source-sync or the other AI slots.
func (s *Store) Run(ctx context.Context, onError func(error)) {
tick := time.NewTicker(time.Second)
defer tick.Stop()
var nextScan, lastError time.Time
if !s.valid() {
if onError != nil {
onError(ErrUnavailable)
}
return
}
var lock sync.Mutex
var lastError time.Time
report := func(err error) {
if err != nil && ctx.Err() == nil && time.Since(lastError) > 30*time.Second {
if err == nil || ctx.Err() != nil {
return
}
lock.Lock()
defer lock.Unlock()
if time.Since(lastError) > 30*time.Second {
lastError = time.Now()
if onError != nil {
onError(err)
}
}
}
for {
if ctx.Err() != nil {
return
}
if time.Now().After(nextScan) {
scanCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
_, err := s.ScanAutomatic(scanCtx)
cancel()
report(err)
nextScan = time.Now().Add(15 * time.Second)
}
_, err := s.ProcessOne(ctx)
var workers sync.WaitGroup
for i := 0; i < s.concurrency(); i++ {
workers.Add(1)
go func() {
defer workers.Done()
for ctx.Err() == nil {
worked, err := s.ProcessOne(ctx)
report(err)
if !worked || err != nil {
select {
case <-ctx.Done():
return
case <-time.After(time.Second):
}
}
}
}()
}
defer workers.Wait()
tick := time.NewTicker(10 * time.Second)
defer tick.Stop()
scan := func() {
scanCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
_, err := s.ScanAutomatic(scanCtx)
report(err)
_, err = s.pool.Exec(scanCtx, `INSERT INTO qa_ops_ai_runtime(tenant_key,heartbeat_at)VALUES($1,clock_timestamp())ON CONFLICT(tenant_key)DO UPDATE SET heartbeat_at=EXCLUDED.heartbeat_at`, s.tenant)
report(err)
}
scan()
for {
select {
case <-ctx.Done():
return
case <-tick.C:
scan()
}
}
}
+1
View File
@@ -12,6 +12,7 @@ import (
)
type Options struct {
Concurrency int
KeyFile string
AllowPrivate bool
DNSOverTLS bool
@@ -1,10 +1,13 @@
package qaopsmirror
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/jackc/pgx/v5/pgxpool"
"io"
"knowledge-governance/internal/dobotaiops"
pg "knowledge-governance/internal/platform/postgres"
"knowledge-governance/internal/qaopsai"
@@ -16,6 +19,7 @@ import (
"sync"
"sync/atomic"
"testing"
"time"
)
func TestAIBatchManualRetryKeepsCumulativeAttemptsAndFixedDenominator(t *testing.T) {
@@ -228,7 +232,8 @@ func newAIMatrix(t *testing.T, tenant string, handler func(http.ResponseWriter,
var body struct {
Messages []struct{ Content string } `json:"messages"`
}
if json.NewDecoder(r.Body).Decode(&body) != nil || len(body.Messages) != 2 {
rawBody, readErr := io.ReadAll(r.Body)
if readErr != nil || json.Unmarshal(rawBody, &body) != nil || len(body.Messages) != 2 {
t.Error("invalid synthetic request")
w.WriteHeader(400)
return
@@ -238,6 +243,7 @@ func newAIMatrix(t *testing.T, tenant string, handler func(http.ResponseWriter,
return
}
calls.Add(1)
r.Body = io.NopCloser(bytes.NewReader(rawBody))
if handler != nil {
handler(w, r)
return
@@ -279,6 +285,221 @@ func (m aiMatrix) batch(t *testing.T, nonce string) qaopsai.Batch {
}
return batch
}
func TestAIRunnerActuallyDispatchesFourConcurrentRequests(t *testing.T) {
entered := make(chan struct{}, 8)
release := make(chan struct{})
var once sync.Once
m := newAIMatrix(t, "fixture-ai-runner-slots", func(w http.ResponseWriter, r *http.Request) {
entered <- struct{}{}
<-release
writeAICompletion(w, `{"question_chinese":"MG400 如何连接?"}`)
})
seedParallelAIWork(t, m)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { m.ai.Run(ctx, nil); close(done) }()
defer func() { once.Do(func() { close(release) }); cancel(); <-done }()
count := 0
timer := time.NewTimer(2 * time.Second)
defer timer.Stop()
loop:
for count < 4 {
select {
case <-entered:
count++
case <-timer.C:
break loop
}
}
if count != 4 {
t.Fatalf("actual worker runner is still serial: concurrent=%d", count)
}
}
func seedParallelAIWork(t *testing.T, m aiMatrix) {
t.Helper()
ctx := context.Background()
entries := []dobotaiops.MirrorRecord{}
ids := []string{}
for i, word := range []string{"Alpha", "Bravo", "Charlie", "Delta", "Echo"} {
id := fmt.Sprintf("parallel-record-%d", i)
entry := fixtureEntry(id, "fixture answer")
var wire map[string]any
_ = json.Unmarshal(entry.Payload, &wire)
wire["question"] = "How do I connect MG400? " + word
entry.Payload, _ = json.Marshal(wire)
entries = append(entries, entry)
ids = append(ids, id)
}
var seedJob string
if m.pool.QueryRow(ctx, `SELECT id FROM jobs WHERE type=$1 AND state='running'`, m.master.SyncJobType()).Scan(&seedJob) != nil {
t.Fatal("seed lease unavailable")
}
if e := pg.NewStore(m.pool).Complete(ctx, seedJob, "fixture-sync-worker", time.Now()); e != nil {
t.Fatal(e)
}
job := claimMirrorJob(t, m.master, pg.NewStore(m.pool), "parallel-seed")
if e := m.master.HandleSync(ctx, *job, func(context.Context) (Source, error) { return &fixtureSource{rows: entries}, nil }); e != nil {
t.Fatal(e)
}
preview, e := m.ai.Preview(ctx, qaopsai.Scope{Kind: "translation", IDs: ids}, "fixture-admin")
if e != nil || preview.Eligible != 5 {
t.Fatal("five unique inputs unavailable", e, preview.Eligible)
}
if _, e = m.ai.Start(ctx, preview.ID, strings.Repeat("parallel", 4), "fixture-admin"); e != nil {
t.Fatal(e)
}
}
func TestAIParallelClaimsUseFourSlotsWithoutDuplicatingOrExceedingLimit(t *testing.T) {
entered := make(chan struct{}, 8)
release := make(chan struct{})
var once sync.Once
m := newAIMatrix(t, "fixture-ai-four-slots", func(w http.ResponseWriter, r *http.Request) {
entered <- struct{}{}
<-release
writeAICompletion(w, `{"question_chinese":"MG400 如何连接?"}`)
})
defer once.Do(func() { close(release) })
ctx := context.Background()
seedParallelAIWork(t, m)
var group sync.WaitGroup
failures := make(chan error, 5)
for i := 0; i < 5; i++ {
group.Add(1)
go func() {
defer group.Done()
_, err := m.ai.ProcessOne(ctx)
if err != nil {
failures <- err
}
}()
}
seen := 0
timeout := time.NewTimer(1500 * time.Millisecond)
loop:
for seen < 4 {
select {
case <-entered:
seen++
case <-timeout.C:
break loop
}
}
timeout.Stop()
if seen != 4 {
t.Errorf("wanted four concurrent model requests before any completes; got %d", seen)
}
select {
case <-entered:
t.Error("exceeded four global slots")
case <-time.After(100 * time.Millisecond):
}
once.Do(func() { close(release) })
group.Wait()
close(failures)
for err := range failures {
t.Error(err)
}
if seen == 4 {
var running, queued, outputs int
if m.pool.QueryRow(ctx, `SELECT (SELECT count(*)FROM qa_ops_ai_work WHERE tenant_key=$1 AND state='running'),(SELECT count(*)FROM qa_ops_ai_work WHERE tenant_key=$1 AND state='queued'),(SELECT count(*)FROM qa_ops_ai_outputs WHERE tenant_key=$1)`, m.tenant).Scan(&running, &queued, &outputs) != nil || running != 0 || queued != 1 || outputs != 4 {
t.Fatal("slot completion lost/duplicated work", running, queued, outputs)
}
}
}
func TestAITruncationRetriesExpandBudgetAndStopAfterThreeAttempts(t *testing.T) {
budgets := []int{}
m := newAIMatrix(t, "fixture-ai-truncation-budget", func(w http.ResponseWriter, r *http.Request) {
var req struct {
Max int `json:"max_tokens"`
}
if json.NewDecoder(r.Body).Decode(&req) != nil {
t.Error("request decode")
}
budgets = append(budgets, req.Max)
if len(budgets) < 3 {
_ = json.NewEncoder(w).Encode(map[string]any{"model": "fixture", "choices": []any{map[string]any{"finish_reason": "length", "message": map[string]string{"content": ""}}}})
return
}
writeAICompletion(w, `{"question_chinese":"MG400 如何连接?"}`)
})
batch := m.batch(t, "t")
ctx := context.Background()
for i := 0; i < 3; i++ {
if _, err := m.pool.Exec(ctx, `UPDATE qa_ops_ai_work SET available_at=clock_timestamp()-interval '1 second'WHERE tenant_key=$1`, m.tenant); err != nil {
t.Fatal(err)
}
if worked, err := m.ai.ProcessOne(ctx); err != nil || !worked {
t.Fatal("bounded retry did not execute", err)
}
}
if fmt.Sprint(budgets) != "[4096 8192 16384]" {
t.Fatal("truncation budget did not grow", budgets)
}
current, err := m.ai.GetBatch(ctx, batch.ID)
if err != nil || current.Succeeded != 1 || current.Total != 1 || m.calls.Load() != 3 {
t.Fatal("retry denominator or completion", err)
}
}
func TestAIParallelSuccessCannotClearAnotherRequestsRateLimit(t *testing.T) {
entered := make(chan struct{}, 4)
release := make(chan struct{})
var once sync.Once
var calls atomic.Int32
m := newAIMatrix(t, "fixture-ai-shared-cooldown", func(w http.ResponseWriter, r *http.Request) {
n := calls.Add(1)
entered <- struct{}{}
if n == 4 {
w.Header().Set("Retry-After", "45")
w.WriteHeader(429)
return
}
<-release
writeAICompletion(w, `{"question_chinese":"MG400 如何连接?"}`)
})
defer once.Do(func() { close(release) })
seedParallelAIWork(t, m)
ctx := context.Background()
var group sync.WaitGroup
errs := make(chan error, 4)
for i := 0; i < 4; i++ {
group.Add(1)
go func() { defer group.Done(); _, err := m.ai.ProcessOne(ctx); errs <- err }()
}
for i := 0; i < 4; i++ {
select {
case <-entered:
case <-time.After(2 * time.Second):
t.Fatal("four parallel slots not reached")
}
}
deadline := time.Now().Add(2 * time.Second)
remaining := 0.0
for time.Now().Before(deadline) {
if m.pool.QueryRow(ctx, `SELECT EXTRACT(EPOCH FROM next_request_at-clock_timestamp())::double precision FROM qa_ops_ai_runtime WHERE tenant_key=$1`, m.tenant).Scan(&remaining) == nil && remaining > 40 {
break
}
time.Sleep(time.Millisecond * 10)
}
once.Do(func() { close(release) })
group.Wait()
close(errs)
for err := range errs {
if err != nil {
t.Fatal(err)
}
}
if m.pool.QueryRow(ctx, `SELECT EXTRACT(EPOCH FROM next_request_at-clock_timestamp())::double precision FROM qa_ops_ai_runtime WHERE tenant_key=$1`, m.tenant).Scan(&remaining) != nil || remaining < 40 {
t.Fatal("success cleared shared provider cooldown", remaining)
}
if worked, err := m.ai.ProcessOne(ctx); err != nil || worked || calls.Load() != 4 {
t.Fatal("new request bypassed shared rate limit", err)
}
}
func TestAIManualBatchPauseResumeKeepsSharedWorkAndActionReplaysSafe(t *testing.T) {
m := newAIMatrix(t, "fixture-ai-pause", nil)
ctx := context.Background()
+10
View File
@@ -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)
}
}
+4
View File
@@ -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,101 @@
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"`
Week string `json:"week,omitempty"`
}
type DepartmentStatisticsSnapshot struct {
Regions []qaopsorg.RegionDefinition `json:"regions"`
qaopsorg.DepartmentStatistics
Organization dobotaiops.OrganizationVersion `json:"organization"`
Period string `json:"period"`
Month string `json:"month"`
Week string `json:"week"`
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,129 @@
package qaopsmirror
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qaopsorg"
"strconv"
"time"
)
func (q DepartmentStatisticsQuery) Bounds(now time.Time) (*time.Time, time.Time, error) {
if q.Period == "all" && q.Month == "" && q.Week == "" {
return nil, now, nil
}
if q.Period == "week" && q.Month == "" {
if len(q.Week) != 8 || q.Week[4:6] != "-W" || q.Week[6] < '0' || q.Week[6] > '9' || q.Week[7] < '0' || q.Week[7] > '9' {
return nil, time.Time{}, dobotaiops.ErrInvalidQuery
}
year, ey := strconv.Atoi(q.Week[:4])
week, ew := strconv.Atoi(q.Week[6:])
if ey != nil || ew != nil || year < 2000 || year > 9998 || week < 1 || week > 53 {
return nil, time.Time{}, dobotaiops.ErrInvalidQuery
}
jan4 := time.Date(year, time.January, 4, 0, 0, 0, 0, time.FixedZone("Asia/Shanghai", 8*3600))
start := jan4.AddDate(0, 0, -(int(jan4.Weekday())+6)%7+7*(week-1))
actualYear, actualWeek := start.ISOWeek()
if actualYear != year || actualWeek != week || start.After(now) {
return nil, time.Time{}, dobotaiops.ErrInvalidQuery
}
end := start.AddDate(0, 0, 7)
if end.After(now) {
end = now
}
return &start, end, nil
}
if q.Period != "month" || q.Week != "" {
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, q.Week})
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, Week: q.Week, 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
}
@@ -0,0 +1,56 @@
package qaopsmirror
import (
"context"
"encoding/json"
"knowledge-governance/internal/qaopsorg"
"testing"
"time"
)
func TestDepartmentStatisticsNaturalWeekBoundaryAndCacheIsolation(t *testing.T) {
p := mirrorFixture(t)
s := NewStore(p, "fixture-department-natural-week")
now, _ := time.Parse(time.RFC3339, "2026-10-21T11:00:00+08:00")
ctx := context.Background()
dir := qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "root", Name: "Fixture center"}, {ID: "child", ParentID: "root", Name: "Fixture department"}}, People: []qaopsorg.Person{{ID: "p1", Name: "Fixture person", DepartmentIDs: []string{"root", "child"}}}}
if _, err := qaopsorg.NewStore(p, s.tenant).ReplaceDirectory(ctx, qaopsorg.Import{Source: "weekly_report_snapshot", SyncedAt: time.Now(), Complete: true, Directory: dir}); err != nil {
t.Fatal(err)
}
for i, stamp := range []string{"2026-10-11T23:59:59+08:00", "2026-10-12T00:00:00+08:00", "2026-10-18T23:59:59+08:00", "2026-10-19T00:00:00+08:00"} {
_, err := 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,'non-business boundary fixture','succeeded','{"staff_id":"p1"}',repeat('b',64),jsonb_build_object('id',$2::text))`, s.tenant, "boundary-"+time.Date(2000, 1, i+1, 0, 0, 0, 0, time.UTC).Format("02"), stamp)
if err != nil {
t.Fatal(err)
}
}
read := func(week string) DepartmentStatisticsResult {
var q DepartmentStatisticsQuery
raw, _ := json.Marshal(map[string]string{"period": "week", "week": week})
_ = json.Unmarshal(raw, &q)
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
r, err := s.ReadDepartmentStatistics(ctx, q, now)
if err != nil {
t.Fatal(err)
}
if r.State == "ready" {
return r
}
time.Sleep(time.Millisecond)
}
t.Fatal("background natural week did not finish")
return DepartmentStatisticsResult{}
}
first, second := read("2026-W42"), read("2026-W43")
if first.CacheKey == second.CacheKey || first.Snapshot.TotalVisits != 2 || second.Snapshot.TotalVisits != 1 {
t.Fatalf("week boundaries/cache contaminated: first=%+v second=%+v", first, second)
}
for _, r := range first.Snapshot.Rows {
if r.Visits != 2 || r.Visitors != 1 || r.TotalPeople != 1 {
t.Fatalf("current branch person was double-counted: %+v", r)
}
}
if repeated := read("2026-W42"); !repeated.CacheHit || repeated.Snapshot.GeneratedAt != first.Snapshot.GeneratedAt {
t.Fatal("same natural week was not cached")
}
}
@@ -0,0 +1,35 @@
package qaopsmirror
import (
"encoding/json"
"testing"
"time"
)
func TestDepartmentStatisticsNaturalWeekUsesBeijingISOCalendar(t *testing.T) {
now, _ := time.Parse(time.RFC3339, "2026-10-21T11:00:00+08:00")
for _, tc := range []struct{ raw, start, end string }{
{`{"period":"week","week":"2026-W43"}`, "2026-10-19T00:00:00+08:00", "2026-10-21T11:00:00+08:00"},
{`{"period":"week","week":"2026-W42"}`, "2026-10-12T00:00:00+08:00", "2026-10-19T00:00:00+08:00"},
{`{"period":"week","week":"2020-W53"}`, "2020-12-28T00:00:00+08:00", "2021-01-04T00:00:00+08:00"},
} {
var q DepartmentStatisticsQuery
if json.Unmarshal([]byte(tc.raw), &q) != nil {
t.Fatal("invalid test input")
}
start, end, err := q.Bounds(now)
if err != nil || start == nil || start.Format(time.RFC3339) != tc.start || end.Format(time.RFC3339) != tc.end {
t.Fatalf("natural week bounds incorrect: %s start=%v end=%v error=%v", tc.raw, start, end, err)
}
}
}
func TestDepartmentStatisticsRejectsInvalidMixedOrFutureWeeks(t *testing.T) {
now, _ := time.Parse(time.RFC3339, "2026-10-21T11:00:00+08:00")
for _, raw := range []string{`{"period":"week"}`, `{"period":"week","week":"2021-W53"}`, `{"period":"week","week":"2026-W00"}`, `{"period":"week","week":"2026-W44"}`, `{"period":"week","week":"2026-W1"}`, `{"period":"week","week":"2026-W+1"}`, `{"period":"week","week":"1999-W01"}`, `{"period":"week","week":"2026-W43","month":"2026-10"}`, `{"period":"all","week":"2026-W43"}`, `{"period":"month","month":"2026-10","week":"2026-W43"}`} {
var q DepartmentStatisticsQuery
_ = json.Unmarshal([]byte(raw), &q)
if _, _, err := q.Bounds(now); err == nil {
t.Fatal("invalid period accepted", raw)
}
}
}
+5 -4
View File
@@ -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)
}
}
+13 -1
View File
@@ -27,7 +27,7 @@ it('shows open-ended automatic queue counts without fabricating a percentage', (
query={{ start: '2026-10-05T00:00:00Z', end: '2026-10-12T00:00:00Z', keyword: 'executed-query', cursor: '' }}
/>
)
for (const value of ['补缺评估', '补缺中文翻译', '当前已执行筛选', '后台任务', '排队 2', '执行 1', '失败 1'])
for (const value of ['AI分析', '当前已执行筛选', '后台任务', '排队 2', '执行 1', '失败 1'])
expect(html).toContain(value)
expect(html).not.toContain('100%')
})
@@ -109,3 +109,15 @@ it('renders original evidence quotes, actual model/version and applied-versus-sk
])
expect(html).toContain(value)
})
it('uses one AI分析 entry for combined evaluation and Chinese translation', () => {
const html = renderToStaticMarkup(
<QAAIWorkbench
initial={status}
query={{ start: '2026-10-05T00:00:00Z', end: '2026-10-12T00:00:00Z', keyword: '', cursor: '' }}
/>
)
expect([...html.matchAll(/>AI分析<\/button>/g)]).toHaveLength(1)
expect(html).not.toContain('补缺评估')
expect(html).not.toContain('补缺中文翻译')
})
+36 -41
View File
@@ -56,23 +56,27 @@ export function QAAIRequest({
disabled,
onQueued,
}: {
scope: AIScope | null
scope: Omit<AIScope, 'kind'> | null
label: string
disabled?: boolean
onQueued?: () => void
}) {
const [preview, setPreview] = useState<AIPreview | null>(null),
const [preview, setPreview] = useState<AIPreview[] | null>(null),
[nonce, setNonce] = useState(''),
[busy, setBusy] = useState(false),
[error, setError] = useState<string | null>(null),
[message, setMessage] = useState<string | null>(null)
const queued = useRef(new Set<AIKind>())
const prepare = async () => {
if (!scope) return
setBusy(true)
setError(null)
setMessage(null)
try {
setPreview(await previewAI(scope))
setPreview(
await Promise.all((['evaluation', 'translation'] as const).map((kind) => previewAI({ ...scope, kind })))
)
queued.current.clear()
setNonce(newOperationID())
} catch (reason) {
setError(errorText(reason))
@@ -85,12 +89,17 @@ export function QAAIRequest({
setBusy(true)
setError(null)
try {
await startAI(preview.id, nonce)
for (const part of preview) {
if (part.eligible === 0 || queued.current.has(part.kind)) continue
await startAI(part.id, nonce + ':' + part.kind)
queued.current.add(part.kind)
}
setPreview(null)
setMessage('批次已持久保存;关闭页面后继续执行。')
setMessage('AI分析任务已持久保存;字段分析与中文翻译按实际缺口执行,关闭页面后继续。')
onQueued?.()
} catch (reason) {
setError(errorText(reason))
setError((queued.current.size ? '部分任务已创建,重试只补未确认部分,不会重复入队。' : '') + errorText(reason))
if (queued.current.size) onQueued?.()
} finally {
setBusy(false)
}
@@ -102,17 +111,23 @@ export function QAAIRequest({
</button>
{preview ? (
<span className="qa-ai-confirm" role="dialog" aria-label={label + '范围确认'}>
<strong>{`${aiKindLabels[preview.kind]}:范围 ${preview.scope_total} 条,实际待补 ${preview.eligible} 条,跳过 ${preview.skipped} 条。`}</strong>
<strong>AI分析:仅补当前范围的空白字段和缺失中文翻译</strong>
{preview.map((part) => (
<small key={part.kind}>
{aiKindLabels[part.kind]}:范围 {part.scope_total} 条,待补 {part.eligible} 条,跳过 {part.skipped} 条。
</small>
))}
<small>
{preview.kind === 'evaluation'
? '只向已配置模型发送待补记录的问题、答案及获准引用,不发送人员/部门信息。'
: '只发送待补记录的原始问题,不翻译或发送答案。'}
仅补空白,不覆盖既有标签或人工结论。
两类任务独立计数,同一记录可能同时需要两项。仅发送问题、分析所需答案及已有引用片段,不发送人员/部门;不覆盖非空标签或人工结论。
</small>
<button type="button" disabled={busy} onClick={() => setPreview(null)}>
取消
</button>
<button type="button" disabled={busy || preview.eligible === 0} onClick={() => void confirm()}>
<button
type="button"
disabled={busy || preview.every((part) => part.eligible === 0)}
onClick={() => void confirm()}
>
确认创建后台批次
</button>
</span>
@@ -192,6 +207,7 @@ export function QAAIWorkbench({
const callbacks = useRef({ onStatus, onRecordChanged })
callbacks.current = { onStatus, onRecordChanged }
const previous = useRef<Map<string, string> | null>(null)
const statusSignature = useRef('')
useEffect(() => {
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout> | undefined
@@ -202,7 +218,11 @@ export function QAAIWorkbench({
if (controller.signal.aborted) return
setStatus(next)
setError(null)
callbacks.current.onStatus?.(next)
const signature = JSON.stringify(next)
if (signature !== statusSignature.current) {
statusSignature.current = signature
callbacks.current.onStatus?.(next)
}
if (previous.current) {
for (const task of next.recent_tasks) {
if (
@@ -245,27 +265,13 @@ export function QAAIWorkbench({
}
}
const ready = Boolean(status?.settings.verification === 'verified' && status.settings.storage_ready)
const scope = (kind: AIKind): AIScope | null =>
query ? { kind, start: query.start, end: query.end, keyword: query.keyword } : null
const scope = query ? { start: query.start, end: query.end, keyword: query.keyword } : null
const scopeKey = query ? `${query.start}:${query.end}:${query.keyword}` : 'none'
return (
<section className="qa-ai-workbench" aria-label="问答后台任务">
<div className="qa-ai-actions">
<span>当前已执行筛选</span>
<QAAIRequest
key={'evaluation:' + scopeKey}
scope={scope('evaluation')}
label="补缺评估"
disabled={!ready}
onQueued={refresh}
/>
<QAAIRequest
key={'translation:' + scopeKey}
scope={scope('translation')}
label="补缺中文翻译"
disabled={!ready}
onQueued={refresh}
/>
<QAAIRequest key={scopeKey} scope={scope} label="AI分析" disabled={!ready} onQueued={refresh} />
{status ? (
<small>
{status.worker_ready ? '执行器在线' : '执行器未在线,任务会持久保留'}
@@ -490,18 +496,7 @@ export function QAAIRecordEvidence({
return (
<>
<div className="qa-ai-actions">
<QAAIRequest
key={recordID + ':evaluation'}
scope={{ kind: 'evaluation', ids: [recordID] }}
label="本条补缺评估"
onQueued={refresh}
/>
<QAAIRequest
key={recordID + ':translation'}
scope={{ kind: 'translation', ids: [recordID] }}
label="本条补缺中文翻译"
onQueued={refresh}
/>
<QAAIRequest key={recordID} scope={{ ids: [recordID] }} label="AI分析" onQueued={refresh} />
</div>
{error ? (
<p role="alert" className="error-banner">
+23
View File
@@ -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)
+67 -31
View File
@@ -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}>
问题统计看板
+31
View File
@@ -0,0 +1,31 @@
import { it, expect } from 'vitest'
import { renderToStaticMarkup } from 'react-dom/server'
import { DepartmentStatisticsView, QARegionalStatistics } from './QADepartmentStatistics'
import { parseDepartmentStatistics } from './qaDepartmentStatistics'
import { departmentStatisticsFixture } from './qaDepartmentStatistics.fixture'
it('offers all, natural-month and natural-week scopes and never switches the selected-department action to a second mapping page', () => {
const html = renderToStaticMarkup(<QARegionalStatistics />)
for (const label of ['按累计统计', '按自然月统计', '按自然周统计', '绑定选中部门']) expect(html).toContain(label)
expect(html).not.toContain('设置选中部门的区域')
expect(html).not.toContain('返回部门统计')
})
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('总人数')
})
+451
View File
@@ -0,0 +1,451 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import type { DepartmentStatisticsSnapshot, DepartmentStatisticsQuery } from './qaDepartmentStatistics'
import { fetchDepartmentStatistics } from './qaDepartmentStatistics'
import { departmentTree, selectDepartmentBranch, subtreeIDs, defaultDepartmentCollapsed } from './qaRegionSelection'
import { currentQAWeek, qaWeek } from './qaWeeks'
import { bindOrganizationDepartments } from './qaOrg'
import type { RegionDefinition } from './qaOrg'
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 ?? defaultDepartmentCollapsed(p.data.rows),
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 DepartmentRegionBinding({
regions,
selectedCount,
disabled,
onBind,
}: {
regions: RegionDefinition[]
selectedCount: number
disabled: boolean
onBind: (id: string) => void
}) {
const [target, setTarget] = useState('')
useEffect(() => {
if (target && !regions.some((r) => r.id === target)) setTarget('')
}, [regions, target])
return (
<div className="qa-department-binding" aria-label="就地绑定部门区域">
<span>已勾选 {selectedCount} 个部门</span>
<select
aria-label="绑定目标区域"
value={target}
disabled={disabled || !selectedCount}
onChange={(e) => setTarget(e.target.value)}
>
<option value="">选择绑定区域</option>
{regions.map((r) => (
<option key={r.id} value={r.id}>
{r.name}
</option>
))}
</select>
<button
type="button"
disabled={disabled || !selectedCount || !regions.some((r) => r.id === target)}
onClick={() => onBind(target)}
>
绑定选中部门
</button>
</div>
)
}
const currentWeekValue = () => {
const w = currentQAWeek()
return `${w.year}-W${String(w.week).padStart(2, '0')}`
}
export function QARegionalStatistics({ onSaved }: { onSaved?: () => void } = {}) {
const [period, setPeriod] = useState<'all' | 'month' | 'week'>('all'),
[month, setMonth] = useState(currentMonth),
[week, setWeek] = useState(currentWeekValue),
[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(''),
[binding, setBinding] = useState(false),
[bindingError, setBindingError] = useState(''),
[bindingNotice, setBindingNotice] = useState(''),
[catalogDirty, setCatalogDirty] = useState(false)
const key = useRef(''),
condition = useRef(''),
collapsedDirectory = useRef(''),
bindingRequest = useRef<AbortController | null>(null),
query = useMemo<DepartmentStatisticsQuery>(
() =>
period === 'all'
? { period: 'all' }
: period === 'month'
? { period: 'month', month }
: { period: 'week', week },
[period, month, week]
)
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)))
if (collapsedDirectory.current !== fresh.organization.directory_id) {
setCollapsed(defaultDepartmentCollapsed(fresh.rows))
collapsedDirectory.current = fresh.organization.directory_id
} else 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])
const invalidateOrganization = () => {
setData(null)
key.current = ''
setReload((v) => v + 1)
onSaved?.()
}
useEffect(() => () => bindingRequest.current?.abort(), [])
const bind = async (regionID: string) => {
if (!data || busy || binding || catalogDirty) return
const controller = new AbortController()
bindingRequest.current = controller
setBinding(true)
setBindingError('')
setBindingNotice('')
try {
await bindOrganizationDepartments(
{ directory_id: data.organization.directory_id, revision_id: data.organization.revision_id },
selected,
regionID,
controller.signal
)
if (controller.signal.aborted) return
setBindingNotice(
`已绑定 ${selected.length} 个部门至 ${data.regions.find((r) => r.id === regionID)?.name ?? '所选区域'},已独立读回保存结果`
)
setSelected([])
invalidateOrganization()
} catch (e) {
if (!controller.signal.aborted)
setBindingError(e instanceof Error ? e.message : '绑定失败,未将未确认结果标为成功')
} finally {
if (!controller.signal.aborted) setBinding(false)
}
}
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)}>
区域设置
</button>
</div>
</header>
<aside
className="qa-region-settings-panel"
hidden={!settings}
role="dialog"
aria-modal="false"
aria-label="区域设置面板"
>
<header>
<h3>区域设置</h3>
<button type="button" onClick={() => setSettings(false)}>
关闭设置
</button>
</header>
<div className="qa-region-settings-content">
<QARegions open={settings} onSaved={() => invalidateOrganization()} onDirtyChange={setCatalogDirty} />
</div>
</aside>
<div>
<div className="qa-department-filters">
<label>
统计范围
<select
aria-label="部门统计范围"
value={period}
onChange={(e) => setPeriod(e.target.value as 'all' | 'month' | 'week')}
>
<option value="all">按累计统计</option>
<option value="month">按自然月统计</option>
<option value="week">按自然周统计</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}
{period === 'week' ? (
<label>
统计周次(北京时间周一至周日)
<input
aria-label="部门统计周次"
type="week"
min="2000-W01"
max={currentWeekValue()}
value={week}
onChange={(e) => setWeek(e.target.value)}
/>
<small>
{(() => {
try {
return qaWeek(Number(week.slice(0, 4)), Number(week.slice(6))).label
} catch {
return '请选择有效自然周'
}
})()}
</small>
</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>
<DepartmentRegionBinding
regions={data?.regions ?? []}
selectedCount={selected.length}
disabled={busy || binding || settings || catalogDirty}
onBind={(id) => void bind(id)}
/>
<button type="button" disabled={!selected.length} onClick={() => setSelected([])}>
取消勾选
</button>
</div>
{catalogDirty ? <p className="qa-ops-muted">区域设置有未保存修改,请先保存或放弃后再绑定部门。</p> : null}
{bindingError ? (
<p role="alert" className="error-banner">
{bindingError}
</p>
) : null}
{bindingNotice ? <p role="status">{bindingNotice}</p> : null}
<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>
)
}
+6 -1
View File
@@ -15,7 +15,12 @@ export function QAMirrorSyncView(p: ViewProps) {
return (
<section className="qa-mirror-sync" aria-label="问答同步状态">
<div className="qa-mirror-sync-line">
<button type="button" onClick={p.onSync} disabled={p.submitting || !s?.worker_ready || active}>
<button
className="qa-query-action"
type="button"
onClick={p.onSync}
disabled={p.submitting || !s?.worker_ready || active}
>
{p.submitting ? '正在入队…' : active ? '后台同步中…' : '立即同步'}
</button>
</div>
+43 -5
View File
@@ -1,3 +1,5 @@
// @ts-expect-error The test runner provides Node; the browser bundle intentionally omits @types/node.
import { readFileSync } from 'node:fs'
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, expect, it, vi } from 'vitest'
import { QAOperationsTabs, QAOperationsView } from './QAOperations'
@@ -101,12 +103,13 @@ describe('QA operations workbench', () => {
expect(html).toContain('数据源有待审核的安全告警')
expect(html).toContain('fixture real read failure')
})
it('keeps a name-only person summary with the original available separately', () => {
it('removes workflow personnel from details while preserving the record data', () => {
const detail = { ...item, trigger_person: JSON.stringify({ name: '示例姓名', unionId: 'fixture-union' }) }
const html = renderToStaticMarkup(<QAOperationsView {...props} detail={detail} />)
expect(html).toContain('<dd>示例姓名</dd>')
expect(html).toContain('原始人员信息')
expect(html).toContain('fixture-union')
const drawer = html.slice(html.indexOf('<aside'))
expect(drawer).not.toContain('示例姓名')
expect(drawer).not.toContain('原始人员信息')
expect(drawer).not.toContain('fixture-union')
})
it('provides a row-level detail target and categorical color tags without adding business columns', () => {
const html = renderToStaticMarkup(<QAOperationsView {...props} />)
@@ -117,7 +120,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('部门/区域保留源快照')
@@ -182,3 +185,38 @@ describe('QA operations workbench', () => {
expect(restored.activeTab).toBe('qaops')
})
})
it('opens a modeless right drawer with fixed leading quality fields and no redundant organization/personnel details', () => {
const html = renderToStaticMarkup(<QAOperationsView {...props} detail={{ ...item, record_origin: 'dobotai_2_0' }} />)
const drawer = html.slice(html.indexOf('<aside'))
expect(html).not.toContain('qa-ops-backdrop')
expect(drawer).toContain('aria-modal="false"')
expect(drawer).toContain('qa-detail-quality')
const labels = ['是否覆盖', '是否正确', '产品分类', '问题类型', '根因分析']
for (const label of labels) expect(drawer).toContain(label)
expect(drawer.indexOf('根因分析')).toBeLessThan(drawer.indexOf('原始问题'))
for (const label of [
'<dt>区域</dt>',
'当前组织关联',
'当前通讯录部门/区域',
'组织版本',
'源端组织快照',
'记录来源',
'问答状态',
'流程触发人员信息',
'原始人员信息',
])
expect(drawer).not.toContain(label)
})
it('names the ledger explicitly as 问题流水表', () => {
const html = renderToStaticMarkup(<QAOperationsTabs view="records" onChange={vi.fn()} />)
expect(html).toContain('>问题流水表</button>')
})
it('uses matching query/sync action sizing and keeps synchronization status outside the button baseline', () => {
const css = readFileSync(new URL('./qaOps.css', import.meta.url), 'utf8')
expect(css).toContain('.qa-ops-query .qa-query-action')
expect(css).toMatch(/\.qa-ops-query \.qa-query-action\s*\{[^}]*width:\s*96px/)
expect(css).toMatch(/\.qa-ops-query \.qa-mirror-sync-line\s*\{[^}]*margin-bottom:\s*0/)
})
+98 -95
View File
@@ -4,13 +4,13 @@ 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 { ledgerWindow, ledgerCellPreview } from './qaLedgerRendering'
import { QARegionalStatistics } from './QADepartmentStatistics'
import { QADashboard } from './QADashboard'
import { QAWeekly } from './QAWeekly'
import { QAQualityEditor } from './QAQuality'
import { qaFieldColors, qaTagColumns } from './qaFieldColors'
import { qualityLabels } from './qaQuality'
import { usageLabels } from './qaUsage'
import { QAWeekPicker } from './QAWeekPicker'
import { QAAnswerMarkdown } from './QAAnswerMarkdown'
import { QAMirrorSync } from './QAMirrorSync'
@@ -24,9 +24,9 @@ export function QAOperationsTabs({ view, onChange }: { view: QAOpsView; onChange
<nav className="qa-region-tabs" aria-label="问答运营视图">
{(
[
['records', '问题流水'],
['records', '问题流水表'],
['dashboard', '问题统计看板'],
['regions', '区域配置'],
['regions', '区域统计'],
['weekly', '周报生成'],
] as const
).map(([id, label]) => (
@@ -58,12 +58,6 @@ const warningLabels: Record<string, string> = {
database_transport_unencrypted: '数据库连接未启用 TLS:上线前须完成传输安全审核',
}
const stamp = (value: string) => new Date(value).toLocaleString('zh-CN', { hour12: false })
const statusLabels: Record<string, string> = {
succeeded: '成功',
failed: '失败',
running: '处理中',
cancelled: '已取消',
}
const sourceCoverageLabels: Record<string, string> = { covered: '已覆盖', uncovered: '未覆盖' }
function tasksFor(item: QARecord, updates: AIWorkState[] | undefined) {
@@ -78,17 +72,21 @@ function tasksFor(item: QARecord, updates: AIWorkState[] | undefined) {
const QARow = memo(
function QARow({
item,
rowIndex,
tasks,
onSelect,
}: {
item: QARecord
rowIndex: number
tasks: AIWorkState[]
signature: string
onSelect: (id: string) => void
}) {
return (
<tr
className="qa-ops-record-row"
data-qa-row={item.id}
aria-rowindex={rowIndex}
onDoubleClick={(event) => {
if (!(event.target as HTMLElement).closest('button,a,input,select,textarea,summary')) onSelect(item.id)
}}
@@ -106,26 +104,55 @@ const QARow = memo(
className={qaTagColumns.has(key) ? 'qa-field-tag' : key === 'trigger_person' ? 'qa-person-name' : ''}
style={qaTagColumns.has(key) ? qaFieldColors(key, qaCellValue(item, key) ?? '—') : undefined}
>
{qaCellValue(item, key) ?? '—'}
{['answer', 'question', 'question_chinese', 'department'].includes(key)
? ledgerCellPreview(qaCellValue(item, key) ?? '—')
: (qaCellValue(item, key) ?? '—')}
</span>
</td>
))}
<td>
<button type="button" onClick={() => onSelect(item.id)} aria-label={`查看问答 ${item.id} 的详情`}>
详情
</button>
{item.quality ? <small className="qa-quality-state">{qualityLabels[item.quality.state]}</small> : null}
<QAAITaskBadges tasks={tasks} />
<div className="qa-ledger-actions">
<button type="button" onClick={() => onSelect(item.id)} aria-label={`查看问答 ${item.id} 的详情`}>
详情
</button>
{item.quality ? <small className="qa-quality-state">{qualityLabels[item.quality.state]}</small> : null}
<QAAITaskBadges tasks={tasks} />
</div>
</td>
</tr>
)
},
(before, after) =>
before.item === after.item && before.signature === after.signature && before.onSelect === after.onSelect
before.item === after.item &&
before.rowIndex === after.rowIndex &&
before.signature === after.signature &&
before.onSelect === after.onSelect
)
const ledgerColumnWidth = (key: string) =>
['answer', 'question', 'question_chinese'].includes(key)
? 320
: key === 'asked_at'
? 185
: key === 'department'
? 240
: key === 'root_cause'
? 155
: 125
export function QAOperationsView(props: ViewProps) {
const page = props.page
const scrollRef = useRef<HTMLDivElement>(null)
const [viewport, setViewport] = useState({ top: 0, height: 600 })
const visible = ledgerWindow(page?.items.length ?? 0, viewport.top, viewport.height)
useEffect(() => {
const element = scrollRef.current
if (!element) return
const observer = new ResizeObserver(() =>
setViewport({ top: Math.max(0, element.scrollTop - 40), height: element.clientHeight })
)
observer.observe(element)
return () => observer.disconnect()
}, [Boolean(page?.items.length)])
const columns = qaColumns
const updates = useMemo(() => {
const map = new Map<string, AIWorkState[]>()
@@ -145,7 +172,7 @@ export function QAOperationsView(props: ViewProps) {
{props.loading
? `正在读取全部问答…${props.progress ? `(${props.progress.loaded} / ${props.progress.total})` : ''}`
: page
? `共 ${page.total} 条 · 已展示 ${page.items.length} 条`
? `共 ${page.total} 条 · 已载入 ${page.items.length} 条`
: '尚未读取问答'}
</span>
<small className="qa-ops-muted">双击行查看详情</small>
@@ -167,8 +194,27 @@ export function QAOperationsView(props: ViewProps) {
</div>
) : null}
{page && page.items.length > 0 ? (
<div className="qa-ops-table-scroll" aria-label="问答表格滚动区" tabIndex={0}>
<table className="qa-ops-table">
<div
ref={scrollRef}
className="qa-ops-table-scroll"
aria-label="问答表格滚动区"
tabIndex={0}
onScroll={(event) => {
const element = event.currentTarget
setViewport({ top: Math.max(0, element.scrollTop - 40), height: element.clientHeight })
}}
>
<table
className="qa-ops-table"
aria-rowcount={page.items.length + 1}
style={{ width: qaColumns.reduce((sum, c) => sum + ledgerColumnWidth(c.key), 160) }}
>
<colgroup>
{qaColumns.map((c) => (
<col key={c.key} style={{ width: ledgerColumnWidth(c.key) }} />
))}
<col style={{ width: 160 }} />
</colgroup>
<thead>
<tr>
{columns.map(({ key, label }) => (
@@ -178,18 +224,29 @@ export function QAOperationsView(props: ViewProps) {
</tr>
</thead>
<tbody>
{page.items.map((item) => {
{visible.padTop > 0 ? (
<tr aria-hidden="true" className="qa-ledger-spacer">
<td colSpan={columns.length + 1} style={{ height: visible.padTop }} />
</tr>
) : null}
{page.items.slice(visible.start, visible.end).map((item, index) => {
const tasks = tasksFor(item, updates.get(item.id))
return (
<QARow
key={item.id}
item={item}
rowIndex={visible.start + index + 2}
tasks={tasks}
signature={JSON.stringify(tasks)}
onSelect={props.onSelect}
/>
)
})}
{visible.padBottom > 0 ? (
<tr aria-hidden="true" className="qa-ledger-spacer">
<td colSpan={columns.length + 1} style={{ height: visible.padBottom }} />
</tr>
) : null}
</tbody>
</table>
</div>
@@ -199,36 +256,13 @@ export function QAOperationsView(props: ViewProps) {
{showDrawer ? (
<>
<button
className="qa-ops-backdrop"
type="button"
onClick={props.onCloseDetail}
aria-label="关闭问答详情遮罩"
/>
<aside
className="qa-ops-drawer"
role="dialog"
aria-modal="true"
aria-modal="false"
aria-label="问答详情"
onKeyDown={(event) => {
if (event.key === 'Escape') props.onCloseDetail()
if (event.key === 'Tab') {
const buttons = Array.from(
event.currentTarget.querySelectorAll<HTMLElement>(
'button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), summary, [tabindex="0"]'
)
)
const first = buttons[0],
last = buttons[buttons.length - 1]
if (event.shiftKey && document.activeElement === first) {
event.preventDefault()
last?.focus()
}
if (!event.shiftKey && document.activeElement === last) {
event.preventDefault()
first?.focus()
}
}
}}
>
<header>
@@ -237,6 +271,18 @@ export function QAOperationsView(props: ViewProps) {
关闭详情
</button>
</header>
{detail ? (
<div className="qa-detail-quality" aria-label="固定质量字段">
{(['coverage', 'is_correct', 'product_category', 'problem_type', 'root_cause'] as const).map((key) => (
<div key={key} data-quality-field={key}>
<span>{qaColumns.find((column) => column.key === key)!.label}</span>
<strong className="qa-field-tag" style={qaFieldColors(key, qaCellValue(detail, key) ?? '—')}>
{qaCellValue(detail, key) ?? '—'}
</strong>
</div>
))}
</div>
) : null}
{props.detailLoading ? <p role="status">正在读取完整问答…</p> : null}
{props.detailError ? (
<p className="error-banner" role="alert">
@@ -258,55 +304,7 @@ export function QAOperationsView(props: ViewProps) {
{detail.department || '未匹配'}
{detail.organization?.department_origin === 'current_directory' ? '(当前通讯录补全)' : ''}
</dd>
<dt>区域</dt>
<dd>
{detail.region || '未配置/待核对'}
{detail.organization?.region_origin === 'current_directory' ? '(当前配置补全)' : ''}
</dd>
{detail.organization ? (
<>
<dt>当前组织关联</dt>
<dd>
{detail.organization.state === 'matched'
? '已关联'
: (usageLabels[detail.organization.state] ?? detail.organization.state)}
</dd>
<dt>当前通讯录部门/区域</dt>
<dd>
{detail.organization.departments.join(';') || '未匹配'} /{' '}
{detail.organization.region || '未配置或待核对'}
</dd>
<dt>组织版本</dt>
<dd>
{detail.organization.version.directory_id || '无完整目录'} /{' '}
{detail.organization.version.revision_id || '未保存区域配置'}
</dd>
<dt>源端组织快照</dt>
<dd>
{detail.organization.source_department || '空'} / {detail.organization.source_region || '空'}
</dd>
</>
) : null}
{detail.record_origin ? (
<>
<dt>记录来源</dt>
<dd>
{detail.record_origin === 'historical_excel'
? '历史 Excel 导入(原标注保留)'
: 'DobotAI 2.0 收录副本'}
;主表不随源同步覆盖或删除
</dd>
</>
) : null}
<dt>问答状态</dt>
<dd>{statusLabels[detail.status] ?? detail.status}</dd>
<dt>流程触发人员信息</dt>
<dd>{qaCellValue(detail, 'trigger_person') || '未记录'}</dd>
</dl>
<details>
<summary>原始人员信息</summary>
<pre>{detail.master_fields?.trigger_person ?? detail.trigger_person ?? '未记录'}</pre>
</details>
<h4>原始问题</h4>
<div className="qa-ops-full-text">{detail.question || '无文本问题'}</div>
<h4>AI答案</h4>
@@ -582,7 +580,7 @@ export function QAOperations() {
onChange={(e) => setDraft({ ...draft, keyword: e.target.value })}
/>
</label>
<button type="submit" disabled={loading}>
<button className="qa-query-action" type="submit" disabled={loading}>
查询
</button>
<QAMirrorSync
@@ -603,7 +601,12 @@ export function QAOperations() {
</>
) : null}
{view === 'regions' ? (
<QARegions />
<QARegionalStatistics
onSaved={() => {
setRevision((v) => v + 1)
setQualityRevision((v) => v + 1)
}}
/>
) : view === 'weekly' ? (
<QAWeekly query={query} />
) : view === 'dashboard' ? (
+1
View File
@@ -16,6 +16,7 @@ describe('manual quality operations', () => {
for (const value of ['人工复核', '保存并读回', '覆盖结论', '正确性', '复核理由', 'fixture-admin'])
expect(html).toContain(value)
expect(html).not.toContain('<script>')
expect(html).not.toContain('AI 评估未接入')
})
it('labels stale manual judgment as needing reconfirmation', () => {
const html = renderToStaticMarkup(
+1 -1
View File
@@ -196,7 +196,7 @@ export function QAQualityEditor({ recordId, quality, onSaved, onReload, dataset
</p>
) : null}
<p className="qa-ops-muted">
AI 评估未接入。自动规则、源端判断和人工结论独立保留;以下分类沿用正式标签,不自动猜测。复核人取登录身份。
模型建议、自动规则、源端判断和人工结论独立保留;以下分类沿用正式标签,人工结论优先。复核人取登录身份。
</p>
{error ? (
<div role="alert" className="error-banner">
+40 -35
View File
@@ -2,7 +2,7 @@ import { renderToStaticMarkup } from 'react-dom/server'
// @ts-expect-error The test runner provides Node; the browser bundle intentionally omits @types/node.
import { readFileSync } from 'node:fs'
import { describe, expect, it, vi } from 'vitest'
import { RegionMappingView } from './QARegions'
import { RegionCatalogView } from './QARegions'
import { parseOrganization } from './qaOrg'
const state = parseOrganization({
state: 'ready',
@@ -36,42 +36,47 @@ const props = {
state,
preview: null,
rules: state.rules,
selectedRegion: 'APAC',
search: '',
busy: false,
error: '',
notice: '',
dirty: false,
onRegion: vi.fn(),
onSearch: vi.fn(),
onToggle: vi.fn(),
onPreview: vi.fn(),
onSave: vi.fn(),
onReload: vi.fn(),
onRemoveMissing: vi.fn(),
}
describe('region mapping workbench', () => {
it('separates multiselect from bulk application and renders hierarchy and editable region names', () => {
describe('region catalog settings', () => {
it('uses a region-name list without a second department mapping page', () => {
const html = renderToStaticMarkup(<RegionCatalogView {...props} />)
expect(html).toContain('区域名称列表')
expect(html).toContain('保存区域设置')
expect(html).not.toContain('qa-region-table')
expect(html).not.toContain('批量归属')
expect(html).not.toContain('全选当前列表')
})
it('shows direct binding counts and enters local confirmation before removing a bound region', () => {
const regions = [
{ id: 'APAC', name: 'Assigned' },
{ id: 'spare', name: 'Spare' },
]
const html = renderToStaticMarkup(<RegionCatalogView {...props} regions={regions} />)
expect(html).toContain('删除区域 Spare')
expect(html).toContain('直接绑定 1 个部门')
expect(html).not.toMatch(/aria-label="删除区域 Assigned"[^>]*disabled=""/)
expect(html).not.toContain('确认删除')
})
it('shows editable saved region names but keeps department binding out of the settings list', () => {
const custom = {
...state,
regions: [{ id: 'APAC', name: '国外工业Amercia' }],
view: { ...state.view, regions: { APAC: 1 } },
}
const html = renderToStaticMarkup(<RegionMappingView {...props} state={custom} />)
for (const label of [
'区域设置',
'添加区域',
'一级部门',
'二级部门',
'三级部门',
'四级及更深',
'批量归属',
'全选当前列表',
'取消本次勾选',
'国外工业Amercia',
])
const html = renderToStaticMarkup(<RegionCatalogView {...props} state={custom} />)
for (const label of ['区域设置', '添加区域', '区域名称列表', '保存区域设置', '国外工业Amercia'])
expect(html).toContain(label)
expect(html).toMatch(/disabled=""[^>]*>批量归属/)
for (const removed of ['一级部门', '二级部门', '批量归属', '全选当前列表', 'qa-region-table'])
expect(html).not.toContain(removed)
expect(html).not.toContain('将 示例公司/')
})
@@ -89,36 +94,36 @@ describe('region mapping workbench', () => {
result: null,
},
}
const html = renderToStaticMarkup(<RegionMappingView {...props} syncStatus={syncStatus} />)
const html = renderToStaticMarkup(<RegionCatalogView {...props} syncStatus={syncStatus} />)
expect(html).toContain('正在读取并校验通讯录')
expect(html).not.toMatch(/\d+%/)
expect(html).toMatch(/disabled=""[^>]*>同步通讯录/)
const dirty = renderToStaticMarkup(
<RegionMappingView {...props} dirty syncStatus={{ configured: true, worker_ready: true, job: null }} />
<RegionCatalogView {...props} dirty syncStatus={{ configured: true, worker_ready: true, job: null }} />
)
expect(dirty).toContain('未保存的区域修改')
expect(dirty).toMatch(/disabled=""[^>]*>同步通讯录/)
})
it('lets long directory paths wrap instead of inheriting the global nowrap table rule', () => {
it('uses a responsive catalog list with wrapping warnings and no obsolete mapping-table styles', () => {
const css = readFileSync(new URL('./qaRegions.css', import.meta.url), 'utf8')
const bodyRule = css.match(/\.qa-region-table td\s*\{([^}]+)\}/)?.[1] ?? ''
expect(bodyRule).toMatch(/white-space:\s*normal/)
expect(bodyRule).toMatch(/overflow-wrap:\s*anywhere/)
const statusRule = css.match(/\.qa-region-table td\.qa-region-basis\s*\{([^}]+)\}/)?.[1] ?? ''
expect(statusRule).toMatch(/white-space:\s*nowrap/)
expect(css).toMatch(/\.qa-region-catalog-list/)
expect(css).toMatch(/minmax\(0,\s*1fr\)/)
expect(css).toMatch(/\.qa-region-row-actions/)
expect(css).toMatch(/overflow-wrap:\s*anywhere/)
expect(css).not.toContain('.qa-region-table')
})
it('shows a dated historical roster, conflicts and no invented performance verdict', () => {
const html = renderToStaticMarkup(<RegionMappingView {...props} />)
const html = renderToStaticMarkup(<RegionCatalogView {...props} />)
expect(html).toContain('历史快照')
expect(html).toContain('跨区域待核对:1')
expect(html).not.toContain('配置区域归属不等于纳入绩效考核')
expect(html).not.toContain('<script>test</script>')
expect(html).not.toContain('达标率')
expect(html).toMatch(/disabled=""[^>]*>保存归属/)
expect(html).toMatch(/disabled=""[^>]*>保存区域设置/)
})
it('requires a preview of the current draft before enabling save', () => {
const html = renderToStaticMarkup(<RegionMappingView {...props} dirty preview={state} />)
it('keeps optional preview visible and lets save invoke the same preview automatically', () => {
const html = renderToStaticMarkup(<RegionCatalogView {...props} dirty preview={state} />)
expect(html).toContain('预览结果(未保存)')
expect(html).not.toMatch(/disabled=""[^>]*>保存归属/)
expect(html).not.toMatch(/disabled=""[^>]*>保存区域设置/)
})
})
+154 -277
View File
@@ -1,24 +1,20 @@
import { useEffect, useRef, useState } from 'react'
import {
changeRegionRule,
fetchOrganization,
previewOrganization,
organizationRegions,
parseRegionDefinitions,
saveOrganization,
commitOrganization,
} from './qaOrg'
import type { Organization, RegionRule, RegionDefinition } from './qaOrg'
import './qaRegions.css'
import { applyBulkRegionRules, departmentLevels } from './qaRegionSelection'
import { completedSyncAction, directorySyncActive, fetchDirectorySync, startDirectorySync } from './qaOrgSync'
import type { DirectorySyncStatus } from './qaOrgSync'
import { newOperationID } from './operationKey'
interface Props {
regions?: RegionDefinition[]
selectedIDs?: string[]
onCatalog?: (regions: RegionDefinition[]) => void
onSelect?: (ids: string[]) => void
onApply?: () => void
onRemoveRegion?: (id: string) => void
syncStatus?: DirectorySyncStatus | null
syncError?: string
syncSubmitting?: boolean
@@ -26,57 +22,46 @@ interface Props {
state: Organization | null
preview: Organization | null
rules: RegionRule[]
selectedRegion: string
search: string
busy: boolean
error: string
notice: string
dirty: boolean
onRegion: (value: string) => void
onSearch: (value: string) => void
onToggle: (id: string, checked: boolean) => void
onRemoveMissing: (id: string) => void
onPreview: () => void
onSave: () => void
onReload: () => void
}
export function RegionMappingView(p: Props) {
export function RegionCatalogView(p: Props) {
const [newName, setNewName] = useState(''),
[level, setLevel] = useState(''),
[catalogError, setCatalogError] = useState('')
const display = p.preview ?? p.state,
available = p.state?.state === 'ready'
const regions = p.regions ?? organizationRegions(p.state),
selected = p.selectedIDs ?? []
const all = display?.view.departments ?? [],
nodes = new Map(all.map((d) => [d.id, d]))
const rows = all.map((d) => ({ department: d, levels: departmentLevels(all, d.id, nodes) }))
const departments = rows.filter(
({ department: d, levels }) =>
d.path.toLowerCase().includes(p.search.toLowerCase()) && (!level || levels.length === Number(level))
)
const maximum = rows.reduce((n, r) => Math.max(n, r.levels.length), 0)
const label = (id: string, catalog = regions) => catalog.find((r) => r.id === id)?.name ?? id
const choose = (id: string, checked: boolean) =>
p.onSelect?.(checked ? [...new Set([...selected, id])] : selected.filter((x) => x !== id))
[catalogError, setCatalogError] = useState(''),
[removeID, setRemoveID] = useState('')
const available = p.state?.state === 'ready',
regions = p.regions ?? organizationRegions(p.state),
display = p.preview ?? p.state
const add = () => {
if (!newName.trim()) return
const next = [...regions, { id: 'region-' + newOperationID(), name: newName.trim() }]
try {
p.onCatalog?.(parseRegionDefinitions(next))
p.onCatalog?.(parseRegionDefinitions([...regions, { id: 'region-' + newOperationID(), name: newName.trim() }]))
setNewName('')
setCatalogError('')
} catch {
setCatalogError('区域名称无效,请核对长度、重名或保留名称')
}
}
const remove = (id: string) => {
p.onRemoveRegion?.(id)
setRemoveID('')
}
return (
<section className="qa-regions" aria-label="区域归属配置">
<section className="qa-regions" aria-label="区域设置">
<div className="qa-region-heading">
<h3>区域归属配置</h3>
<h3>区域名称</h3>
<button type="button" disabled={p.busy} onClick={p.onReload}>
{p.dirty ? '放弃修改并重读' : '重新读取'}
</button>
</div>
<p className="qa-ops-muted">区域名称、筛选及看板使用同一份配置;部门绑定在左侧统计表完成。</p>
<div className="qa-region-directory-status">
<button
type="button"
disabled={
@@ -91,172 +76,122 @@ export function RegionMappingView(p: Props) {
>
同步通讯录
</button>
<small role="status" aria-label="通讯录后台同步状态">
{!p.syncStatus
? '正在读取后台同步状态…'
: !p.syncStatus.configured
? '后台同步未接线'
: p.syncStatus.job
? {
pending: '等待后台执行器',
running: '正在读取并校验通讯录',
retry: '上次同步失败,等待后台重试;保留原快照',
completed: '同步已完成,完整快照已落库',
failed: '同步失败,保留原快照;可重新同步',
cancelled: '同步已取消,保留原快照',
}[p.syncStatus.job.state]
: p.syncStatus.worker_ready
? '后台执行器在线,尚未发起同步'
: '后台执行器未在线,不会创建无人处理的任务'}
{p.dirty ? ';存在未保存的区域修改,请先保存或放弃后同步' : ''}
</small>
</div>
<div className="qa-ops-muted" aria-label="通讯录后台同步状态" role="status">
{!p.syncStatus
? '正在读取后台同步状态…'
: !p.syncStatus.configured
? '后台同步未接线'
: p.syncStatus.job
? {
pending: '等待后台执行器',
running: '正在读取并校验通讯录',
retry: '上次同步失败,等待后台重试;保留原快照',
completed: '同步已完成,完整快照已落库',
failed: '同步失败,保留原快照;可重新同步',
cancelled: '同步已取消,保留原快照',
}[p.syncStatus.job.state]
: p.syncStatus.worker_ready
? '后台执行器在线,尚未发起同步'
: '后台执行器未在线,不会创建无人处理的任务'}
{p.dirty ? ';存在未保存的区域修改,请先保存或放弃后同步' : ''}
</div>
{p.syncError ? (
<p role="alert" className="error-banner">
{p.syncError}
</p>
) : null}
{p.state?.directory_synced_at ? (
<p className="qa-ops-muted">
{p.state.directory_source === 'weekly_report_snapshot' ? '历史快照' : '全量同步快照'} · 通讯录同步时间:
{new Date(p.state.directory_synced_at).toLocaleString('zh-CN', { hour12: false })} · 配置版本:
{p.state.revision_id || '尚未保存'}
{new Date(p.state.directory_synced_at).toLocaleString('zh-CN', { hour12: false })}
</p>
) : null}
{p.error ? (
<p role="alert" className="error-banner">
{p.error}
{[p.error, p.syncError, catalogError].filter(Boolean).map((error, index) => (
<p role="alert" className="error-banner" key={index}>
{error}
</p>
) : null}
))}
{p.notice ? <p role="status">{p.notice}</p> : null}
{!p.state ? (
<p role="status">{p.busy ? '正在读取通讯录…' : '尚未读取通讯录'}</p>
<p role="status">{p.busy ? '正在读取区域设置…' : '尚未读取区域设置'}</p>
) : !available ? (
<p className="qa-ops-empty">暂无通讯录,请先同步。</p>
) : (
<>
<section className="qa-region-catalog" aria-label="区域设置">
<h4>区域设置</h4>
{catalogError ? (
<p role="alert" className="error-banner">
{catalogError}
</p>
) : null}
<div className="qa-region-names">
{regions.map((r) => (
<label key={r.id}>
区域名称
<input
aria-label={`区域名称 ${r.id}`}
value={r.name}
maxLength={100}
disabled={p.busy}
onChange={(e) =>
p.onCatalog?.(regions.map((x) => (x.id === r.id ? { ...x, name: e.target.value } : x)))
}
/>
</label>
))}
</div>
<form
onSubmit={(e) => {
e.preventDefault()
add()
}}
className="qa-region-add"
>
<input
aria-label="新区域名称"
value={newName}
maxLength={100}
disabled={p.busy}
placeholder="输入业务区域名称"
onChange={(e) => setNewName(e.target.value)}
/>
<button
disabled={
p.busy || !newName.trim() || regions.length >= 100 || regions.some((r) => r.name === newName.trim())
}
>
添加区域
</button>
</form>
</section>
<div className="qa-region-filters">
<label>
选择区域
<select value={p.selectedRegion} disabled={p.busy} onChange={(e) => p.onRegion(e.target.value)}>
{regions.length ? (
regions.map((r) => (
<option key={r.id} value={r.id}>
{r.name}
</option>
))
) : (
<option value="">请先添加区域</option>
)}
</select>
</label>
<label>
搜索完整部门路径
<input
type="search"
value={p.search}
onChange={(e) => p.onSearch(e.target.value)}
placeholder="输入部门名称或完整路径"
/>
</label>
<label>
部门层级
<select aria-label="部门层级" value={level} onChange={(e) => setLevel(e.target.value)}>
<option value="">全部层级</option>
{Array.from({ length: maximum }, (_, i) => (
<option key={i} value={i + 1}>
第 {i + 1} 级
</option>
))}
</select>
</label>
</div>
<div className="qa-region-bulk">
<label>
<input
type="checkbox"
aria-label="全选当前列表"
disabled={p.busy || !departments.length}
checked={departments.length > 0 && departments.every((r) => selected.includes(r.department.id))}
onChange={(e) => {
const visible = new Set(departments.map((r) => r.department.id))
p.onSelect?.(
e.target.checked
? [...new Set([...selected, ...visible])]
: selected.filter((id) => !visible.has(id))
)
}}
/>
全选当前列表
</label>
<span>已勾选 {selected.length} 个部门</span>
<ul className="qa-region-catalog-list" aria-label="区域名称列表">
{regions.map((r) => {
const count = p.rules.filter((rule) => rule.region === r.id).length
return (
<li key={r.id} data-region-id={r.id}>
<label>
<span>区域名称</span>
<input
aria-label={`区域名称 ${r.id}`}
value={r.name}
maxLength={100}
disabled={p.busy}
onChange={(e) =>
p.onCatalog?.(
regions.map((item) => (item.id === r.id ? { ...item, name: e.target.value } : item))
)
}
/>
</label>
<small>直接绑定 {count} 个部门</small>
<div className="qa-region-row-actions">
{removeID === r.id ? (
<>
<button type="button" disabled={p.busy} onClick={() => setRemoveID('')}>
取消
</button>
<button type="button" disabled={p.busy} onClick={() => remove(r.id)}>
确认删除
</button>
</>
) : (
<button
type="button"
aria-label={`删除区域 ${r.name}`}
disabled={p.busy}
onClick={() => (count ? setRemoveID(r.id) : remove(r.id))}
>
删除
</button>
)}
</div>
{removeID === r.id ? (
<p role="alert" className="qa-region-removal-warning">
保存后将删除“{r.name}”并解除 {count}{' '}
个部门的直接绑定;这些部门将重新按剩余上级规则计算归属,不删除问答。
</p>
) : null}
</li>
)
})}
</ul>
{!regions.length ? <p>暂无区域,请添加区域名称。</p> : null}
<form
className="qa-region-add"
onSubmit={(e) => {
e.preventDefault()
add()
}}
>
<input
aria-label="新区域名称"
value={newName}
maxLength={100}
disabled={p.busy}
placeholder="输入新的区域名称"
onChange={(e) => setNewName(e.target.value)}
/>
<button
type="button"
disabled={p.busy || !selected.length || !regions.some((r) => r.id === p.selectedRegion)}
onClick={p.onApply}
disabled={
p.busy || !newName.trim() || regions.length >= 100 || regions.some((r) => r.name === newName.trim())
}
>
批量归属
添加区域
</button>
<button type="button" disabled={p.busy || !selected.length} onClick={() => p.onSelect?.([])}>
取消本次勾选
</button>
<button type="button" disabled={p.busy || !p.dirty} onClick={p.onPreview}>
预览影响
</button>
<button type="button" disabled={p.busy || !p.dirty || !p.preview} onClick={p.onSave}>
保存归属
</button>
</div>
{display ? (
</form>
{p.preview && display ? (
<div className="qa-region-preview" aria-label="归属人数预览">
<strong>{p.preview ? '预览结果(未保存)' : '已保存归属'}</strong>
<strong>预览结果(未保存)</strong>
<span>通讯录人数:{display.view.total_people}</span>
{organizationRegions(display).map((r) => (
<span key={r.id}>
@@ -266,14 +201,17 @@ export function RegionMappingView(p: Props) {
<span>未归属:{display.view.unassigned_people}</span>
<span>跨区域待核对:{display.view.conflicting_people}</span>
</div>
) : display ? (
<small>
已保存:通讯录人数 {display.view.total_people},跨区域待核对:{display.view.conflicting_people}
</small>
) : null}
{p.dirty && !p.preview ? <p className="qa-ops-muted">人数仍为已保存结果;请预览后保存。</p> : null}
{display?.view.missing_departments.length ? (
<div role="alert" className="qa-ops-warning">
部分已配置部门不在当前通讯录中,原规则保留,需核对:
部分历史绑定不在当前通讯录中:
{display.view.missing_departments.map((id) => (
<span key={id}>
{id}{' '}
{id}
<button type="button" disabled={p.busy} onClick={() => p.onRemoveMissing(id)}>
移除此规则
</button>
@@ -281,77 +219,28 @@ export function RegionMappingView(p: Props) {
))}
</div>
) : null}
<div className="qa-region-tree-scroll">
<table className="qa-region-table">
<thead>
<tr>
<th>选择</th>
<th>一级部门</th>
<th>二级部门</th>
<th>三级部门</th>
<th>四级及更深</th>
<th>完整部门路径</th>
<th>直接配置</th>
<th>{p.dirty && !p.preview ? '已保存归属' : '生效归属'}</th>
<th>依据</th>
</tr>
</thead>
<tbody>
{departments.map(({ department: d, levels }) => {
const direct = p.rules.find((r) => r.department_id === d.id)
return (
<tr key={d.id} data-department-id={d.id}>
<td>
<input
type="checkbox"
aria-label={`选择部门 ${d.path}`}
checked={selected.includes(d.id)}
disabled={p.busy}
onChange={(e) => choose(d.id, e.target.checked)}
/>
</td>
<td>{levels[0] || '—'}</td>
<td>{levels[1] || '—'}</td>
<td>{levels[2] || '—'}</td>
<td>{levels.slice(3).join(' / ') || '—'}</td>
<td>{d.path}</td>
<td>
{direct ? (
<>
<span>{label(direct.region)}</span>
<button
type="button"
aria-label={`清除直接配置 ${d.path}`}
disabled={p.busy}
onClick={() => p.onToggle(d.id, false)}
>
清除
</button>
</>
) : (
'—'
)}
</td>
<td>{d.region ? label(d.region, organizationRegions(display)) : '未归属'}</td>
<td className="qa-region-basis">
{d.explicit ? '直接配置' : d.inherited_from ? '继承上级' : '未配置'}
</td>
</tr>
)
})}
</tbody>
</table>
{!departments.length ? <p>没有匹配的部门路径</p> : null}
</div>
<footer className="qa-region-save-actions">
<button type="button" disabled={p.busy || !p.dirty} onClick={p.onPreview}>
预览影响
</button>
<button type="button" disabled={p.busy || !p.dirty} onClick={p.onSave}>
{p.busy ? '正在处理…' : '保存区域设置'}
</button>
</footer>
</>
)}
</section>
)
}
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({
onSaved,
onDirtyChange,
open = true,
}: { onSaved?: (value: Organization) => void; onDirtyChange?: (dirty: boolean) => void; open?: boolean } = {}) {
const [syncStatus, setSyncStatus] = useState<DirectorySyncStatus | null>(null),
[syncError, setSyncError] = useState(''),
[syncSubmitting, setSyncSubmitting] = useState(false)
@@ -363,11 +252,8 @@ export function QARegions() {
const [state, setState] = useState<Organization | null>(null),
[preview, setPreview] = useState<Organization | null>(null),
[rules, setRules] = useState<RegionRule[]>([])
const [regions, setRegions] = useState<RegionDefinition[]>([]),
[selected, setSelected] = useState<string[]>([])
const [region, setRegion] = useState<string>(''),
[search, setSearch] = useState(''),
[busy, setBusy] = useState(false),
const [regions, setRegions] = useState<RegionDefinition[]>([])
const [busy, setBusy] = useState(false),
[error, setError] = useState(''),
[notice, setNotice] = useState('')
const request = useRef<AbortController | null>(null)
@@ -375,10 +261,6 @@ export function QARegions() {
setState(value)
setRules(value.rules)
setRegions(organizationRegions(value))
setRegion((current) =>
organizationRegions(value).some((r) => r.id === current) ? current : (organizationRegions(value)[0]?.id ?? '')
)
setSelected([])
setPreview(null)
}
const load = async () => {
@@ -401,12 +283,10 @@ export function QARegions() {
if (!controller.signal.aborted) setBusy(false)
}
}
useEffect(() => {
void load()
return () => request.current?.abort()
}, [])
useEffect(() => () => request.current?.abort(), [])
const dirty = Boolean(state && signature(rules, regions) !== signature(state.rules, organizationRegions(state)))
dirtyRef.current = dirty
useEffect(() => onDirtyChange?.(dirty), [dirty, onDirtyChange])
const loadRef = useRef(load)
loadRef.current = load
useEffect(() => {
@@ -477,8 +357,11 @@ export function QARegions() {
setNotice('')
setError('')
}
useEffect(() => {
if (open && !dirtyRef.current) void load()
}, [open])
const act = async (save: boolean) => {
if (!state || busy || (save && !preview)) return
if (!state || busy) return
const controller = new AbortController()
request.current?.abort()
request.current = controller
@@ -487,15 +370,13 @@ export function QARegions() {
setNotice('')
try {
const value = await (save
? saveOrganization({ ...state, regions: parseRegionDefinitions(regions) }, rules, controller.signal)
? commitOrganization(state, parseRegionDefinitions(regions), rules, controller.signal)
: previewOrganization({ ...state, regions: parseRegionDefinitions(regions) }, rules, controller.signal))
if (!controller.signal.aborted) {
if (save) {
const readback = await fetchOrganization(controller.signal)
if (controller.signal.aborted) return
accept(readback)
if (readback.revision_id !== value.revision_id) throw new Error('保存后配置再次变化,已读取最新版本,请核对')
setNotice('区域归属已保存并重新读取')
accept(value)
setNotice('区域设置已保存,筛选和看板将使用此版本')
onSaved?.(value)
} else setPreview(value)
}
} catch (e) {
@@ -508,17 +389,18 @@ export function QARegions() {
}
}
return (
<RegionMappingView
<RegionCatalogView
onRemoveRegion={(id) => {
setRegions((old) => old.filter((r) => r.id !== id))
edit(rules.filter((rule) => rule.region !== id))
}}
regions={regions}
selectedIDs={selected}
onCatalog={(next) => {
setRegions(next)
setPreview(null)
setNotice('')
setError('')
}}
onSelect={setSelected}
onApply={() => edit(applyBulkRegionRules(rules, selected, region))}
syncStatus={syncStatus}
syncError={syncError}
syncSubmitting={syncSubmitting}
@@ -526,15 +408,10 @@ export function QARegions() {
state={state}
preview={preview}
rules={rules}
selectedRegion={region}
search={search}
busy={busy}
error={error}
notice={notice}
dirty={dirty}
onRegion={setRegion}
onSearch={setSearch}
onToggle={(id, checked) => edit(changeRegionRule(rules, id, region, checked))}
onRemoveMissing={(id) => edit(rules.filter((r) => r.department_id !== id))}
onPreview={() => void act(false)}
onSave={() => void act(true)}
+30
View File
@@ -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)
+48
View File
@@ -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,
+230
View File
@@ -0,0 +1,230 @@
.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%;
}
}
.qa-department-binding {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
border-left: 1px solid #e5ebf2;
padding-left: 12px;
}
.qa-department-binding > span {
color: #64748b;
font-size: 12px;
}
.qa-region-settings-panel {
position: fixed;
inset: 0 0 0 auto;
z-index: 80;
display: flex;
flex-direction: column;
width: min(560px, 100vw);
box-sizing: border-box;
border-left: 1px solid #d8e1eb;
background: #fff;
color: #334155;
box-shadow: -10px 0 30px #33415514;
}
.qa-region-settings-panel[hidden] {
display: none;
}
.qa-region-settings-panel > header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 18px 20px;
border-bottom: 1px solid #e5ebf2;
gap: 12px;
}
.qa-region-settings-panel > header h3 {
margin: 0;
font-size: 18px;
}
.qa-region-settings-content {
overflow: auto;
min-height: 0;
padding: 20px;
}
@media (max-width: 680px) {
.qa-department-binding {
border-left: 0;
padding-left: 0;
flex-basis: 100%;
}
.qa-region-settings-content {
padding: 16px;
}
}
+62
View File
@@ -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,
},
],
},
}
+23
View File
@@ -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()
})
+212
View File
@@ -0,0 +1,212 @@
import { qaWeek } from './qaWeeks'
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' | 'week'
month?: string
week?: 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' | 'week'
month: string
week: 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 (
!['all', 'month', 'week'].includes(query.period) ||
d.period !== query.period ||
(d.week === undefined ? '' : text(d.week)) !== (query.week ?? '') ||
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()
if (query.period === 'week') {
if (!query.week || !/^\d{4}-W\d{2}$/.test(query.week) || query.month) return bad()
let range
try {
range = qaWeek(Number(query.week.slice(0, 4)), Number(query.week.slice(6)))
} catch {
return bad()
}
if (
start === null ||
Date.parse(start) !== Date.parse(range.start + ':00+08:00') ||
Date.parse(end) > Date.parse(range.end + ':00+08:00')
)
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 ?? '',
week: query.week ?? '',
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
}
+26
View File
@@ -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()
})
+27
View File
@@ -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)
})
+47
View File
@@ -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
}
+14
View File
@@ -0,0 +1,14 @@
import { it, expect, vi } from 'vitest'
import { qaCellValue } from './qaOps'
import type { QARecord } from './qaOps'
it('formats Beijing timestamps identically without constructing per-row locale formatting work', () => {
const record = { asked_at: '2026-10-19T12:11:22Z' } as QARecord
const expected = new Date(record.asked_at).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
const spy = vi.spyOn(Date.prototype, 'toLocaleString')
try {
for (let i = 0; i < 200; i++) expect(qaCellValue(record, 'asked_at')).toBe(expected)
expect(spy).not.toHaveBeenCalled()
} finally {
spy.mockRestore()
}
})
+10
View File
@@ -0,0 +1,10 @@
import { it, expect } from 'vitest'
import { ledgerCellPreview } from './qaLedgerRendering'
it('bounds clipped cell text without modifying full original strings or splitting Unicode', () => {
const original = '测试🎵'.repeat(5000)
const preview = ledgerCellPreview(original)
expect([...preview].length).toBeLessThanOrEqual(401)
expect(preview.endsWith('…')).toBe(true)
expect(original).toBe('测试🎵'.repeat(5000))
expect(ledgerCellPreview('短问题')).toBe('短问题')
})
+17
View File
@@ -0,0 +1,17 @@
export const ledgerRowHeight = 108
export function ledgerWindow(total: number, top: number, height: number) {
const visible = Math.max(1, Math.ceil(height / ledgerRowHeight))
const start = Math.min(Math.max(0, total - visible), Math.max(0, Math.floor(top / ledgerRowHeight) - 8))
const end = Math.min(total, start + visible + 16)
return { start, end, padTop: start * ledgerRowHeight, padBottom: (total - end) * ledgerRowHeight }
}
export function ledgerCellPreview(value: string): string {
if (value.length <= 400) return value
let prefix = '',
count = 0
for (const point of value) {
if (count++ === 400) return prefix + '…'
prefix += point
}
return prefix
}
+14
View File
@@ -0,0 +1,14 @@
import { it, expect } from 'vitest'
import { ledgerWindow } from './qaLedgerRendering'
it('keeps a bounded viewport while all records remain reachable without pagination', () => {
const total = 6041,
seen = new Set<number>()
for (let top = 0; top < total * 108; top += 540) {
const w = ledgerWindow(total, top, 600)
expect(w.end - w.start).toBeLessThanOrEqual(23)
expect(w.padTop + (w.end - w.start) * 108 + w.padBottom).toBe(total * 108)
for (let i = w.start; i < w.end; i++) seen.add(i)
}
expect(seen.size).toBe(total)
expect(ledgerWindow(total, total * 108, 600).end).toBe(total)
})
+95 -24
View File
@@ -264,11 +264,34 @@
min-height: 0;
overflow: auto;
}
.qa-ops-table .qa-ops-record-row {
height: 108px;
}
.qa-ledger-actions {
max-height: 84px;
overflow: hidden;
}
.qa-ledger-actions .qa-ai-task {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.qa-ops-table .qa-ops-record-row > td > span {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
.qa-ops-table .qa-ledger-spacer > td {
padding: 0;
border: 0;
line-height: 0;
}
.qa-ops-table {
width: 100%;
min-width: 980px;
border-collapse: collapse;
table-layout: auto;
table-layout: fixed;
font-size: 13px;
}
.qa-ops-table th {
@@ -321,44 +344,55 @@
.qa-ops-page-bar {
border-top: 1px solid var(--border-base);
}
.qa-ops-backdrop {
position: fixed;
inset: 0;
z-index: 80;
width: 100%;
height: 100%;
border: 0;
border-radius: 0;
background: rgb(15 23 32 / 28%);
cursor: default;
}
.qa-ops-backdrop:hover {
background: rgb(15 23 32 / 28%);
}
.qa-ops-drawer {
position: fixed;
top: 0;
right: 0;
inset: 0 0 0 auto;
z-index: 81;
width: min(760px, 100vw);
height: 100vh;
overflow: auto;
padding: 22px;
height: 100dvh;
display: flex;
flex-direction: column;
overflow: hidden;
padding: 0;
background: var(--bg-panel);
border-left: 1px solid var(--border-strong);
box-shadow: -8px 0 24px rgb(15 23 32 / 10%);
color: var(--ink-strong);
}
.qa-ops-drawer > header {
display: flex;
justify-content: space-between;
align-items: center;
flex: none;
gap: 14px;
position: sticky;
top: -22px;
padding: 12px 0;
padding: 16px 22px;
background: var(--bg-panel);
border-bottom: 1px solid var(--border-base);
}
.qa-detail-quality {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
flex: none;
gap: 8px;
padding: 12px 22px;
border-bottom: 1px solid var(--border-base);
background: var(--bg-soft);
}
.qa-detail-quality > div {
min-width: 0;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 6px;
}
.qa-detail-quality > div > span {
color: var(--ink-mute);
font-size: 12px;
}
.qa-detail-quality .qa-field-tag {
white-space: normal;
overflow-wrap: anywhere;
}
.qa-ops-drawer h3 {
margin: 0;
font-size: 18px;
@@ -368,6 +402,10 @@
font-size: 14px;
}
.qa-ops-detail-content {
flex: 1;
min-height: 0;
overflow: auto;
padding: 0 22px 22px;
font-size: 13px;
line-height: 1.7;
overflow-wrap: anywhere;
@@ -416,7 +454,14 @@
max-height: 55vh;
}
.qa-ops-drawer {
padding: 14px;
padding: 0;
}
.qa-detail-quality {
grid-template-columns: repeat(3, minmax(0, 1fr));
padding: 10px 14px;
}
.qa-ops-detail-content {
padding: 0 14px 14px;
}
.qa-ops-detail-meta {
grid-template-columns: 100px 1fr;
@@ -633,3 +678,29 @@
.qa-ai-hash {
overflow-wrap: anywhere;
}
.qa-ops-query .qa-query-action {
width: 96px;
height: 36px;
flex: none;
padding: 0 8px;
margin: 0;
white-space: nowrap;
}
.qa-ops-query .qa-mirror-sync {
position: relative;
}
.qa-ops-query .qa-mirror-sync-line {
margin-bottom: 0;
}
.qa-ops-query .qa-mirror-sync > [role='status']:not(:empty),
.qa-ops-query .qa-mirror-sync > .error-banner {
position: absolute;
top: calc(100% + 4px);
right: 0;
min-width: 260px;
z-index: 4;
padding: 6px 8px;
background: var(--bg-panel);
border: 1px solid var(--border-base);
}
+12 -2
View File
@@ -387,6 +387,17 @@ export function triggerPersonName(raw: string): string | null {
}
}
const qaAskedAtFormatter = new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
})
export function qaCellValue(item: QARecord, column: QAColumn): string | null {
if (column === 'trigger_person') return triggerPersonName(item.master_fields?.trigger_person ?? item.trigger_person)
@@ -439,7 +450,6 @@ export function qaCellValue(item: QARecord, column: QAColumn): string | null {
if (item.feedback.up || item.feedback.down) return `其他人:赞 ${item.feedback.up} / 踩 ${item.feedback.down}`
return null
}
if (column === 'asked_at')
return new Date(item.asked_at).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
if (column === 'asked_at') return qaAskedAtFormatter.format(new Date(item.asked_at))
return item[column] || null
}
+41
View File
@@ -1,3 +1,4 @@
import { applyBulkRegionRules } from './qaRegionSelection'
export const regionNames = ['国内工业', 'APAC', 'EMEA', 'America'] as const
export interface RegionDefinition {
id: string
@@ -189,6 +190,46 @@ export const previewOrganization = (state: Organization, rules: RegionRule[], si
{ directory_id: state.directory_id, base_revision: state.revision_id, regions: organizationRegions(state), rules },
signal
)
export async function bindOrganizationDepartments(
expected: { directory_id: string; revision_id: string },
ids: string[],
region: string,
signal?: AbortSignal
): Promise<Organization> {
const state = await fetchOrganization(signal),
catalog = organizationRegions(state)
if (state.directory_id !== expected.directory_id || state.revision_id !== expected.revision_id)
throw new Error('通讯录或区域版本已变化,请重新读取统计后绑定')
const known = new Set(state.view.departments.map((d) => d.id))
if (!ids.length || ids.some((id) => !known.has(id)) || !catalog.some((r) => r.id === region))
throw new Error('选中部门或目标区域无效,请重新读取')
return commitOrganization(state, catalog, applyBulkRegionRules(state.rules, ids, region), signal)
}
const organizationCommitSignature = (regions: RegionDefinition[], rules: RegionRule[]) =>
JSON.stringify({
regions: [...regions].sort((a, b) => a.id.localeCompare(b.id)),
rules: [...rules].sort((a, b) => a.department_id.localeCompare(b.department_id)),
})
export async function commitOrganization(
state: Organization,
regions: RegionDefinition[],
rules: RegionRule[],
signal?: AbortSignal
): Promise<Organization> {
const catalog = parseRegionDefinitions(regions),
base = { ...state, regions: catalog }
await previewOrganization(base, rules, signal)
const saved = await saveOrganization(base, rules, signal),
readback = await fetchOrganization(signal)
if (
readback.directory_id !== state.directory_id ||
readback.revision_id !== saved.revision_id ||
organizationCommitSignature(organizationRegions(readback), readback.rules) !==
organizationCommitSignature(catalog, rules)
)
throw new Error('保存后配置再次变化,未将旧结果标为成功,请重新读取核对')
return readback
}
export const saveOrganization = (state: Organization, rules: RegionRule[], signal?: AbortSignal) =>
requestOrganization(
'/regions',
+115
View File
@@ -0,0 +1,115 @@
import { it, expect, vi } from 'vitest'
import { commitOrganization, parseOrganization, bindOrganizationDepartments } from './qaOrg'
const raw = {
state: 'ready',
directory_id: 'fixture-dir',
directory_source: 'weekly_report_snapshot',
directory_synced_at: '2026-10-18T00:00:00Z',
revision_id: 'old',
updated_by: 'fixture-admin',
updated_at: null,
regions: [{ id: 'new-region', name: '业务区域' }],
rules: [{ department_id: 'root', region: 'new-region' }],
view: {
departments: [
{
id: 'root',
parent_id: '',
name: 'Fixture',
path: 'Fixture',
region: 'new-region',
explicit: true,
inherited_from: '',
},
],
regions: { 'new-region': 1 },
total_people: 1,
unassigned_people: 0,
conflicting_people: 0,
missing_departments: [],
},
}
const response = (v: unknown) => ({ ok: true, status: 200, json: async () => ({ data: v }) })
it('binds selected current department IDs in place and verifies the persisted version', async () => {
const fetch = vi
.fn()
.mockResolvedValueOnce(response(raw))
.mockResolvedValueOnce(response(raw))
.mockResolvedValueOnce(response({ ...raw, revision_id: 'new' }))
.mockResolvedValueOnce(response({ ...raw, revision_id: 'new' }))
vi.stubGlobal('fetch', fetch)
try {
const saved = await bindOrganizationDepartments(
{ directory_id: 'fixture-dir', revision_id: 'old' },
['root'],
'new-region'
)
expect(saved.revision_id).toBe('new')
expect(fetch.mock.calls.map((c) => c[1]?.method)).toEqual(['GET', 'POST', 'PUT', 'GET'])
expect(JSON.parse(fetch.mock.calls[2][1].body).rules).toEqual(raw.rules)
} finally {
vi.unstubAllGlobals()
}
})
it('refuses binding a stale directory/revision or a missing department before any write', async () => {
for (const [revision, ids] of [
['stale', ['root']],
['old', ['missing']],
] as const) {
const fetch = vi.fn().mockResolvedValue(response(raw))
vi.stubGlobal('fetch', fetch)
try {
await expect(
bindOrganizationDepartments({ directory_id: 'fixture-dir', revision_id: revision }, [...ids], 'new-region')
).rejects.toThrow()
expect(fetch).toHaveBeenCalledTimes(1)
} finally {
vi.unstubAllGlobals()
}
}
})
it('previews and persists the same versioned catalog/rules before independent exact readback', async () => {
const state = parseOrganization(raw),
receipt = { ...raw, revision_id: 'new' }
const fetch = vi
.fn()
.mockResolvedValueOnce(response(raw))
.mockResolvedValueOnce(response(receipt))
.mockResolvedValueOnce(response(receipt))
vi.stubGlobal('fetch', fetch)
try {
expect((await commitOrganization(state, state.regions!, state.rules)).revision_id).toBe('new')
expect(fetch.mock.calls.map((c) => c[0])).toEqual([
'/api/v1/qa-ops/organization/preview',
'/api/v1/qa-ops/organization/regions',
'/api/v1/qa-ops/organization',
])
for (const call of fetch.mock.calls.slice(0, 2)) {
const input = JSON.parse(call[1].body)
expect(input).toMatchObject({
directory_id: 'fixture-dir',
base_revision: 'old',
regions: raw.regions,
rules: raw.rules,
})
}
} finally {
vi.unstubAllGlobals()
}
})
it('does not claim a successful save when another revision wins before readback', async () => {
vi.stubGlobal(
'fetch',
vi
.fn()
.mockResolvedValueOnce(response(raw))
.mockResolvedValueOnce(response({ ...raw, revision_id: 'new' }))
.mockResolvedValueOnce(response({ ...raw, revision_id: 'other' }))
)
try {
const state = parseOrganization(raw)
await expect(commitOrganization(state, state.regions!, state.rules)).rejects.toThrow('保存后配置')
} finally {
vi.unstubAllGlobals()
}
})
+95
View File
@@ -1,4 +1,99 @@
import type { DepartmentRegion, RegionRule } from './qaOrg'
export type DepartmentNode = { id: string; parent_id: string; name: string }
export function defaultDepartmentCollapsed(nodes: DepartmentNode[]): Set<string> {
return new Set(
departmentTree(nodes, new Set())
.filter((r) => r.depth >= 2 && r.hasChildren)
.map((r) => r.department.id)
)
}
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]
+41
View File
@@ -0,0 +1,41 @@
import { it, expect } from 'vitest'
import { defaultDepartmentCollapsed, departmentTree } from './qaRegionSelection'
import { parseDepartmentStatistics } from './qaDepartmentStatistics'
import { departmentStatisticsFixture as f } from './qaDepartmentStatistics.fixture'
it('defaults to company, business centers and second-level departments while preserving deeper search and expansion', () => {
const nodes = [
{ id: 'company', parent_id: '', name: '示例公司' },
{ id: 'finance', parent_id: 'company', name: '财务中心' },
{ id: 'department', parent_id: 'finance', name: '财务部' },
{ id: 'office', parent_id: 'department', name: '更深财务组' },
{ id: 'global', parent_id: 'company', name: '全球业务支持中心' },
{ id: 'solution', parent_id: 'global', name: '解决方案部' },
{ id: 'support', parent_id: 'global', name: '全球技术支持部' },
]
const collapsed = defaultDepartmentCollapsed(nodes)
expect(departmentTree(nodes, collapsed).map((r) => r.department.id)).not.toContain('office')
expect(new Set(departmentTree(nodes, collapsed).map((r) => r.department.id))).toEqual(
new Set(nodes.filter((n) => n.id !== 'office').map((n) => n.id))
)
expect(departmentTree(nodes, collapsed, '更深财务组').some((r) => r.department.id === 'office')).toBe(true)
collapsed.delete('department')
expect(departmentTree(nodes, collapsed).some((r) => r.department.id === 'office')).toBe(true)
})
it('accepts an exact natural week response and rejects a mismatched week or non-Monday start', () => {
const raw = {
...f,
snapshot: {
...f.snapshot,
period: 'week',
week: '2026-W42',
start: '2026-10-12T00:00:00+08:00',
end: '2026-10-19T00:00:00+08:00',
},
}
const query = JSON.parse('{"period":"week","week":"2026-W42"}')
expect(parseDepartmentStatistics(raw, query).snapshot?.period).toBe('week')
expect(() => parseDepartmentStatistics({ ...raw, snapshot: { ...raw.snapshot, week: '2026-W43' } }, query)).toThrow()
expect(() =>
parseDepartmentStatistics({ ...raw, snapshot: { ...raw.snapshot, start: '2026-10-11T00:00:00+08:00' } }, query)
).toThrow()
})
+98 -145
View File
@@ -2,8 +2,8 @@
display: flex;
flex-direction: column;
min-height: 0;
gap: 12px;
flex: 1;
min-width: 0;
gap: 14px;
}
.qa-region-heading {
display: flex;
@@ -13,80 +13,108 @@
}
.qa-region-heading h3 {
margin: 0;
font-size: 15px;
}
.qa-region-filters {
.qa-region-directory-status {
display: flex;
gap: 12px;
align-items: end;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
.qa-region-filters label {
.qa-region-directory-status small {
color: #64748b;
line-height: 1.6;
}
.qa-region-catalog-list {
padding: 0;
margin: 0;
list-style: none;
border-top: 1px solid #e5ebf2;
}
.qa-region-catalog-list > li {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
gap: 7px 12px;
padding: 14px 0;
border-bottom: 1px solid #e5ebf2;
}
.qa-region-catalog-list label {
display: flex;
flex-direction: column;
gap: 6px;
gap: 5px;
grid-column: 1;
min-width: 0;
font-size: 12px;
color: #64748b;
}
.qa-region-filters label:nth-child(2) {
flex: 1;
min-width: 220px;
.qa-region-catalog-list small {
grid-column: 1;
color: #8190a4;
font-size: 11px;
}
.qa-region-filters input,
.qa-region-filters select {
.qa-region-catalog-list input,
.qa-region-add input {
box-sizing: border-box;
width: 100%;
min-width: 0;
min-height: 36px;
padding: 6px 10px;
border: 1px solid var(--line, #d8e1eb);
border-radius: 6px;
background: var(--panel, #fff);
color: inherit;
padding: 7px 10px;
border: 1px solid #d8e1eb;
border-radius: 5px;
background: #fff;
color: #334155;
}
.qa-region-row-actions {
min-width: 152px;
justify-content: flex-start;
display: flex;
flex-wrap: nowrap;
gap: 8px;
grid-column: 2;
grid-row: 1 / span 2;
}
.qa-region-row-actions button {
min-width: 48px;
white-space: nowrap;
}
.qa-region-removal-warning {
grid-column: 1 / -1;
color: #97572d;
line-height: 1.6;
overflow-wrap: anywhere;
font-size: 12px;
}
.qa-region-add {
display: flex;
gap: 8px;
align-items: center;
}
.qa-region-add input {
flex: 1;
}
.qa-region-add button {
flex: none;
}
.qa-region-save-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
position: sticky;
bottom: -20px;
padding: 12px 0;
border-top: 1px solid #e5ebf2;
background: #fff;
}
.qa-region-preview {
display: flex;
gap: 8px 18px;
gap: 8px 16px;
flex-wrap: wrap;
padding: 12px 14px;
border: 1px solid var(--line, #d8e1eb);
background: var(--panel-muted, #f3f7fc);
border-radius: 6px;
}
.qa-region-tree-scroll {
min-height: 120px;
overflow: auto;
flex: 1;
border: 1px solid var(--line, #d8e1eb);
border-radius: 6px;
}
.qa-region-table {
width: 100%;
border-collapse: collapse;
text-align: left;
font-size: 13px;
table-layout: fixed;
min-width: 960px;
}
.qa-region-table th,
.qa-region-table td {
padding: 10px 12px;
border-bottom: 1px solid var(--line, #d8e1eb);
white-space: normal;
overflow-wrap: anywhere;
}
.qa-region-table th {
position: sticky;
top: 0;
background: var(--panel, #fff);
white-space: nowrap;
}
.qa-region-table td:nth-child(2) {
min-width: 0;
overflow-wrap: anywhere;
}
.qa-region-table td.qa-region-basis {
white-space: nowrap;
}
.qa-region-table input[type='checkbox'] {
width: 17px;
height: 17px;
cursor: pointer;
accent-color: #1765c1;
padding: 12px;
border: 1px solid #d8e1eb;
background: #f3f7fc;
border-radius: 5px;
font-size: 12px;
}
.qa-region-tabs {
display: flex;
@@ -112,89 +140,14 @@
outline: 2px solid #1765c1;
outline-offset: 2px;
}
.qa-region-catalog {
border-bottom: 1px solid var(--line, #d8e1eb);
padding-bottom: 14px;
min-width: 0;
}
.qa-region-catalog h4 {
margin: 0 0 10px;
}
.qa-region-names {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
gap: 10px;
}
.qa-region-names label {
display: flex;
flex-direction: column;
gap: 4px;
color: var(--text-muted, #5e6d82);
font-size: 12px;
min-width: 0;
}
.qa-region-catalog input {
width: 100%;
min-width: 0;
box-sizing: border-box;
padding: 8px 10px;
border: 1px solid var(--line, #d8e1eb);
border-radius: 5px;
background: var(--panel, #fff);
color: inherit;
}
.qa-region-add,
.qa-region-bulk {
display: flex;
flex-wrap: wrap;
gap: 8px 12px;
align-items: center;
}
.qa-region-add {
margin-top: 10px;
}
.qa-region-add input {
max-width: 320px;
}
.qa-region-bulk label {
display: flex;
gap: 6px;
align-items: center;
}
.qa-region-tree-scroll {
max-height: 60vh;
}
.qa-region-table th {
white-space: normal;
}
.qa-region-table th:first-child {
width: 36px;
}
.qa-region-table th:nth-child(6) {
width: 23%;
}
.qa-region-table th:last-child {
width: 65px;
}
.qa-region-table td button {
padding: 3px 6px;
font-size: 11px;
margin-top: 4px;
}
@media (max-width: 700px) {
.qa-region-filters {
align-items: stretch;
}
.qa-region-filters label {
flex: 1;
}
.qa-region-tree-scroll {
min-height: 300px;
}
.qa-region-preview {
font-size: 13px;
}
@media (max-width: 480px) {
.qa-region-heading {
flex-wrap: wrap;
}
.qa-region-catalog-list > li {
gap: 7px 8px;
}
.qa-region-row-actions {
gap: 5px;
}
}