Compare commits

..

6 Commits

Author SHA1 Message Date
姚章浩 2c0bb32183 fix(qaops): 点踩问题统一判为不正确
build / build (push) Successful in 1m11s
通过持久来源关联读取最新本地反馈,强制总表有效正确性为否,保留原问答和人工证据。统一列表、详情、指标和两阶段读取的反馈快照,拒绝冲突选择并保留其他字段编辑。已通过完整本地门禁、隔离PG竞态和真实恢复库52条点踩逐条读回、桌面及手机验收;未调用模型或连接源生产库。
2026-10-20 08:18:03 +08:00
姚章浩 87f97a2f9b feat(qaops): 完成详情下拉与每周自动保存草稿
build / build (push) Successful in 1m7s
详情使用共享主表字典,稀疏修改所选字段并保留原始问答及旧复核审计。
月周统计提供文本和下拉双入口;每租户每周一份持久草稿,按技能六节双语模板真实预填。
加入幂等自动保存、冲突保留、未知响应重试、切周及离开保护和schema58非破坏降级保护。

验证:完整make verify、隔离PostgreSQL全mirror竞态回归、真实恢复库浏览器验收通过。
浏览器实测字段精确读回、月周双输入、模板预填、MD/CSV、自动保存、冲突、失败重试与API重启恢复。
未连接或改写DobotAI生产源库,未运行付费模型;提交时尚未部署。
2026-10-20 05:44:02 +08:00
姚章浩 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
108 changed files with 6590 additions and 856 deletions
+70
View File
@@ -76,6 +76,76 @@
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯,
> 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。
## 开发快照 snapshot/v0.1.42 - 2026-10-20
### Fixed
- 问题存在当前点踩时,总表有效“是否正确”固定为“否”,列表、详情和动态质量统计使用同一规则;通过已保存来源关联读取本地镜像最新反馈,避免导入快照漏掉后续点踩。仅点赞或无反馈不推定正确,原问答、旧模型结论、人工复核与字段修改审计保持不变。
- 详情对已点踩问题锁定“是否正确”并简洁说明;后端拒绝改为“是”或“待确认”的冲突选择,其余字段仍可编辑。迁移59只补充派生读模型、反馈索引及总表快照失效通知,不回写 DobotAI 源数据,也不重算或覆盖旧周冻结与历史上报。
## 开发快照 snapshot/v0.1.41 - 2026-10-20
### Added
- 周报生成升级为按北京时间自然周保存的 Markdown 编辑器,提供编辑、预览、对照、自动保存、立即保存及 MD/本周明细 CSV 下载;每个租户每周一份共享草稿,切周或离开前保存未提交输入,刷新与重新打开恢复正文。
- 按周报模板预填英文在上、中文在下的各六节正文,复用正式总表和已保存区域统计;历史周优先使用相应上报/冻结质量指标,缺失才使用当周实时指标。统计建议可人工修改,重点保留待填写,不编造 FAQ 调整或英文事项,不自动发送或归档。
- 治理库新增迁移 58:独立稀疏字段覆盖、不可变字段改动审计、周草稿及逐版保存收据。保存绑定输入与编辑版本,同 nonce 重试不重复留档,冲突和读回失败保留输入;已有草稿重新预填须明确确认,存在人工数据时拒绝删除式降级迁移。
### Changed
- 详情顶部五个质量字段可直接下拉修改,范围取源主表实际使用的覆盖/正确性选项及与模型共享的产品、问题、根因字典;只保存明确选择的字段,不补齐其他空白、不把模型值冒充整条人工复核。移除单独人工复核/反馈展示,保留原始问答、旧人工历史和后台留痕。
- 区域统计的月份及 ISO 周同时支持下拉选择和直接输入,合法值在回车或失焦后应用;未完成、非法及未来输入在本地提示,不发送错误统计请求,保留原自然月/周和缓存口径。
## 开发快照 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
+114 -3
View File
@@ -44,6 +44,75 @@
}
],
"paths": {
"/api/v1/qa-ops/master/field-options": {"get":{"operationId":"getQAMasterFieldOptions","tags":["QA operations"],"summary":"只读主表五字段的正式可选范围,与模型共享同一分类字典;不返回业务问答","parameters":[],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}}}},
"/api/v1/qa-ops/master/records/{id}/fields": {"post":{"operationId":"patchQAMasterFields","tags":["QA operations"],"summary":"只更新明确选择的字段并留幂等审计;不改原始正文、其他空白、旧复核或冻结证据。存在当前点踩时是否正确固定为否,改为是或待确认返回409且不写审计","parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-master-fields"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["input_hash","input_epoch","base_revision","base_review_revision","nonce","fields"],"properties":{"input_hash":{"type":"string","pattern":"^[a-f0-9]{64}$"},"input_epoch":{"type":"integer","minimum":1},"base_revision":{"type":"integer","minimum":0},"base_review_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"},"fields":{"type":"object","additionalProperties":false,"minProperties":1,"maxProperties":5,"properties":{"is_correct":{"type":"string","enum":["是","否","待确认"]},"product_category":{"type":"string","enum":["CR/CRA/H/AP","CRV","CR配件","Nova及系列","Nova配件","MG400","MG400配件","M1 Pro","VX500","新示教器","DobotStudio Pro","仿真软件","维护工具","教育所有产品","人形机器人","四六足机器人","X-Trainer","码垛解决方案","码垛插件","焊接解决方案","焊接插件","移动复合机器人","生态插件","生态合作","安全皮肤","未知"]},"problem_type":{"type":"string","enum":["参数","故障","使用配置","二次开发","资料获取","咨询","认证","案例","售后","培训与学习","其他"]},"root_cause":{"type":"string","enum":["知识缺失","检索不到","结果不清","答案生成错误","问题质量差","非知识范围","知识过期"]},"coverage":{"type":"string","enum":["是","否","否但不计入"]}}}}}}}}}},
"/api/v1/qa-ops/master/weekly-drafts/{week}": {"get":{"operationId":"getQAWeeklyDraft","tags":["QA operations"],"summary":"读取租户指定北京时间ISO周的持久草稿;不存在时revision=0且不创建记录","parameters":[{"name":"week","in":"path","required":true,"schema":{"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":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}}},"post":{"operationId":"saveQAWeeklyDraft","tags":["QA operations"],"summary":"防抖编辑保存:版本锁、逐版历史及同nonce重放;正文不会触发外发/归档","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-draft"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["base_revision","nonce","markdown"],"properties":{"base_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"},"markdown":{"type":"string","maxLength":262144,"description":"UTF-8正文最多256KiB;允许空正文,保存草稿不等于发布"}}}}}}}},
"/api/v1/qa-ops/master/weekly-drafts/{week}/prefill": {"post":{"operationId":"prefillQAWeeklyDraft","tags":["QA operations"],"summary":"从同一正式总表截止和保存区域生成中英各六节草稿;优先匹配已上报/冻结历史指标,其余用当周实时指标;不编造FAQ调整或重点。须带当前草稿版本,防止覆盖旧编辑","parameters":[{"name":"week","in":"path","required":true,"schema":{"type":"string","pattern":"^[0-9]{4}-W[0-9]{2}$"}},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-weekly-draft"}}],"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员且写入须同源操作意图"},"409":{"description":"版本、输入或nonce冲突,未覆盖现有数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"独立治理存储不可用,不将失败伪装为已保存"}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["base_revision","nonce"],"properties":{"base_revision":{"type":"integer","minimum":0},"nonce":{"type":"string","pattern":"^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$"}}}}}}}},
"/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 +125,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"],
@@ -221,7 +290,7 @@
"QA operations"
],
"operationId": "listQAOperationsRecordsMaster",
"summary": "正式主表:按半开提问时间范围、原问题关键词、稳定游标列出钉钉问答;租户由后端固定;答案包含暂无已发布则治理侧未覆盖",
"summary": "正式主表:按半开提问时间范围、原问题关键词、稳定游标列出问答;租户固定。通过持久来源关联读取本地镜像最新反馈,点踩强制有效是否正确为否,quality.feedback_rule=downvote-is-incorrect-v1;原人工证据保留,点赞不推定正确。答案包含暂无已发布则未覆盖",
"parameters": [
{
"name": "start",
@@ -297,7 +366,7 @@
"QA operations"
],
"operationId": "getQAOperationsRecordMaster",
"summary": "正式主表:读取授权租户内的完整问答与源端覆盖对照;治理覆盖规则独立,不写回源库",
"summary": "正式主表:读取授权租户内的完整问答与最新本地反馈;点踩强制有效是否正确为否,quality.feedback_rule=downvote-is-incorrect-v1;原人工证据不改写,治理规则不写回源库",
"parameters": [
{
"name": "id",
@@ -4392,6 +4461,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"]},
+1
View File
@@ -69,6 +69,7 @@ type RecordFeedback struct {
}
type Record struct {
FieldEditRevision int64 `json:"field_edit_revision,omitempty"`
BackgroundTasks json.RawMessage `json:"background_tasks,omitempty"`
RecordOrigin string `json:"record_origin,omitempty"`
MasterFields map[string]string `json:"master_fields,omitempty"`
@@ -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")
}
@@ -0,0 +1,53 @@
package httpapi
import (
"context"
"encoding/json"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qaopsquality"
"testing"
)
type downvoteSnapshotReader struct {
QAOpsReader
view qaopsquality.View
}
func (s downvoteSnapshotReader) ReadStoredQuality(context.Context, []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
return map[string]qaopsquality.View{"fixture-feedback-race": s.view}, nil
}
func TestMasterQualityEnrichmentUsesOneFeedbackDecisionEvenWhenVoteChangesBetweenReads(t *testing.T) {
for _, test := range []struct {
name string
old, current dobotaiops.RecordFeedback
label, correctness, rule string
}{
{"new-downvote", dobotaiops.RecordFeedback{}, dobotaiops.RecordFeedback{Down: 1}, "否", "incorrect", "downvote-is-incorrect-v1"},
{"withdrawn-current-vote", dobotaiops.RecordFeedback{Down: 1}, dobotaiops.RecordFeedback{}, "是", "correct", ""},
} {
t.Run(test.name, func(t *testing.T) {
view := qaopsquality.View{EffectiveSource: "master-effective-fields-v1", FeedbackRule: test.rule, Effective: qaopsquality.Fields{Correctness: test.correctness}, MasterFeedback: &test.current}
c := Config{QAOps: downvoteSnapshotReader{view: view}, QAQuality: &qualityFake{}}
item := dobotaiops.Record{ID: "fixture-feedback-race", RecordOrigin: "dobotai_2_0", Feedback: test.old, MasterFields: map[string]string{"is_correct": "待确认"}}
if err := enrichQAQualityRecord(context.Background(), c, &item); err != nil {
t.Fatal(err)
}
if item.Feedback != test.current || item.MasterFields["is_correct"] != test.label {
t.Fatal("detail combines an old feedback snapshot with a newer quality decision")
}
page := dobotaiops.RecordPage{Items: []dobotaiops.Record{{ID: item.ID, RecordOrigin: item.RecordOrigin, Feedback: test.old, MasterFields: map[string]string{"is_correct": "待确认"}}}}
// The common projection must be shared by the list and detail enrichment paths.
if err := enrichQAQualityPage(context.Background(), c, &page); err != nil {
t.Fatal(err)
}
if page.Items[0].Feedback != test.current || page.Items[0].MasterFields["is_correct"] != test.label {
t.Fatal("list combines an old feedback snapshot with a newer quality decision")
}
var quality map[string]any
if json.Unmarshal(item.Quality, &quality) != nil {
t.Fatal("quality response missing")
}
})
}
}
+58
View File
@@ -0,0 +1,58 @@
package httpapi
import (
"context"
"errors"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qaopsfields"
"knowledge-governance/internal/qaopsmirror"
"knowledge-governance/internal/qaopsquality"
"net/http"
)
type masterFieldWriter interface {
PatchMasterFields(context.Context, string, qaopsmirror.MasterFieldPatch, string) (qaopsmirror.MasterFieldReceipt, error)
}
func qaMasterFieldOptions(w http.ResponseWriter, r *http.Request, c Config) {
if !authorizeQAOps(w, r) {
return
}
if r.URL.RawQuery != "" {
qaOpsError(w, dobotaiops.ErrInvalidQuery)
return
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, 200, map[string]any{"data": map[string]any{"version": "qa-master-options-v1", "fields": qaopsfields.EditableOptions()}})
}
func qaMasterFieldPatch(w http.ResponseWriter, r *http.Request, c Config) {
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-master-fields") {
return
}
var q qaopsmirror.MasterFieldPatch
if decodeQualityJSON(w, r, &q, "input_hash", "input_epoch", "base_revision", "base_review_revision", "nonce", "fields") != nil {
writeJSON(w, 400, map[string]string{"error": "字段选项或编辑参数无效"})
return
}
writer, ok := c.QAOps.(masterFieldWriter)
if !ok || c.QAOpsTenantKey == "" {
qaOpsError(w, dobotaiops.ErrUnavailable)
return
}
identity, _ := sessionFrom(r.Context())
result, err := writer.PatchMasterFields(r.Context(), r.PathValue("id"), q, identity.Username)
if err != nil {
switch {
case errors.Is(err, qaopsquality.ErrDownvoted):
writeJSON(w, 409, map[string]string{"error": "问题已点踩,是否正确固定为否;未保存冲突选择,请重新读取"})
case errors.Is(err, qaopsquality.ErrConflict):
writeJSON(w, 409, map[string]string{"error": "字段或问答版本已变化,请重新读取后修改;未覆盖其他人的内容"})
case errors.Is(err, dobotaiops.ErrInvalidQuery):
writeJSON(w, 400, map[string]string{"error": "字段选项无效,未保存;请选择主表允许的内容"})
default:
qaOpsError(w, err)
}
return
}
writeJSON(w, 200, map[string]any{"data": result})
}
+23 -3
View File
@@ -68,9 +68,26 @@ func enrichQAQualityRecord(ctx context.Context, c Config, item *dobotaiops.Recor
if !ok {
return qaopsquality.ErrUnavailable
}
item.Quality, err = json.Marshal(v)
return attachQAQualityView(item, v)
}
func attachQAQualityView(item *dobotaiops.Record, view qaopsquality.View) error {
// A vote may change between the payload and quality reads; return the vote
// that actually produced this decision, not a contradictory older snapshot.
if view.MasterFeedback != nil && item.RecordOrigin != "" {
item.Feedback = *view.MasterFeedback
fields := make(map[string]string, len(item.MasterFields)+1)
for key, value := range item.MasterFields {
fields[key] = value
}
fields["is_correct"] = map[string]string{"correct": "是", "incorrect": "否", "pending": "待确认"}[view.Effective.Correctness]
item.MasterFields = fields
}
raw, err := json.Marshal(view)
item.Quality = raw
return err
}
func enrichQAQualityPage(ctx context.Context, c Config, page *dobotaiops.RecordPage) error {
if c.QAQuality == nil {
return nil
@@ -84,7 +101,7 @@ func enrichQAQualityPage(ctx context.Context, c Config, page *dobotaiops.RecordP
if !ok {
return qaopsquality.ErrUnavailable
}
page.Items[i].Quality, err = json.Marshal(v)
err = attachQAQualityView(&page.Items[i], v)
if err != nil {
return err
}
@@ -98,10 +115,13 @@ func enrichQAQualityPage(ctx context.Context, c Config, page *dobotaiops.RecordP
}
func walkQualityJSON(d *json.Decoder) error { return strictjson.Walk(d) }
func decodeQualityJSON(w http.ResponseWriter, r *http.Request, target any, required ...string) error {
return decodeGovernanceJSON(w, r, target, 64<<10, required...)
}
func decodeGovernanceJSON(w http.ResponseWriter, r *http.Request, target any, maxBytes int64, required ...string) error {
if r.URL.RawQuery != "" {
return qaopsquality.ErrInvalid
}
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64<<10))
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBytes))
if err != nil || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
return qaopsquality.ErrInvalid
}
+82
View File
@@ -0,0 +1,82 @@
package httpapi
import (
"context"
"errors"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qaopsmirror"
"knowledge-governance/internal/qaopsquality"
"net/http"
"time"
)
type weeklyDraftStore interface {
ReadWeeklyDraft(context.Context, string, time.Time) (qaopsmirror.WeeklyDraft, error)
SaveWeeklyDraft(context.Context, string, qaopsmirror.WeeklyDraftRequest, string, time.Time) (qaopsmirror.WeeklyDraftReceipt, error)
PrefillWeeklyDraft(context.Context, string, qaopsmirror.WeeklyDraftPrefillRequest, string, time.Time) (qaopsmirror.WeeklyDraftReceipt, error)
}
func weeklyDraftError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, qaopsquality.ErrConflict):
writeJSON(w, 409, map[string]string{"error": "本周草稿已被其他窗口修改;你的文字未被覆盖,请先下载或核对服务器版本", "code": "weekly_draft_conflict"})
case errors.Is(err, dobotaiops.ErrInvalidQuery):
writeJSON(w, 400, map[string]string{"error": "周次或草稿内容无效,请使用已到达的合法ISO周,正文不超过256KiB", "code": "weekly_draft_invalid"})
default:
writeJSON(w, 503, map[string]string{"error": "草稿存储暂不可用,请保留文字并重试;未标记为已保存", "code": "weekly_draft_unavailable"})
}
}
func qaWeeklyDraftRead(w http.ResponseWriter, r *http.Request, c Config) {
if !authorizeQAOps(w, r) {
return
}
if r.URL.RawQuery != "" {
weeklyDraftError(w, dobotaiops.ErrInvalidQuery)
return
}
store, ok := c.QAOps.(weeklyDraftStore)
if !ok || c.QAOpsTenantKey == "" {
weeklyDraftError(w, dobotaiops.ErrUnavailable)
return
}
w.Header().Set("Cache-Control", "no-store")
out, err := store.ReadWeeklyDraft(r.Context(), r.PathValue("week"), c.Now())
if err != nil {
weeklyDraftError(w, err)
return
}
writeJSON(w, 200, map[string]any{"data": out})
}
func qaWeeklyDraftWrite(w http.ResponseWriter, r *http.Request, c Config, prefill bool) {
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-weekly-draft") {
return
}
store, ok := c.QAOps.(weeklyDraftStore)
if !ok || c.QAOpsTenantKey == "" {
weeklyDraftError(w, dobotaiops.ErrUnavailable)
return
}
identity, _ := sessionFrom(r.Context())
var out qaopsmirror.WeeklyDraftReceipt
var err error
if prefill {
var q qaopsmirror.WeeklyDraftPrefillRequest
if decodeQualityJSON(w, r, &q, "base_revision", "nonce") != nil {
weeklyDraftError(w, dobotaiops.ErrInvalidQuery)
return
}
out, err = store.PrefillWeeklyDraft(r.Context(), r.PathValue("week"), q, identity.Username, c.Now())
} else {
var q qaopsmirror.WeeklyDraftRequest
if decodeGovernanceJSON(w, r, &q, 512<<10, "base_revision", "nonce", "markdown") != nil {
weeklyDraftError(w, dobotaiops.ErrInvalidQuery)
return
}
out, err = store.SaveWeeklyDraft(r.Context(), r.PathValue("week"), q, identity.Username, c.Now())
}
if err != nil {
weeklyDraftError(w, err)
return
}
writeJSON(w, 200, map[string]any{"data": out})
}
+6
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) })
@@ -199,6 +200,11 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("GET /api/v1/qa-ops/status", func(w http.ResponseWriter, r *http.Request) {
qaOpsStatus(w, r, config)
})
mux.HandleFunc("GET /api/v1/qa-ops/master/weekly-drafts/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyDraftRead(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-drafts/{week}", func(w http.ResponseWriter, r *http.Request) { qaWeeklyDraftWrite(w, r, config, false) })
mux.HandleFunc("POST /api/v1/qa-ops/master/weekly-drafts/{week}/prefill", func(w http.ResponseWriter, r *http.Request) { qaWeeklyDraftWrite(w, r, config, true) })
mux.HandleFunc("GET /api/v1/qa-ops/master/field-options", func(w http.ResponseWriter, r *http.Request) { qaMasterFieldOptions(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/master/records/{id}/fields", func(w http.ResponseWriter, r *http.Request) { qaMasterFieldPatch(w, r, config) })
mux.HandleFunc("GET /api/v1/qa-ops/master/records", func(w http.ResponseWriter, r *http.Request) { withQAMaster(w, r, config, listQAOpsRecords) })
mux.HandleFunc("GET /api/v1/qa-ops/master/records/{id}", func(w http.ResponseWriter, r *http.Request) { withQAMaster(w, r, config, getQAOpsRecord) })
mux.HandleFunc("POST /api/v1/qa-ops/master/quality/query", func(w http.ResponseWriter, r *http.Request) { withQAMaster(w, r, config, qaQualityQuery) })
@@ -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();
@@ -0,0 +1,20 @@
DO $$ BEGIN
IF EXISTS(SELECT 1 FROM qa_ops_weekly_draft_revisions) OR EXISTS(SELECT 1 FROM qa_ops_master_field_edits) THEN
RAISE EXCEPTION 'Saved human edits or weekly drafts exist; retain the additive schema for image rollback';
END IF;
END $$;
DROP TABLE qa_ops_weekly_draft_revisions;
DROP TABLE qa_ops_weekly_drafts;
DROP VIEW qa_ops_master_read_model;
CREATE VIEW qa_ops_master_read_model AS
SELECT m.*,a.ai_fields,t.background_tasks,qa_ops_fill_empty_fields(m.local_fields||jsonb_build_object('question_chinese',m.chinese_question),a.ai_fields) AS effective_fields
FROM qa_ops_master_records m LEFT JOIN LATERAL (
SELECT COALESCE(jsonb_object_agg(f.key,f.value ORDER BY o.created_at,o.work_id),'{}'::jsonb) AS ai_fields
FROM qa_ops_ai_outputs o CROSS JOIN LATERAL jsonb_each(o.applied_fields) f
WHERE o.tenant_key=m.tenant_key AND o.record_id=m.id AND o.input_hash=CASE WHEN o.kind='evaluation' THEN m.quality_hash ELSE encode(sha256(convert_to(m.question,'UTF8')),'hex') END
) a ON true LEFT JOIN LATERAL (
SELECT COALESCE(jsonb_agg(jsonb_build_object('id',w.id,'record_id',w.record_id,'kind',w.kind,'state',w.state,'stage',w.stage,'attempt',w.attempt,'error_code',w.error_code,'skip_reason',w.skip_reason,'started_at',w.started_at,'updated_at',w.updated_at)),'[]'::jsonb) AS background_tasks
FROM (SELECT DISTINCT ON (kind) * FROM qa_ops_ai_work WHERE tenant_key=m.tenant_key AND record_id=m.id ORDER BY kind,created_at DESC,id DESC) w
) t ON true;
DROP TABLE qa_ops_master_field_edits;
DROP TABLE qa_ops_master_field_overrides;
@@ -0,0 +1,27 @@
-- Sparse human overrides keep untouched stored/AI fields and original payload immutable.
CREATE TABLE qa_ops_master_field_overrides (
tenant_key text NOT NULL,record_id text NOT NULL,revision bigint NOT NULL CHECK(revision>0),input_hash text NOT NULL,review_revision bigint NOT NULL CHECK(review_revision>=0),fields jsonb NOT NULL CHECK(jsonb_typeof(fields)='object'),updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(tenant_key,record_id),FOREIGN KEY(tenant_key,record_id) REFERENCES qa_ops_master_records(tenant_key,id)
);
CREATE TABLE qa_ops_master_field_edits (
tenant_key text NOT NULL,record_id text NOT NULL,revision bigint NOT NULL CHECK(revision>0),input_hash text NOT NULL,review_revision bigint NOT NULL,changed_fields jsonb NOT NULL,before_fields jsonb NOT NULL,fields jsonb NOT NULL,actor text NOT NULL,nonce text NOT NULL,request_hash text NOT NULL,created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(tenant_key,record_id,revision),UNIQUE(tenant_key,record_id,nonce),FOREIGN KEY(tenant_key,record_id) REFERENCES qa_ops_master_records(tenant_key,id)
);
CREATE OR REPLACE VIEW qa_ops_master_read_model AS
SELECT m.*,a.ai_fields,t.background_tasks,qa_ops_fill_empty_fields(m.local_fields||jsonb_build_object('question_chinese',m.chinese_question),a.ai_fields)||COALESCE(CASE WHEN e.input_hash=m.quality_hash AND e.review_revision=COALESCE(h.review_revision,0) THEN e.fields END,'{}'::jsonb) AS effective_fields,COALESCE(e.revision,0) AS field_edit_revision,COALESCE(CASE WHEN e.input_hash=m.quality_hash AND e.review_revision=COALESCE(h.review_revision,0) THEN e.fields END,'{}'::jsonb) AS inline_fields
FROM qa_ops_master_records m LEFT JOIN LATERAL (
SELECT COALESCE(jsonb_object_agg(f.key,f.value ORDER BY o.created_at,o.work_id),'{}'::jsonb) AS ai_fields
FROM qa_ops_ai_outputs o CROSS JOIN LATERAL jsonb_each(o.applied_fields) f
WHERE o.tenant_key=m.tenant_key AND o.record_id=m.id AND o.input_hash=CASE WHEN o.kind='evaluation' THEN m.quality_hash ELSE encode(sha256(convert_to(m.question,'UTF8')),'hex') END
) a ON true LEFT JOIN LATERAL (
SELECT COALESCE(jsonb_agg(jsonb_build_object('id',w.id,'record_id',w.record_id,'kind',w.kind,'state',w.state,'stage',w.stage,'attempt',w.attempt,'error_code',w.error_code,'skip_reason',w.skip_reason,'started_at',w.started_at,'updated_at',w.updated_at)),'[]'::jsonb) AS background_tasks
FROM (SELECT DISTINCT ON (kind) * FROM qa_ops_ai_work WHERE tenant_key=m.tenant_key AND record_id=m.id ORDER BY kind,created_at DESC,id DESC) w
) t ON true LEFT JOIN qa_ops_quality_records h ON h.tenant_key=m.tenant_key||'::master' AND h.record_id=m.id LEFT JOIN qa_ops_master_field_overrides e ON e.tenant_key=m.tenant_key AND e.record_id=m.id;
-- One shared editable document per tenant/week, with durable idempotent save receipts.
CREATE TABLE qa_ops_weekly_drafts (
tenant_key text NOT NULL,week text NOT NULL CHECK(week ~ '^[0-9]{4}-W[0-9]{2}$'),revision bigint NOT NULL CHECK(revision>0),markdown text NOT NULL CHECK(octet_length(markdown)<=262144),seed jsonb NOT NULL CHECK(jsonb_typeof(seed)='object'),updated_by text NOT NULL,created_at timestamptz NOT NULL DEFAULT now(),updated_at timestamptz NOT NULL DEFAULT now(),PRIMARY KEY(tenant_key,week)
);
CREATE TABLE qa_ops_weekly_draft_revisions (
tenant_key text NOT NULL,week text NOT NULL,revision bigint NOT NULL CHECK(revision>0),operation text NOT NULL CHECK(operation IN ('edit','prefill')),markdown text NOT NULL CHECK(octet_length(markdown)<=262144),seed jsonb NOT NULL CHECK(jsonb_typeof(seed)='object'),actor text NOT NULL,nonce text NOT NULL,request_hash text NOT NULL,created_at timestamptz NOT NULL DEFAULT now(),PRIMARY KEY(tenant_key,week,revision),UNIQUE(tenant_key,week,nonce),FOREIGN KEY(tenant_key,week) REFERENCES qa_ops_weekly_drafts(tenant_key,week)
);
@@ -0,0 +1,15 @@
DROP TRIGGER qa_mirror_feedback_master_revision ON qa_ops_mirror_records;
DROP FUNCTION qa_ops_master_feedback_revision();
DROP VIEW qa_ops_master_read_model;
CREATE OR REPLACE VIEW qa_ops_master_read_model AS
SELECT m.*,a.ai_fields,t.background_tasks,qa_ops_fill_empty_fields(m.local_fields||jsonb_build_object('question_chinese',m.chinese_question),a.ai_fields)||COALESCE(CASE WHEN e.input_hash=m.quality_hash AND e.review_revision=COALESCE(h.review_revision,0) THEN e.fields END,'{}'::jsonb) AS effective_fields,COALESCE(e.revision,0) AS field_edit_revision,COALESCE(CASE WHEN e.input_hash=m.quality_hash AND e.review_revision=COALESCE(h.review_revision,0) THEN e.fields END,'{}'::jsonb) AS inline_fields
FROM qa_ops_master_records m LEFT JOIN LATERAL (
SELECT COALESCE(jsonb_object_agg(f.key,f.value ORDER BY o.created_at,o.work_id),'{}'::jsonb) AS ai_fields
FROM qa_ops_ai_outputs o CROSS JOIN LATERAL jsonb_each(o.applied_fields) f
WHERE o.tenant_key=m.tenant_key AND o.record_id=m.id AND o.input_hash=CASE WHEN o.kind='evaluation' THEN m.quality_hash ELSE encode(sha256(convert_to(m.question,'UTF8')),'hex') END
) a ON true LEFT JOIN LATERAL (
SELECT COALESCE(jsonb_agg(jsonb_build_object('id',w.id,'record_id',w.record_id,'kind',w.kind,'state',w.state,'stage',w.stage,'attempt',w.attempt,'error_code',w.error_code,'skip_reason',w.skip_reason,'started_at',w.started_at,'updated_at',w.updated_at)),'[]'::jsonb) AS background_tasks
FROM (SELECT DISTINCT ON (kind) * FROM qa_ops_ai_work WHERE tenant_key=m.tenant_key AND record_id=m.id ORDER BY kind,created_at DESC,id DESC) w
) t ON true LEFT JOIN qa_ops_quality_records h ON h.tenant_key=m.tenant_key||'::master' AND h.record_id=m.id LEFT JOIN qa_ops_master_field_overrides e ON e.tenant_key=m.tenant_key AND e.record_id=m.id;
DROP INDEX idx_qa_master_source_feedback;
DROP FUNCTION qa_ops_feedback_is_down(jsonb);
@@ -0,0 +1,33 @@
-- Feedback is a derived business rule; imported payloads and human evidence stay immutable.
CREATE FUNCTION qa_ops_feedback_is_down(value jsonb) RETURNS boolean LANGUAGE sql IMMUTABLE AS $$
SELECT COALESCE(value->>'asker_value'='down',false) OR CASE WHEN jsonb_typeof(value->'down')='number' THEN (value->>'down')::numeric>0 ELSE false END
$$;
CREATE INDEX idx_qa_master_source_feedback ON qa_ops_master_source_links(tenant_key,master_id,source_kind,source_id);
CREATE FUNCTION qa_ops_master_feedback_revision() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP='UPDATE' AND OLD.payload->'feedback' IS NOT DISTINCT FROM NEW.payload->'feedback' THEN RETURN NEW; END IF;
IF EXISTS(SELECT 1 FROM qa_ops_master_source_links WHERE tenant_key=NEW.tenant_key AND source_kind='dobotai_2_0' AND source_id=NEW.id) THEN
UPDATE qa_ops_master_state SET revision=revision+1,updated_at=clock_timestamp() WHERE tenant_key=NEW.tenant_key;
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER qa_mirror_feedback_master_revision AFTER INSERT OR UPDATE OF payload ON qa_ops_mirror_records FOR EACH ROW EXECUTE FUNCTION qa_ops_master_feedback_revision();
-- The effective read contract changes once on activation, without rewriting any question row.
UPDATE qa_ops_master_state SET revision=revision+1,updated_at=clock_timestamp();
CREATE OR REPLACE VIEW qa_ops_master_read_model AS
SELECT m.*,a.ai_fields,t.background_tasks,qa_ops_fill_empty_fields(m.local_fields||jsonb_build_object('question_chinese',m.chinese_question),a.ai_fields)||COALESCE(CASE WHEN e.input_hash=m.quality_hash AND e.review_revision=COALESCE(h.review_revision,0) THEN e.fields END,'{}'::jsonb)||CASE WHEN qa_ops_feedback_is_down(f.current_feedback) THEN '{"is_correct":"否"}'::jsonb ELSE '{}'::jsonb END AS effective_fields,COALESCE(e.revision,0) AS field_edit_revision,COALESCE(CASE WHEN e.input_hash=m.quality_hash AND e.review_revision=COALESCE(h.review_revision,0) THEN e.fields END,'{}'::jsonb) AS inline_fields,f.current_feedback
FROM qa_ops_master_records m LEFT JOIN LATERAL (
SELECT COALESCE((
SELECT jsonb_build_object('asker_value',CASE WHEN bool_or(r.payload#>>'{feedback,asker_value}'='down') THEN 'down' WHEN bool_or(r.payload#>>'{feedback,asker_value}'='up') THEN 'up' ELSE '' END,
'up',sum(COALESCE((r.payload#>>'{feedback,up}')::bigint,0)),'down',sum(COALESCE((r.payload#>>'{feedback,down}')::bigint,0)))
FROM qa_ops_master_source_links l JOIN qa_ops_mirror_records r ON r.tenant_key=l.tenant_key AND r.id=l.source_id
WHERE l.tenant_key=m.tenant_key AND l.master_id=m.id AND l.source_kind='dobotai_2_0' HAVING count(*)>0
),jsonb_build_object('asker_value','','up',0,'down',0)||COALESCE(NULLIF(m.payload->'feedback','null'::jsonb),'{}'::jsonb)) AS current_feedback
) f ON true LEFT JOIN LATERAL (
SELECT COALESCE(jsonb_object_agg(f.key,f.value ORDER BY o.created_at,o.work_id),'{}'::jsonb) AS ai_fields
FROM qa_ops_ai_outputs o CROSS JOIN LATERAL jsonb_each(o.applied_fields) f
WHERE o.tenant_key=m.tenant_key AND o.record_id=m.id AND o.input_hash=CASE WHEN o.kind='evaluation' THEN m.quality_hash ELSE encode(sha256(convert_to(m.question,'UTF8')),'hex') END
) a ON true LEFT JOIN LATERAL (
SELECT COALESCE(jsonb_agg(jsonb_build_object('id',w.id,'record_id',w.record_id,'kind',w.kind,'state',w.state,'stage',w.stage,'attempt',w.attempt,'error_code',w.error_code,'skip_reason',w.skip_reason,'started_at',w.started_at,'updated_at',w.updated_at)),'[]'::jsonb) AS background_tasks
FROM (SELECT DISTINCT ON (kind) * FROM qa_ops_ai_work WHERE tenant_key=m.tenant_key AND record_id=m.id ORDER BY kind,created_at DESC,id DESC) w
) t ON true LEFT JOIN qa_ops_quality_records h ON h.tenant_key=m.tenant_key||'::master' AND h.record_id=m.id LEFT JOIN qa_ops_master_field_overrides e ON e.tenant_key=m.tenant_key AND e.record_id=m.id;
@@ -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) != 59 {
t.Fatalf("migration count = %d, want 59", len(migrations))
}
if migrations[0].Version != 1 || !strings.Contains(migrations[0].UpSQL, "CREATE TABLE IF NOT EXISTS jobs") {
t.Fatalf("migration 1 = %#v", migrations[0])
@@ -0,0 +1,30 @@
package postgres
import (
"strings"
"testing"
)
func TestMasterDownvoteMigrationPreservesOriginalAndSavedHumanData(t *testing.T) {
migrations, err := loadMigrations()
if err != nil {
t.Fatal(err)
}
m := migrations[58]
if m.Version != 59 {
t.Fatal("missing feedback-rule migration")
}
for _, marker := range []string{"CREATE FUNCTION qa_ops_feedback_is_down", "qa_ops_master_source_links", "l.master_id=m.id", "l.source_kind='dobotai_2_0'", "current_feedback", "'{\"is_correct\":\"否\"}'::jsonb", "e.input_hash=m.quality_hash AND e.review_revision=COALESCE(h.review_revision,0)", "qa_mirror_feedback_master_revision", "CREATE INDEX idx_qa_master_source_feedback"} {
if !strings.Contains(m.UpSQL, marker) {
t.Fatalf("downvote read contract missing: %s", marker)
}
}
for _, marker := range []string{"UPDATE qa_ops_master_records", "UPDATE qa_ops_quality_reviews", "UPDATE qa_ops_master_field_overrides", "DELETE FROM", "DROP TABLE"} {
if strings.Contains(m.UpSQL, marker) || strings.Contains(m.DownSQL, marker) {
t.Fatalf("derived feedback migration mutates saved business or human evidence: %s", marker)
}
}
if !strings.Contains(m.DownSQL, "AS inline_fields") || !strings.Contains(m.DownSQL, "DROP TRIGGER qa_mirror_feedback_master_revision") {
t.Fatal("rollback must retain sparse human fields and remove only the new derived feedback contract")
}
}
@@ -0,0 +1,30 @@
package postgres
import (
"strings"
"testing"
)
func TestInlineFieldsWeeklyDraftMigrationIsAdditiveTenantScopedAndRollbackProtected(t *testing.T) {
migrations, e := loadMigrations()
if e != nil {
t.Fatal(e)
}
m := migrations[57]
if m.Version != 58 {
t.Fatal("missing migration 58")
}
for _, marker := range []string{"CREATE TABLE qa_ops_master_field_overrides", "CREATE TABLE qa_ops_master_field_edits", "CREATE TABLE qa_ops_weekly_drafts", "CREATE TABLE qa_ops_weekly_draft_revisions", "UNIQUE(tenant_key,record_id,nonce)", "UNIQUE(tenant_key,week,nonce)", "e.input_hash=m.quality_hash AND e.review_revision=COALESCE(h.review_revision,0)", "field_edit_revision", "inline_fields"} {
if !strings.Contains(m.UpSQL, marker) {
t.Fatalf("migration lost sparse tenant/input/review/idempotency contract: %s", marker)
}
}
if strings.Contains(m.UpSQL, "UPDATE qa_ops_master_records SET payload") || strings.Contains(m.UpSQL, "UPDATE qa_ops_quality_reviews") {
t.Fatal("migration rewrites original records or human history")
}
for _, marker := range []string{"RAISE EXCEPTION", "SELECT 1 FROM qa_ops_weekly_draft_revisions", "SELECT 1 FROM qa_ops_master_field_edits"} {
if !strings.Contains(m.DownSQL, marker) {
t.Fatalf("down migration must refuse to discard saved human data: %s", marker)
}
}
}
+2 -6
View File
@@ -3,6 +3,7 @@ package qaopsai
import (
"encoding/json"
"io"
"knowledge-governance/internal/qaopsfields"
"knowledge-governance/internal/strictjson"
"strings"
"unicode/utf8"
@@ -12,12 +13,7 @@ const DictionaryVersion = "qa-approved-labels-v1"
const EvaluationPromptVersion = "qa-evaluate-evidence-v1"
const TranslationPromptVersion = "qa-question-zh-v1"
var Taxonomy = map[string][]string{
"is_correct": {"是", "否", "待确认"},
"product_category": {"CR/CRA/H/AP", "CRV", "CR配件", "Nova及系列", "Nova配件", "MG400", "MG400配件", "M1 Pro", "VX500", "新示教器", "DobotStudio Pro", "仿真软件", "维护工具", "教育所有产品", "人形机器人", "四六足机器人", "X-Trainer", "码垛解决方案", "码垛插件", "焊接解决方案", "焊接插件", "移动复合机器人", "生态插件", "生态合作", "安全皮肤", "未知"},
"problem_type": {"参数", "故障", "使用配置", "二次开发", "资料获取", "咨询", "认证", "案例", "售后", "培训与学习", "其他"},
"root_cause": {"知识缺失", "检索不到", "结果不清", "答案生成错误", "问题质量差", "非知识范围", "知识过期"},
}
var Taxonomy = qaopsfields.ClassificationTaxonomy
func allowedLabel(field, value string) bool {
for _, label := range Taxonomy[field] {
+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
+5 -4
View File
@@ -53,6 +53,7 @@ type recordMeta struct {
ID, Hash, Status, Question string
Revision int64
Fields map[string]string
InlineFields map[string]string
Coverage dobotaiops.CoverageCheck
View qaopsquality.View
}
@@ -81,7 +82,7 @@ func promptVersion(kind string) string {
return EvaluationPromptVersion
}
func (s *Store) readMetas(ctx context.Context, tx pgx.Tx, ids []string, scope *Scope) ([]recordMeta, error) {
query := `SELECT m.id,m.quality_hash,m.row_revision,m.status,m.question,m.effective_fields,m.coverage_result,EXISTS(SELECT 1 FROM qa_ops_ai_outputs o JOIN qa_ops_ai_work w ON w.tenant_key=o.tenant_key AND w.id=o.work_id WHERE o.tenant_key=m.tenant_key AND o.record_id=m.id AND o.kind='evaluation' AND o.input_hash=m.quality_hash AND w.state='succeeded' AND w.prompt_version='` + EvaluationPromptVersion + `' AND o.payload->'fields'?'root_cause' AND o.payload->'fields'->'root_cause'->>'value'='') FROM qa_ops_master_read_model m WHERE tenant_key=$1`
query := `SELECT m.id,m.quality_hash,m.row_revision,m.status,m.question,m.effective_fields,m.coverage_result,EXISTS(SELECT 1 FROM qa_ops_ai_outputs o JOIN qa_ops_ai_work w ON w.tenant_key=o.tenant_key AND w.id=o.work_id WHERE o.tenant_key=m.tenant_key AND o.record_id=m.id AND o.kind='evaluation' AND o.input_hash=m.quality_hash AND w.state='succeeded' AND w.prompt_version='` + EvaluationPromptVersion + `' AND o.payload->'fields'?'root_cause' AND o.payload->'fields'->'root_cause'->>'value'=''),m.inline_fields FROM qa_ops_master_read_model m WHERE tenant_key=$1`
args := []any{s.tenant}
if scope != nil && len(scope.IDs) == 0 {
window, err := dobotaiops.NewWindow(s.tenant, scope.Start, scope.End, 90*24*time.Hour, time.Now())
@@ -103,8 +104,8 @@ func (s *Store) readMetas(ctx context.Context, tx pgx.Tx, ids []string, scope *S
keys := []dobotaiops.QualityKey{}
for rows.Next() {
var m recordMeta
var fields, coverage []byte
if rows.Scan(&m.ID, &m.Hash, &m.Revision, &m.Status, &m.Question, &fields, &coverage, &m.RootHandled) != nil || json.Unmarshal(fields, &m.Fields) != nil || json.Unmarshal(coverage, &m.Coverage) != nil {
var fields, coverage, edits []byte
if rows.Scan(&m.ID, &m.Hash, &m.Revision, &m.Status, &m.Question, &fields, &coverage, &m.RootHandled, &edits) != nil || json.Unmarshal(fields, &m.Fields) != nil || json.Unmarshal(coverage, &m.Coverage) != nil || json.Unmarshal(edits, &m.InlineFields) != nil {
rows.Close()
return nil, ErrUnavailable
}
@@ -139,7 +140,7 @@ func (s *Store) readMetas(ctx context.Context, tx pgx.Tx, ids []string, scope *S
if !ok {
return nil, ErrUnavailable
}
metas[i].View = qaopsquality.ProjectMaster(v, metas[i].Fields, metas[i].Coverage)
metas[i].View = qaopsquality.ProjectMasterWithEdits(v, metas[i].Fields, metas[i].Coverage, metas[i].InlineFields)
}
return metas, nil
}
+25
View File
@@ -0,0 +1,25 @@
package qaopsfields
var ClassificationTaxonomy = map[string][]string{
"is_correct": {"是", "否", "待确认"},
"product_category": {"CR/CRA/H/AP", "CRV", "CR配件", "Nova及系列", "Nova配件", "MG400", "MG400配件", "M1 Pro", "VX500", "新示教器", "DobotStudio Pro", "仿真软件", "维护工具", "教育所有产品", "人形机器人", "四六足机器人", "X-Trainer", "码垛解决方案", "码垛插件", "焊接解决方案", "焊接插件", "移动复合机器人", "生态插件", "生态合作", "安全皮肤", "未知"},
"problem_type": {"参数", "故障", "使用配置", "二次开发", "资料获取", "咨询", "认证", "案例", "售后", "培训与学习", "其他"},
"root_cause": {"知识缺失", "检索不到", "结果不清", "答案生成错误", "问题质量差", "非知识范围", "知识过期"},
}
func EditableOptions() map[string][]string {
out := make(map[string][]string, len(ClassificationTaxonomy)+1)
for key, values := range ClassificationTaxonomy {
out[key] = append([]string(nil), values...)
}
out["coverage"] = []string{"是", "否", "否但不计入"}
return out
}
func ValidEditableValue(field, value string) bool {
for _, label := range EditableOptions()[field] {
if value == label {
return true
}
}
return false
}
@@ -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,93 @@
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")
}
}
// The assertion belongs to migration 57, not whichever newer empty schema is last.
for {
var version int64
if e := p.QueryRow(ctx, `SELECT max(version)FROM schema_migrations`).Scan(&version); e != nil {
t.Fatal(e)
}
if version == 57 {
break
}
if version < 57 {
t.Fatal("reported-history migration missing")
}
if e := pg.RollbackLatestMigration(ctx, p); e != nil {
t.Fatalf("could not reach the historical-data rollback guard: %v", e)
}
}
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)
}
}
+16 -4
View File
@@ -18,7 +18,9 @@ type dashboardRecord struct {
at time.Time
identity dobotaiops.ActorIdentity
fields map[string]string
edits map[string]string
coverage dobotaiops.CoverageCheck
feedback dobotaiops.RecordFeedback
}
func dashboardRate(n, d int) qaopsquality.Rate {
@@ -118,7 +120,7 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
rowsSQL := `SELECT id,asked_at,identity,quality_hash FROM qa_ops_mirror_records WHERE tenant_key=$1 AND asked_at>=$2 AND asked_at<$3 AND ($4='' OR position(lower($4) IN lower(question))>0) ORDER BY id LIMIT 100001`
if master {
rowsSQL = strings.ReplaceAll(rowsSQL, "qa_ops_mirror_records", "qa_ops_master_read_model")
rowsSQL = strings.ReplaceAll(rowsSQL, "SELECT id,asked_at,identity,quality_hash FROM", "SELECT id,asked_at,identity,quality_hash,effective_fields,coverage_result FROM")
rowsSQL = strings.ReplaceAll(rowsSQL, "SELECT id,asked_at,identity,quality_hash FROM", "SELECT id,asked_at,identity,quality_hash,effective_fields,coverage_result,inline_fields,current_feedback FROM")
rowsSQL = strings.ReplaceAll(rowsSQL, "lower(question)", "lower(question||E'\\n'||chinese_question||E'\\n'||COALESCE(ai_fields->>'question_chinese',''))")
}
rows, e := tx.Query(ctx, rowsSQL, s.tenant, lower, q.Window.End, q.Keyword)
@@ -132,14 +134,20 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
var identity []byte
var scanErr error
if master {
var fields, coverage []byte
scanErr = rows.Scan(&r.id, &r.at, &identity, &r.hash, &fields, &coverage)
var fields, coverage, edits, feedback []byte
scanErr = rows.Scan(&r.id, &r.at, &identity, &r.hash, &fields, &coverage, &edits, &feedback)
if scanErr == nil {
scanErr = json.Unmarshal(fields, &r.fields)
if scanErr == nil {
scanErr = json.Unmarshal(edits, &r.edits)
}
}
if scanErr == nil {
scanErr = json.Unmarshal(coverage, &r.coverage)
}
if scanErr == nil {
scanErr = json.Unmarshal(feedback, &r.feedback)
}
} else {
scanErr = rows.Scan(&r.id, &r.at, &identity, &r.hash)
}
@@ -183,7 +191,7 @@ func (s *Store) readDashboard(ctx context.Context, q dobotaiops.RecordQuery, mas
if master {
for _, r := range records {
if v, ok := views[r.id]; ok {
views[r.id] = qaopsquality.ProjectMaster(v, r.fields, r.coverage)
views[r.id] = qaopsquality.ProjectMasterWithEdits(v, r.fields, r.coverage, r.edits, r.feedback)
}
}
}
@@ -256,6 +264,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)
}
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ func (s *Store) MasterQualityStore() *qaopsquality.Store {
return qaopsquality.NewStore(s.pool, s.tenant+"::master")
}
const masterBaseSQL = `WITH records AS (SELECT id,asked_at,question||E'\n'||chinese_question||E'\n'||COALESCE(ai_fields->>'question_chinese','') AS question,status,identity,quality_hash,jsonb_set(payload,'{master_fields}',qa_ops_fill_empty_fields(COALESCE(payload->'master_fields','{}'::jsonb),ai_fields))||jsonb_build_object('record_origin',origin,'background_tasks',background_tasks) AS payload FROM qa_ops_master_read_model WHERE tenant_key=$1)`
const masterBaseSQL = `WITH records AS (SELECT id,asked_at,question||E'\n'||chinese_question||E'\n'||COALESCE(ai_fields->>'question_chinese','') AS question,status,identity,quality_hash,jsonb_set(payload,'{master_fields}',effective_fields)||jsonb_build_object('record_origin',origin,'background_tasks',background_tasks,'field_edit_revision',field_edit_revision,'feedback',current_feedback) AS payload FROM qa_ops_master_read_model WHERE tenant_key=$1)`
var masterMetadataBase = strings.NewReplacer("qa_ops_mirror_records", "qa_ops_master_read_model", "h.tenant_key=m.tenant_key", "h.tenant_key=m.tenant_key||'::master'", "m.question", "(m.question||E'\\n'||m.chinese_question||E'\\n'||COALESCE(m.ai_fields->>'question_chinese','')) AS question").Replace(localMetadataBase)
@@ -0,0 +1,86 @@
package qaopsmirror
import (
"context"
"encoding/json"
"knowledge-governance/internal/dobotaiops"
pg "knowledge-governance/internal/platform/postgres"
"testing"
"time"
)
func TestMasterDownvoteOverridesStoredAndInlineCorrectnessAcrossReaders(t *testing.T) {
p := mirrorFixture(t)
ctx := context.Background()
s := NewStore(p, "fixture-feedback-rule")
queue := pg.NewStore(p)
entry := fixtureEntry("feedback-rule", "已有资料")
var wire map[string]any
if err := json.Unmarshal(entry.Payload, &wire); err != nil {
t.Fatal(err)
}
wire["asked_at"] = "2026-10-06T08:00:00+08:00"
entry.Payload, _ = json.Marshal(wire)
job := claimMirrorJob(t, s, queue, "feedback-rule-seed")
if err := s.HandleSync(ctx, *job, func(context.Context) (Source, error) {
return &fixtureSource{rows: []dobotaiops.MirrorRecord{entry}}, nil
}); err != nil {
t.Fatal(err)
}
if _, err := p.Exec(ctx, `UPDATE qa_ops_master_records SET local_fields=local_fields||'{"coverage":"是","is_correct":"是","product_category":"MG400","problem_type":"参数"}'::jsonb WHERE tenant_key=$1 AND id=$2`, s.tenant, "feedback-rule"); err != nil {
t.Fatal(err)
}
rec, err := s.GetMasterRecord(ctx, s.tenant, "feedback-rule")
if err != nil {
t.Fatal(err)
}
keys := []dobotaiops.QualityKey{{ID: rec.ID, InputHash: rec.QualityInputHash}}
views, err := s.ReadMasterQualityViews(ctx, keys)
if err != nil {
t.Fatal(err)
}
v := views[rec.ID]
receipt, err := s.PatchMasterFields(ctx, rec.ID, MasterFieldPatch{InputHash: v.InputHash, InputEpoch: v.InputEpoch, BaseReviewRevision: v.Revision, Nonce: "fixture_feedback_rule_001", Fields: map[string]string{"is_correct": "是"}}, "fixture-admin")
if err != nil || receipt.SavedRevision != 1 {
t.Fatal("fixture inline positive edit failed", err)
}
var before string
if err = p.QueryRow(ctx, `SELECT md5(payload::text||original_fields::text||local_fields::text) FROM qa_ops_master_records WHERE tenant_key=$1 AND id=$2`, s.tenant, rec.ID).Scan(&before); err != nil {
t.Fatal(err)
}
// Only the replaceable local source mirror receives the live feedback update.
var revisionBefore, revisionAfter int64
if err = p.QueryRow(ctx, `SELECT revision FROM qa_ops_master_state WHERE tenant_key=$1`, s.tenant).Scan(&revisionBefore); err != nil {
t.Fatal(err)
}
if _, err = p.Exec(ctx, `UPDATE qa_ops_mirror_records SET payload=jsonb_set(payload,'{feedback}','{"asker_value":"down","up":0,"down":1}') WHERE tenant_key=$1 AND id=$2`, s.tenant, rec.ID); err != nil {
t.Fatal(err)
}
if err = p.QueryRow(ctx, `SELECT revision FROM qa_ops_master_state WHERE tenant_key=$1`, s.tenant).Scan(&revisionAfter); err != nil || revisionAfter <= revisionBefore {
t.Fatal("current master feedback changed without invalidating its snapshot revision", err)
}
fresh, err := s.GetMasterRecord(ctx, s.tenant, rec.ID)
if err != nil || fresh.Feedback.Down != 1 || fresh.MasterFields["is_correct"] != "否" {
t.Fatalf("live downvote did not force detail/master fields to incorrect: fields=%v feedback=%+v error=%v", fresh.MasterFields, fresh.Feedback, err)
}
page, err := s.ListMasterRecords(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: rec.AskedAt.Add(-time.Hour), End: rec.AskedAt.Add(time.Hour)}, Limit: 10})
if err != nil || len(page.Items) != 1 || page.Items[0].MasterFields["is_correct"] != "否" {
t.Fatal("list differs from detail", err)
}
views, err = s.ReadMasterQualityViews(ctx, keys)
if err != nil || views[rec.ID].Effective.Correctness != "incorrect" {
t.Fatal("effective quality retained the old positive inline edit", err)
}
if _, err = s.PatchMasterFields(ctx, rec.ID, MasterFieldPatch{InputHash: fresh.QualityInputHash, InputEpoch: views[rec.ID].InputEpoch, BaseRevision: 1, BaseReviewRevision: views[rec.ID].Revision, Nonce: "fixture_feedback_rule_002", Fields: map[string]string{"is_correct": "是"}}, "fixture-admin"); err == nil {
t.Fatal("an active downvote accepted a positive correctness write")
}
start, _ := time.Parse(time.RFC3339, "2026-10-05T00:00:00+08:00")
dashboard, err := s.ReadMasterDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: start.AddDate(0, 0, 7)}})
if err != nil || dashboard.Quality.Rates.Correctness.Numerator != 0 || dashboard.Quality.Rates.Correctness.Denominator != 1 {
t.Fatal("dashboard did not consume the same downvote rule", err)
}
var after, originalInline string
if err = p.QueryRow(ctx, `SELECT md5(m.payload::text||m.original_fields::text||m.local_fields::text),e.fields->>'is_correct' FROM qa_ops_master_records m JOIN qa_ops_master_field_overrides e ON e.tenant_key=m.tenant_key AND e.record_id=m.id WHERE m.tenant_key=$1 AND m.id=$2`, s.tenant, rec.ID).Scan(&after, &originalInline); err != nil || after != before || originalInline != "是" {
t.Fatal("feedback projection rewrote original questions, labels or human evidence", err)
}
}
+155
View File
@@ -0,0 +1,155 @@
package qaopsmirror
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qaopsfields"
"knowledge-governance/internal/qaopsquality"
"regexp"
"strings"
"time"
"unicode/utf8"
)
type MasterFieldPatch struct {
InputHash string `json:"input_hash"`
InputEpoch int64 `json:"input_epoch"`
BaseRevision int64 `json:"base_revision"`
BaseReviewRevision int64 `json:"base_review_revision"`
Nonce string `json:"nonce"`
Fields map[string]string `json:"fields"`
}
type MasterFieldReceipt struct {
SavedRevision int64 `json:"saved_revision"`
Replayed bool `json:"replayed"`
}
var inlineHash = regexp.MustCompile(`^[a-f0-9]{64}$`)
var inlineNonce = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.:-]{15,127}$`)
func validInlineID(value string) bool {
return value != "" && len(value) <= 256 && utf8.ValidString(value) && !strings.ContainsAny(value, "\x00\x1f")
}
func (s *Store) PatchMasterFields(ctx context.Context, id string, q MasterFieldPatch, actor string) (MasterFieldReceipt, error) {
if !s.valid() {
return MasterFieldReceipt{}, dobotaiops.ErrUnavailable
}
if !validInlineID(id) || !validInlineID(actor) || !inlineHash.MatchString(q.InputHash) || !inlineNonce.MatchString(q.Nonce) || q.InputEpoch < 1 || q.BaseRevision < 0 || q.BaseReviewRevision < 0 || len(q.Fields) < 1 || len(q.Fields) > 5 {
return MasterFieldReceipt{}, dobotaiops.ErrInvalidQuery
}
for field, value := range q.Fields {
if !qaopsfields.ValidEditableValue(field, value) {
return MasterFieldReceipt{}, dobotaiops.ErrInvalidQuery
}
}
ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return MasterFieldReceipt{}, dobotaiops.ErrUnavailable
}
defer tx.Rollback(context.Background())
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1||chr(31)||$2,258))`, s.tenant, id); err != nil {
return MasterFieldReceipt{}, dobotaiops.ErrUnavailable
}
payload, _ := json.Marshal(q)
sum := sha256.Sum256(payload)
requestHash := hex.EncodeToString(sum[:])
var savedRevision int64
var savedHash, savedActor string
err = tx.QueryRow(ctx, `SELECT revision,request_hash,actor FROM qa_ops_master_field_edits WHERE tenant_key=$1 AND record_id=$2 AND nonce=$3`, s.tenant, id, q.Nonce).Scan(&savedRevision, &savedHash, &savedActor)
if err == nil {
if savedHash != requestHash || savedActor != actor {
return MasterFieldReceipt{}, qaopsquality.ErrConflict
}
return MasterFieldReceipt{SavedRevision: savedRevision, Replayed: true}, nil
}
if !errors.Is(err, pgx.ErrNoRows) {
return MasterFieldReceipt{}, dobotaiops.ErrUnavailable
}
var hash string
var reviewRevision, epoch int64
err = tx.QueryRow(ctx, `SELECT input_hash,review_revision,input_epoch FROM qa_ops_quality_records WHERE tenant_key=$1 AND record_id=$2 FOR UPDATE`, s.tenant+"::master", id).Scan(&hash, &reviewRevision, &epoch)
if errors.Is(err, pgx.ErrNoRows) {
return MasterFieldReceipt{}, dobotaiops.ErrRecordNotFound
}
if err != nil {
return MasterFieldReceipt{}, dobotaiops.ErrUnavailable
}
if hash != q.InputHash || epoch != q.InputEpoch || reviewRevision != q.BaseReviewRevision {
return MasterFieldReceipt{}, qaopsquality.ErrConflict
}
var currentRevision, previousReview int64
var previousHash string
var raw []byte
overrides := map[string]string{}
err = tx.QueryRow(ctx, `SELECT revision,input_hash,review_revision,fields FROM qa_ops_master_field_overrides WHERE tenant_key=$1 AND record_id=$2`, s.tenant, id).Scan(&currentRevision, &previousHash, &previousReview, &raw)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return MasterFieldReceipt{}, dobotaiops.ErrUnavailable
}
if currentRevision != q.BaseRevision {
return MasterFieldReceipt{}, qaopsquality.ErrConflict
}
if previousHash == hash && previousReview == reviewRevision && json.Unmarshal(raw, &overrides) != nil {
return MasterFieldReceipt{}, dobotaiops.ErrUnavailable
}
var masterHash string
var fieldsRaw, coverageRaw, editsRaw, feedbackRaw []byte
err = tx.QueryRow(ctx, `SELECT quality_hash,effective_fields,coverage_result,inline_fields,current_feedback FROM qa_ops_master_read_model WHERE tenant_key=$1 AND id=$2`, s.tenant, id).Scan(&masterHash, &fieldsRaw, &coverageRaw, &editsRaw, &feedbackRaw)
if err != nil {
return MasterFieldReceipt{}, dobotaiops.ErrUnavailable
}
if masterHash != q.InputHash {
return MasterFieldReceipt{}, qaopsquality.ErrConflict
}
var fields, edits map[string]string
var coverage dobotaiops.CoverageCheck
var feedback dobotaiops.RecordFeedback
if json.Unmarshal(fieldsRaw, &fields) != nil || json.Unmarshal(editsRaw, &edits) != nil || json.Unmarshal(coverageRaw, &coverage) != nil || json.Unmarshal(feedbackRaw, &feedback) != nil {
return MasterFieldReceipt{}, dobotaiops.ErrUnavailable
}
if value, changed := q.Fields["is_correct"]; changed && value != "否" && qaopsquality.FeedbackForcesIncorrect(feedback) {
return MasterFieldReceipt{}, qaopsquality.ErrDownvoted
}
views, err := s.MasterQualityStore().ReadViewsInTx(ctx, tx, []dobotaiops.QualityKey{{ID: id, InputHash: masterHash}})
if err != nil {
return MasterFieldReceipt{}, err
}
current := qaopsquality.ProjectMasterWithEdits(views[id], fields, coverage, edits, feedback).Effective
beforeAll := map[string]string{"coverage": map[string]string{"covered": "是", "uncovered": "否", "partial": "部分覆盖", "pending": "待确认", "excluded": "否但不计入"}[current.Coverage], "is_correct": map[string]string{"correct": "是", "incorrect": "否", "pending": "待确认"}[current.Correctness], "product_category": current.ProductCategory, "problem_type": current.ProblemType, "root_cause": current.RootCause}
correctness := beforeAll["is_correct"]
if value, ok := q.Fields["is_correct"]; ok {
correctness = value
}
if correctness == "是" && q.Fields["root_cause"] != "" {
return MasterFieldReceipt{}, dobotaiops.ErrInvalidQuery
}
before := map[string]string{}
for key, value := range q.Fields {
before[key] = beforeAll[key]
overrides[key] = value
}
encoded, _ := json.Marshal(overrides)
changed, _ := json.Marshal(q.Fields)
previous, _ := json.Marshal(before)
revision := currentRevision + 1
if _, err = tx.Exec(ctx, `INSERT INTO qa_ops_master_field_overrides(tenant_key,record_id,revision,input_hash,review_revision,fields) VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(tenant_key,record_id) DO UPDATE SET revision=EXCLUDED.revision,input_hash=EXCLUDED.input_hash,review_revision=EXCLUDED.review_revision,fields=EXCLUDED.fields,updated_at=now()`, s.tenant, id, revision, hash, reviewRevision, encoded); err != nil {
return MasterFieldReceipt{}, dobotaiops.ErrUnavailable
}
if _, err = tx.Exec(ctx, `INSERT INTO qa_ops_master_field_edits(tenant_key,record_id,revision,input_hash,review_revision,changed_fields,before_fields,fields,actor,nonce,request_hash) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)`, s.tenant, id, revision, hash, reviewRevision, changed, previous, encoded, actor, q.Nonce, requestHash); err != nil {
return MasterFieldReceipt{}, dobotaiops.ErrUnavailable
}
tag, err := tx.Exec(ctx, `UPDATE qa_ops_master_records SET row_revision=row_revision+1 WHERE tenant_key=$1 AND id=$2 AND quality_hash=$3`, s.tenant, id, hash)
if err != nil || tag.RowsAffected() != 1 {
return MasterFieldReceipt{}, qaopsquality.ErrConflict
}
if err = tx.Commit(ctx); err != nil {
return MasterFieldReceipt{}, dobotaiops.ErrUnavailable
}
return MasterFieldReceipt{SavedRevision: revision}, nil
}
@@ -0,0 +1,69 @@
package qaopsmirror
import (
"context"
"encoding/json"
"knowledge-governance/internal/dobotaiops"
pg "knowledge-governance/internal/platform/postgres"
"testing"
"time"
)
func TestMasterInlineFieldPatchPersistsOnlyChosenField(t *testing.T) {
p := mirrorFixture(t)
ctx := context.Background()
s := NewStore(p, "fixture-inline-fields")
queue := pg.NewStore(p)
source := &fixtureSource{rows: []dobotaiops.MirrorRecord{fixtureEntry("inline-field", "first")}}
job := claimMirrorJob(t, s, queue, "inline-initial")
if e := s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
t.Fatal(e)
}
if e := queue.Complete(ctx, job.ID, job.LeaseOwner, time.Now()); e != nil {
t.Fatal(e)
}
rec, e := s.GetMasterRecord(ctx, s.tenant, "inline-field")
if e != nil {
t.Fatal(e)
}
keys := []dobotaiops.QualityKey{{ID: rec.ID, InputHash: rec.QualityInputHash}}
before, e := s.ReadMasterQualityViews(ctx, keys)
if e != nil {
t.Fatal(e)
}
var original string
if e = p.QueryRow(ctx, `SELECT md5(payload::text||local_fields::text) FROM qa_ops_master_records WHERE tenant_key=$1 AND id=$2`, s.tenant, rec.ID).Scan(&original); e != nil {
t.Fatal(e)
}
q := MasterFieldPatch{InputHash: rec.QualityInputHash, InputEpoch: before[rec.ID].InputEpoch, BaseReviewRevision: before[rec.ID].Revision, Nonce: "fixture_inline_field_001", Fields: map[string]string{"product_category": "MG400"}}
receipt, e := s.PatchMasterFields(ctx, rec.ID, q, "fixture-admin")
if e != nil {
t.Fatalf("single-field persistent edit rejected: %v", e)
}
if receipt.SavedRevision != 1 || receipt.Replayed {
t.Fatalf("invalid receipt: %+v", receipt)
}
after, e := NewStore(p, s.tenant).ReadMasterQualityViews(ctx, keys)
if e != nil {
t.Fatal(e)
}
fresh, e := s.GetMasterRecord(ctx, s.tenant, rec.ID)
if e != nil || fresh.FieldEditRevision != 1 || fresh.MasterFields["product_category"] != "MG400" {
t.Fatalf("detail/list read model did not expose saved field version and value: %+v error=%v", fresh, e)
}
b, a := before[rec.ID], after[rec.ID]
b.Effective.ProductCategory = "MG400"
rawB, _ := json.Marshal(b)
rawA, _ := json.Marshal(a)
if string(rawB) != string(rawA) {
t.Fatalf("unselected conclusions/review provenance changed: before=%s after=%s", rawB, rawA)
}
var current string
var audits int
if e = p.QueryRow(ctx, `SELECT md5(payload::text||local_fields::text) FROM qa_ops_master_records WHERE tenant_key=$1 AND id=$2`, s.tenant, rec.ID).Scan(&current); e != nil || original != current {
t.Fatal("source/master payload or stored labels were rewritten", e)
}
if e = p.QueryRow(ctx, `SELECT count(*) FROM qa_ops_master_field_edits WHERE tenant_key=$1 AND record_id=$2`, s.tenant, rec.ID).Scan(&audits); e != nil || audits != 1 {
t.Fatal("field edit audit missing", e)
}
}
+6 -5
View File
@@ -27,17 +27,18 @@ func (s *Store) ReadMasterQualityViews(ctx context.Context, keys []dobotaiops.Qu
ids = append(ids, key.ID)
hashes[key.ID] = key.InputHash
}
rows, err := tx.Query(ctx, `SELECT id,quality_hash,effective_fields,coverage_result FROM qa_ops_master_read_model WHERE tenant_key=$1 AND id=ANY($2::text[])`, s.tenant, ids)
rows, err := tx.Query(ctx, `SELECT id,quality_hash,effective_fields,coverage_result,inline_fields,current_feedback FROM qa_ops_master_read_model WHERE tenant_key=$1 AND id=ANY($2::text[])`, s.tenant, ids)
if err != nil {
return nil, dobotaiops.ErrUnavailable
}
count := 0
for rows.Next() {
var id, hash string
var rawFields, rawCoverage []byte
var fields map[string]string
var rawFields, rawCoverage, rawEdits, rawFeedback []byte
var feedback dobotaiops.RecordFeedback
var fields, edits map[string]string
var coverage dobotaiops.CoverageCheck
if rows.Scan(&id, &hash, &rawFields, &rawCoverage) != nil || json.Unmarshal(rawFields, &fields) != nil || json.Unmarshal(rawCoverage, &coverage) != nil {
if rows.Scan(&id, &hash, &rawFields, &rawCoverage, &rawEdits, &rawFeedback) != nil || json.Unmarshal(rawFields, &fields) != nil || json.Unmarshal(rawCoverage, &coverage) != nil || json.Unmarshal(rawEdits, &edits) != nil || json.Unmarshal(rawFeedback, &feedback) != nil {
rows.Close()
return nil, dobotaiops.ErrUnavailable
}
@@ -50,7 +51,7 @@ func (s *Store) ReadMasterQualityViews(ctx context.Context, keys []dobotaiops.Qu
rows.Close()
return nil, qaopsquality.ErrUnavailable
}
views[id] = qaopsquality.ProjectMaster(view, fields, coverage)
views[id] = qaopsquality.ProjectMasterWithEdits(view, fields, coverage, edits, feedback)
count++
}
err = rows.Err()
+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} }
+179
View File
@@ -0,0 +1,179 @@
package qaopsmirror
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"github.com/jackc/pgx/v5"
"knowledge-governance/internal/dobotaiops"
"knowledge-governance/internal/qaopsquality"
"strings"
"time"
"unicode/utf8"
)
func (s *Store) PrefillWeeklyDraft(ctx context.Context, week string, q WeeklyDraftPrefillRequest, actor string, now time.Time) (WeeklyDraftReceipt, error) {
if !s.valid() {
return WeeklyDraftReceipt{}, dobotaiops.ErrUnavailable
}
start, end, err := weeklyDraftBounds(week, now)
if err != nil {
return WeeklyDraftReceipt{}, err
}
if q.BaseRevision < 0 || !inlineNonce.MatchString(q.Nonce) || !validInlineID(actor) {
return WeeklyDraftReceipt{}, dobotaiops.ErrInvalidQuery
}
request := WeeklyDraftRequest{BaseRevision: q.BaseRevision, Nonce: q.Nonce}
saved := WeeklyDraft{Week: week}
var hash, owner string
err = s.pool.QueryRow(ctx, `SELECT revision,markdown,seed,created_at,actor,request_hash FROM qa_ops_weekly_draft_revisions WHERE tenant_key=$1 AND week=$2 AND nonce=$3`, s.tenant, week, q.Nonce).Scan(&saved.Revision, &saved.Markdown, &saved.Seed, &saved.UpdatedAt, &owner, &hash)
if err == nil {
if hash != weeklyRequestHash(request, "prefill") || owner != actor {
return WeeklyDraftReceipt{}, qaopsquality.ErrConflict
}
return WeeklyDraftReceipt{Draft: saved, Replayed: true}, nil
}
if !errors.Is(err, pgx.ErrNoRows) {
return WeeklyDraftReceipt{}, dobotaiops.ErrUnavailable
}
data, err := s.ReadMasterDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}})
if err != nil {
return WeeklyDraftReceipt{}, err
}
markdown, seed, err := renderWeeklyTemplate(week, data, now)
if err != nil {
return WeeklyDraftReceipt{}, err
}
request.Markdown = markdown
return s.saveWeeklyDraft(ctx, week, request, actor, now, "prefill", seed)
}
const maxWeeklyDraftBytes = 256 << 10
type WeeklyDraft struct {
Week string `json:"week"`
Revision int64 `json:"revision"`
Markdown string `json:"markdown"`
Seed json.RawMessage `json:"seed"`
UpdatedAt *time.Time `json:"updated_at"`
}
type WeeklyDraftRequest struct {
BaseRevision int64 `json:"base_revision"`
Nonce string `json:"nonce"`
Markdown string `json:"markdown"`
}
type WeeklyDraftPrefillRequest struct {
BaseRevision int64 `json:"base_revision"`
Nonce string `json:"nonce"`
}
type WeeklyDraftReceipt struct {
Draft WeeklyDraft `json:"draft"`
Replayed bool `json:"replayed"`
}
func weeklyDraftBounds(week string, now time.Time) (time.Time, time.Time, error) {
start, end, err := (DepartmentStatisticsQuery{Period: "week", Week: week}).Bounds(now)
if err != nil {
return time.Time{}, time.Time{}, err
}
if start == nil {
return time.Time{}, time.Time{}, dobotaiops.ErrInvalidQuery
}
return *start, end, nil
}
func (s *Store) ReadWeeklyDraft(ctx context.Context, week string, now time.Time) (WeeklyDraft, error) {
out := WeeklyDraft{Week: week, Seed: json.RawMessage(`{}`)}
if !s.valid() {
return out, dobotaiops.ErrUnavailable
}
if _, _, e := weeklyDraftBounds(week, now); e != nil {
return out, e
}
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
e := s.pool.QueryRow(ctx, `SELECT revision,markdown,seed,updated_at FROM qa_ops_weekly_drafts WHERE tenant_key=$1 AND week=$2`, s.tenant, week).Scan(&out.Revision, &out.Markdown, &out.Seed, &out.UpdatedAt)
if errors.Is(e, pgx.ErrNoRows) {
return out, nil
}
if e != nil {
return WeeklyDraft{}, dobotaiops.ErrUnavailable
}
return out, nil
}
func weeklyRequestHash(q WeeklyDraftRequest, operation string) string {
if operation == "prefill" {
q.Markdown = ""
}
raw, _ := json.Marshal(struct {
Request WeeklyDraftRequest
Operation string
}{q, operation})
sum := sha256.Sum256(raw)
return hex.EncodeToString(sum[:])
}
func (s *Store) SaveWeeklyDraft(ctx context.Context, week string, q WeeklyDraftRequest, actor string, now time.Time) (WeeklyDraftReceipt, error) {
return s.saveWeeklyDraft(ctx, week, q, actor, now, "edit", nil)
}
func (s *Store) saveWeeklyDraft(ctx context.Context, week string, q WeeklyDraftRequest, actor string, now time.Time, operation string, seed json.RawMessage) (WeeklyDraftReceipt, error) {
if !s.valid() {
return WeeklyDraftReceipt{}, dobotaiops.ErrUnavailable
}
if _, _, e := weeklyDraftBounds(week, now); e != nil {
return WeeklyDraftReceipt{}, e
}
if q.BaseRevision < 0 || !inlineNonce.MatchString(q.Nonce) || !validInlineID(actor) || !utf8.ValidString(q.Markdown) || len(q.Markdown) > maxWeeklyDraftBytes || strings.ContainsRune(q.Markdown, 0) || (operation != "edit" && operation != "prefill") {
return WeeklyDraftReceipt{}, dobotaiops.ErrInvalidQuery
}
ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
defer cancel()
tx, e := s.pool.Begin(ctx)
if e != nil {
return WeeklyDraftReceipt{}, dobotaiops.ErrUnavailable
}
defer tx.Rollback(context.Background())
if _, e = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1||chr(31)||$2,259))`, s.tenant, week); e != nil {
return WeeklyDraftReceipt{}, dobotaiops.ErrUnavailable
}
requestHash := weeklyRequestHash(q, operation)
saved := WeeklyDraft{Week: week}
var savedActor, savedHash string
e = tx.QueryRow(ctx, `SELECT revision,markdown,seed,created_at,actor,request_hash FROM qa_ops_weekly_draft_revisions WHERE tenant_key=$1 AND week=$2 AND nonce=$3`, s.tenant, week, q.Nonce).Scan(&saved.Revision, &saved.Markdown, &saved.Seed, &saved.UpdatedAt, &savedActor, &savedHash)
if e == nil {
if savedActor != actor || savedHash != requestHash {
return WeeklyDraftReceipt{}, qaopsquality.ErrConflict
}
return WeeklyDraftReceipt{Draft: saved, Replayed: true}, nil
}
if !errors.Is(e, pgx.ErrNoRows) {
return WeeklyDraftReceipt{}, dobotaiops.ErrUnavailable
}
current := WeeklyDraft{Week: week, Seed: json.RawMessage(`{}`)}
e = tx.QueryRow(ctx, `SELECT revision,markdown,seed,updated_at FROM qa_ops_weekly_drafts WHERE tenant_key=$1 AND week=$2 FOR UPDATE`, s.tenant, week).Scan(&current.Revision, &current.Markdown, &current.Seed, &current.UpdatedAt)
if e != nil && !errors.Is(e, pgx.ErrNoRows) {
return WeeklyDraftReceipt{}, dobotaiops.ErrUnavailable
}
if current.Revision != q.BaseRevision {
return WeeklyDraftReceipt{}, qaopsquality.ErrConflict
}
if seed == nil {
seed = current.Seed
}
if len(seed) == 0 || !json.Valid(seed) {
return WeeklyDraftReceipt{}, dobotaiops.ErrInvalidQuery
}
var created time.Time
next := current.Revision + 1
e = tx.QueryRow(ctx, `INSERT INTO qa_ops_weekly_drafts(tenant_key,week,revision,markdown,seed,updated_by) VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(tenant_key,week) DO UPDATE SET revision=EXCLUDED.revision,markdown=EXCLUDED.markdown,seed=EXCLUDED.seed,updated_by=EXCLUDED.updated_by,updated_at=now() RETURNING updated_at`, s.tenant, week, next, q.Markdown, seed, actor).Scan(&created)
if e != nil {
return WeeklyDraftReceipt{}, dobotaiops.ErrUnavailable
}
if _, e = tx.Exec(ctx, `INSERT INTO qa_ops_weekly_draft_revisions(tenant_key,week,revision,operation,markdown,seed,actor,nonce,request_hash,created_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, s.tenant, week, next, operation, q.Markdown, seed, actor, q.Nonce, requestHash, created); e != nil {
return WeeklyDraftReceipt{}, dobotaiops.ErrUnavailable
}
if e = tx.Commit(ctx); e != nil {
return WeeklyDraftReceipt{}, dobotaiops.ErrUnavailable
}
return WeeklyDraftReceipt{Draft: WeeklyDraft{Week: week, Revision: next, Markdown: q.Markdown, Seed: seed, UpdatedAt: &created}}, nil
}
@@ -0,0 +1,43 @@
package qaopsmirror
import (
"context"
"testing"
"time"
)
func TestWeeklyDraftDurablyRoundTripsOneDraftPerWeekWithoutReadSideEffects(t *testing.T) {
p := mirrorFixture(t)
s := NewStore(p, "fixture-weekly-editor")
ctx := context.Background()
now := time.Date(2026, 10, 19, 12, 0, 0, 0, time.UTC)
empty, e := s.ReadWeeklyDraft(ctx, "2026-W41", now)
if e != nil || empty.Revision != 0 || empty.Week != "2026-W41" || empty.Markdown != "" {
t.Fatalf("missing week must be a read-only empty draft, not unavailable/fabricated content: %+v %v", empty, e)
}
var rows int
if e = p.QueryRow(ctx, `SELECT count(*) FROM qa_ops_weekly_drafts WHERE tenant_key=$1`, s.tenant).Scan(&rows); e != nil || rows != 0 {
t.Fatal("viewing a week created a draft", e)
}
q := WeeklyDraftRequest{BaseRevision: 0, Nonce: "fixture_weekly_editor_0001", Markdown: "# Edited report\n\n中文正文,English text\n<script>not executable</script>\n"}
receipt, e := s.SaveWeeklyDraft(ctx, "2026-W41", q, "fixture-admin", now)
if e != nil || receipt.Draft.Revision != 1 || receipt.Replayed {
t.Fatalf("autosave rejected: %+v %v", receipt, e)
}
fresh, e := NewStore(p, s.tenant).ReadWeeklyDraft(ctx, "2026-W41", now)
if e != nil || fresh.Markdown != q.Markdown || fresh.Revision != 1 || fresh.UpdatedAt == nil {
t.Fatalf("reopened editor lost exact content: %+v %v", fresh, e)
}
other, e := s.ReadWeeklyDraft(ctx, "2026-W40", now)
if e != nil || other.Revision != 0 || other.Markdown != "" {
t.Fatal("week contents contaminated", e)
}
tenant, e := NewStore(p, "fixture-other-tenant").ReadWeeklyDraft(ctx, "2026-W41", now)
if e != nil || tenant.Revision != 0 {
t.Fatal("tenant isolation failed", e)
}
replay, e := s.SaveWeeklyDraft(ctx, "2026-W41", q, "fixture-admin", now)
if e != nil || !replay.Replayed || replay.Draft.Revision != 1 {
t.Fatal("same autosave retry must recover its existing receipt", e)
}
}
@@ -0,0 +1,69 @@
package qaopsmirror
import (
"context"
"encoding/json"
"fmt"
"knowledge-governance/internal/dobotaiops"
pg "knowledge-governance/internal/platform/postgres"
"strings"
"testing"
"time"
)
func TestWeeklyPrefillUsesRealMasterDashboardAndDoesNotOverwriteExistingDraft(t *testing.T) {
p := mirrorFixture(t)
ctx := context.Background()
s := NewStore(p, "fixture-weekly-prefill")
queue := pg.NewStore(p)
source := &fixtureSource{rows: []dobotaiops.MirrorRecord{fixtureEntry("prefill-event", "existing answer")}}
job := claimMirrorJob(t, s, queue, "prefill-source")
if e := s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
t.Fatal(e)
}
if e := queue.Complete(ctx, job.ID, job.LeaseOwner, time.Now()); e != nil {
t.Fatal(e)
}
record, e := s.GetMasterRecord(ctx, s.tenant, "prefill-event")
if e != nil {
t.Fatal(e)
}
year, weekNumber := record.AskedAt.In(dashboardLocation).ISOWeek()
week := fmt.Sprintf("%04d-W%02d", year, weekNumber)
now := time.Now()
start, end, e := weeklyDraftBounds(week, now)
if e != nil {
t.Fatal(e)
}
data, e := s.ReadMasterDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}})
if e != nil {
t.Fatal(e)
}
q := WeeklyDraftPrefillRequest{Nonce: "fixture_prefill_week_0001"}
receipt, e := s.PrefillWeeklyDraft(ctx, week, q, "fixture-admin", now)
if e != nil {
t.Fatalf("real-source prefill unavailable: %v", e)
}
if receipt.Draft.Revision != 1 || !strings.Contains(receipt.Draft.Markdown, fmt.Sprintf("问题总数:%d", data.TotalIssues)) || !strings.Contains(receipt.Draft.Markdown, fmt.Sprintf("New This Week: %d", data.NewThisWeek)) {
t.Fatal("prefill was not generated from matching master cutoff")
}
var seed map[string]any
if json.Unmarshal(receipt.Draft.Seed, &seed) != nil || seed["source"] != "governance-master" || seed["week"] != week {
t.Fatal("prefill source provenance missing")
}
edit := WeeklyDraftRequest{BaseRevision: 1, Nonce: "fixture_prefill_user_0002", Markdown: receipt.Draft.Markdown + "\n用户亲写内容,不许替换\n"}
if _, e = s.SaveWeeklyDraft(ctx, week, edit, "fixture-admin", now); e != nil {
t.Fatal(e)
}
if _, e = s.PrefillWeeklyDraft(ctx, week, WeeklyDraftPrefillRequest{BaseRevision: 1, Nonce: "fixture_prefill_stale_0003"}, "fixture-admin", now); e == nil {
t.Fatal("stale regeneration silently replaced edited content")
}
fresh, e := s.ReadWeeklyDraft(ctx, week, now)
if e != nil || fresh.Revision != 2 || fresh.Markdown != edit.Markdown {
t.Fatal("prefill or stale request overwrote user input", e)
}
replay, e := s.PrefillWeeklyDraft(ctx, week, q, "fixture-admin", now)
if e != nil || !replay.Replayed || replay.Draft.Revision != 1 {
t.Fatal("prefill retry must return its exact historical receipt", e)
}
}
+175
View File
@@ -0,0 +1,175 @@
package qaopsmirror
import (
"encoding/json"
"fmt"
"knowledge-governance/internal/dobotaiops"
"math"
"sort"
"strings"
"time"
)
func weeklyMarkdownCell(value string) string {
return strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;", "\\", "\\\\", "*", "\\*", "_", "\\_", "[", "\\[", "]", "\\]", "|", "\\|", "`", "\\`", "\r", " ", "\n", " ").Replace(value)
}
func weeklyPercent(value *float64) string {
if value == nil {
return "—"
}
return fmt.Sprintf("%.2f%%", *value)
}
func weeklyNumber(value *float64) string {
if value == nil {
return "—"
}
return fmt.Sprintf("%.2f", *value)
}
func validWeeklyValue(v *float64, percent bool) bool {
return v == nil || (!math.IsNaN(*v) && !math.IsInf(*v, 0) && *v >= 0 && (!percent || *v <= 100))
}
func weeklyRegionRanking(regions []DashboardRegion, coverage, english bool) string {
rows := append([]DashboardRegion(nil), regions...)
metric := func(r DashboardRegion) *float64 {
if coverage {
return r.UsageCoverage.Percent
}
return r.Frequency
}
sort.SliceStable(rows, func(i, j int) bool {
a, b := metric(rows[i]), metric(rows[j])
if a == nil {
return false
}
if b == nil {
return true
}
if *a == *b {
return rows[i].ID < rows[j].ID
}
return *a > *b
})
values := make([]string, 0, len(rows))
for i, r := range rows {
name := r.Name
if english {
if translated := map[string]string{"国内工业": "China Industrial", "America": "Americas", "APAC": "APAC", "EMEA": "EMEA"}[name]; translated != "" {
name = translated
}
}
value := weeklyNumber(metric(r))
if coverage {
value = weeklyPercent(metric(r))
}
values = append(values, fmt.Sprintf("%d. %s: %s", i+1, weeklyMarkdownCell(name), value))
}
if len(values) == 0 {
return "—"
}
return strings.Join(values, "\n")
}
func renderWeeklyTemplate(week string, data Dashboard, now time.Time) (string, json.RawMessage, error) {
start, end, err := weeklyDraftBounds(week, now)
if err != nil || !data.Start.Equal(start) || !data.End.Equal(end) || data.TotalIssues < 0 || data.NewThisWeek < 0 || data.NewThisWeek > data.TotalIssues || data.MonthStart.IsZero() {
return "", nil, dobotaiops.ErrInvalidQuery
}
coverage, accuracy := data.Quality.Rates.Coverage.Percent, data.Quality.Rates.Correctness.Percent
qualitySource := "live-week"
qualitySourceWeekKey := ""
for _, f := range data.FrozenWeeks {
if f.WeekStart.Equal(start) && f.FrozenAt != nil {
coverage, accuracy = f.Coverage.Percent, f.Correctness.Percent
qualitySource = "frozen-week"
}
}
for _, p := range data.ReportedWeeks {
if p.WeekStart.Equal(start) && p.WeekEnd.Equal(start.AddDate(0, 0, 7)) && !p.WeekEnd.After(end) {
c, a := p.CoveragePercent, p.CorrectnessPercent
coverage, accuracy = &c, &a
qualitySource = "reported-history"
qualitySourceWeekKey = p.Week
}
}
if !validWeeklyValue(coverage, true) || !validWeeklyValue(accuracy, true) {
return "", nil, dobotaiops.ErrInvalidQuery
}
for _, r := range data.Regions {
if !validWeeklyValue(r.Frequency, false) || !validWeeklyValue(r.UsageCoverage.Percent, true) {
return "", nil, dobotaiops.ErrInvalidQuery
}
}
month := data.MonthStart.In(dashboardLocation)
replacements := []string{
"{{YEAR}}", week[:4], "{{WEEK}}", week[6:],
"{{TOTAL_QUESTIONS}}", fmt.Sprint(data.TotalIssues), "{{NEW_THIS_WEEK}}", fmt.Sprint(data.NewThisWeek),
"{{COVERAGE_RATE}}", weeklyPercent(coverage), "{{ACCURACY_RATE}}", weeklyPercent(accuracy),
"{{MONTH_EN}}", month.Format("January 2006"), "{{MONTH_ZH}}", fmt.Sprintf("%d年%d月", month.Year(), month.Month()),
"{{AVERAGE_USAGE_RANKING_EN}}", weeklyRegionRanking(data.Regions, false, true), "{{AVERAGE_USAGE_RANKING_ZH}}", weeklyRegionRanking(data.Regions, false, false),
"{{USAGE_COVERAGE_RANKING_EN}}", weeklyRegionRanking(data.Regions, true, true), "{{USAGE_COVERAGE_RANKING_ZH}}", weeklyRegionRanking(data.Regions, true, false),
"{{WEEKLY_HIGHLIGHTS_EN}}", "[To be completed]", "{{NEXT_WEEK_PRIORITIES_EN}}", "[To be completed]",
"{{WEEKLY_HIGHLIGHTS_ZH}}", "[待填写]", "{{NEXT_WEEK_PRIORITIES_ZH}}", "[待填写]"}
markdown := strings.NewReplacer(replacements...).Replace(weeklySkillTemplate)
seed, _ := json.Marshal(map[string]any{"template_version": "dobot-weekly-six-sections-v1", "week": week, "start": start, "end": end, "generated_at": now, "source": "governance-master", "local_revision": data.LocalRevision, "source_observed_at": data.AsOf, "organization": data.Organization, "quality_source": qualitySource, "quality_source_week_key": qualitySourceWeekKey, "total_issues": data.TotalIssues, "new_this_week": data.NewThisWeek, "coverage_percent": coverage, "correctness_percent": accuracy, "month": month.Format("2006-01"), "regions": data.Regions})
return markdown, seed, nil
}
const weeklySkillTemplate = `# Knowledge Base Weekly Report - {{YEAR}} WK{{WEEK}}
## 1. Weekly Summary
Total Questions: {{TOTAL_QUESTIONS}}
New This Week: {{NEW_THIS_WEEK}}
## 2. Key Metrics
Coverage Rate: {{COVERAGE_RATE}}
Accuracy Rate: {{ACCURACY_RATE}}
## 3. {{MONTH_EN}} Regional Average Usage Ranking
{{AVERAGE_USAGE_RANKING_EN}}
## 4. {{MONTH_EN}} Regional Usage Coverage Ranking
{{USAGE_COVERAGE_RANKING_EN}}
## 5. Weekly Highlights
{{WEEKLY_HIGHLIGHTS_EN}}
## 6. Next Week Priorities
{{NEXT_WEEK_PRIORITIES_EN}}
# 知识库周报 - {{YEAR}}年第{{WEEK}}周
## 一、本周概况
问题总数:{{TOTAL_QUESTIONS}}
本周新增:{{NEW_THIS_WEEK}}
## 二、核心指标
覆盖率:{{COVERAGE_RATE}}
正确率:{{ACCURACY_RATE}}
## 三、{{MONTH_ZH}}区域人均使用次数排名
{{AVERAGE_USAGE_RANKING_ZH}}
## 四、{{MONTH_ZH}}区域使用覆盖率排名
{{USAGE_COVERAGE_RANKING_ZH}}
## 五、本周重点
{{WEEKLY_HIGHLIGHTS_ZH}}
## 六、下周重点
{{NEXT_WEEK_PRIORITIES_ZH}}
`
@@ -0,0 +1,61 @@
package qaopsmirror
import (
"encoding/json"
"knowledge-governance/internal/qaopsquality"
"strings"
"testing"
"time"
)
func TestWeeklyTemplateHistoricalRatesKeepSourceWeekKeyAndUseMatchingBoundaries(t *testing.T) {
now := time.Date(2026, 10, 19, 12, 0, 0, 0, time.UTC)
start, end, e := weeklyDraftBounds("2026-W40", now)
if e != nil {
t.Fatal(e)
}
data := Dashboard{Start: start, End: end, MonthStart: dashboardDay(end.Add(-time.Second)), ReportedWeeks: []DashboardReported{{Week: "2026WK40", WeekStart: start, WeekEnd: end, CoveragePercent: 57.23, CorrectnessPercent: 92.34, Source: "user_provided_history"}}}
md, seed, e := renderWeeklyTemplate("2026-W40", data, now)
if e != nil {
t.Fatal(e)
}
var meta map[string]any
if json.Unmarshal(seed, &meta) != nil {
t.Fatal("invalid seed")
}
if !strings.Contains(md, "Coverage Rate: 57.23%") || !strings.Contains(md, "Accuracy Rate: 92.34%") || meta["quality_source"] != "reported-history" || meta["quality_source_week_key"] != "2026WK40" {
t.Fatalf("historical source key must remain verbatim and match by real week boundaries: %s", md)
}
if data.ReportedWeeks[0].Week != "2026WK40" {
t.Fatal("rewrote source week identifier")
}
}
func TestWeeklyTemplateUsesExactBilingualSixSectionsAndRealMetricValues(t *testing.T) {
now := time.Date(2026, 10, 19, 12, 0, 0, 0, time.UTC)
start, end, e := weeklyDraftBounds("2026-W41", now)
if e != nil {
t.Fatal(e)
}
p := func(v float64) *float64 { return &v }
data := Dashboard{Start: start, End: end, MonthStart: time.Date(2026, 10, 1, 0, 0, 0, 0, dashboardLocation), TotalIssues: 1234, NewThisWeek: 12, Quality: qaopsquality.Summary{Rates: qaopsquality.Rates{Coverage: qaopsquality.Rate{Percent: p(0)}, Correctness: qaopsquality.Rate{}}}, Regions: []DashboardRegion{{ID: "a", Name: "APAC", Frequency: p(0), UsageCoverage: qaopsquality.Rate{Percent: p(10)}}, {ID: "b", Name: "America", Frequency: p(2), UsageCoverage: qaopsquality.Rate{Percent: p(5)}}, {ID: "c", Name: "unassigned\n## fake", Frequency: nil}}}
md, seed, e := renderWeeklyTemplate("2026-W41", data, now)
if e != nil {
t.Fatal(e)
}
if strings.Count(md, "\n## ") != 12 || !strings.HasPrefix(md, "# Knowledge Base Weekly Report - 2026 WK41") || strings.Index(md, "## 6. Next Week Priorities") > strings.Index(md, "# 知识库周报") || !strings.Contains(md, "问题总数:1234") || !strings.Contains(md, "New This Week: 12") || !strings.Contains(md, "Coverage Rate: 0.00%") || !strings.Contains(md, "Accuracy Rate: —") || strings.Contains(md, "{{") || strings.Contains(md, "\n## fake") {
t.Fatalf("skill template, trusted values or escaping missing: %s", md)
}
if !strings.Contains(md, "[待填写]") || !strings.Contains(md, "[To be completed]") {
t.Fatal("invented authored highlights instead of leaving placeholders")
}
average := md[strings.Index(md, "Regional Average"):strings.Index(md, "## 4.")]
coverage := md[strings.Index(md, "Regional Usage Coverage"):strings.Index(md, "## 5.")]
if strings.Index(average, "Americas") > strings.Index(average, "APAC") || strings.Index(coverage, "APAC") > strings.Index(coverage, "Americas") {
t.Fatal("regional rankings not sorted independently")
}
var meta map[string]any
if json.Unmarshal(seed, &meta) != nil || meta["quality_source"] != "live-week" {
t.Fatal("prefill provenance missing")
}
}
@@ -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)
}
}
+41
View File
@@ -2,6 +2,47 @@ package qaopsquality
import "knowledge-governance/internal/dobotaiops"
func FeedbackForcesIncorrect(feedback dobotaiops.RecordFeedback) bool {
return feedback.Down > 0 || feedback.AskerValue == "down"
}
func ProjectMasterWithEdits(v View, stored map[string]string, derived dobotaiops.CoverageCheck, edits map[string]string, feedback ...dobotaiops.RecordFeedback) View {
v = ProjectMaster(v, stored, derived)
v.FeedbackRule = ""
v.MasterFeedback = nil
if len(feedback) > 0 {
current := feedback[0]
v.MasterFeedback = &current
}
if value, ok := edits["coverage"]; ok {
v.Effective.Coverage = map[string]string{"是": "covered", "否": "uncovered", "否但不计入": "excluded"}[value]
v.Effective.ExclusionReason = ""
if value == "否但不计入" {
v.Effective.ExclusionReason = "详情字段选择:否但不计入"
}
}
if value, ok := edits["is_correct"]; ok {
v.Effective.Correctness = map[string]string{"是": "correct", "否": "incorrect", "待确认": "pending"}[value]
}
if value, ok := edits["product_category"]; ok {
v.Effective.ProductCategory = value
}
if value, ok := edits["problem_type"]; ok {
v.Effective.ProblemType = value
}
if value, ok := edits["root_cause"]; ok {
v.Effective.RootCause = value
}
if len(feedback) > 0 && FeedbackForcesIncorrect(feedback[0]) {
v.Effective.Correctness = "incorrect"
v.FeedbackRule = "downvote-is-incorrect-v1"
}
if v.Effective.Correctness == "correct" {
v.Effective.RootCause = ""
}
return v
}
// Stored master labels remain their original provenance, not synthetic reviews.
func ProjectMaster(v View, stored map[string]string, derived dobotaiops.CoverageCheck) View {
v.EffectiveSource = "master-effective-fields-v1"
@@ -0,0 +1,33 @@
package qaopsquality
import (
"knowledge-governance/internal/dobotaiops"
"testing"
)
func TestMasterDownvoteRuleOverridesOnlyCorrectnessWithoutChangingReviewEvidence(t *testing.T) {
for _, test := range []struct {
name string
feedback dobotaiops.RecordFeedback
correctness string
want string
}{
{"asker-down-without-counter", dobotaiops.RecordFeedback{AskerValue: "down"}, "correct", "incorrect"},
{"someone-else-down", dobotaiops.RecordFeedback{AskerValue: "up", Up: 10, Down: 1}, "pending", "incorrect"},
{"no-vote-keeps-pending", dobotaiops.RecordFeedback{}, "pending", "pending"},
{"up-is-not-proof-of-correctness", dobotaiops.RecordFeedback{AskerValue: "up", Up: 1}, "incorrect", "incorrect"},
} {
t.Run(test.name, func(t *testing.T) {
original := Fields{Coverage: "covered", Correctness: test.correctness, ProductCategory: "MG400", ProblemType: "参数"}
review := Review{Revision: 3, Fields: original}
v := View{State: "reviewed", Revision: 3, LatestReview: &review, Effective: original}
got := ProjectMasterWithEdits(v, map[string]string{}, dobotaiops.CoverageCheck{}, map[string]string{}, test.feedback)
if got.Effective.Correctness != test.want || review.Fields != original || got.LatestReview.Fields != original || got.State != "reviewed" || got.Revision != 3 || got.Effective.Coverage != "covered" || got.Effective.ProductCategory != "MG400" {
t.Fatalf("feedback rule changed unrelated quality or evidence: %+v", got)
}
if FeedbackForcesIncorrect(test.feedback) != (got.FeedbackRule == "downvote-is-incorrect-v1") {
t.Fatal("feedback provenance missing or invented")
}
})
}
}
@@ -0,0 +1,31 @@
package qaopsquality
import (
"knowledge-governance/internal/dobotaiops"
"testing"
)
func TestMasterInlineEditsOverrideLegacyReviewOnlyForSelectedFields(t *testing.T) {
v := View{State: "reviewed", Revision: 7, Effective: Fields{Coverage: "covered", Correctness: "incorrect", ProductCategory: "legacy", ProblemType: "故障", RootCause: "知识过期"}, LatestReview: &Review{Revision: 7}}
edits := map[string]string{"coverage": "否但不计入", "is_correct": "是", "root_cause": "检索不到"}
got := ProjectMasterWithEdits(v, map[string]string{}, dobotaiops.CoverageCheck{}, edits)
if got.Effective.Coverage != "excluded" || got.Effective.ExclusionReason == "" || got.Effective.Correctness != "correct" || got.Effective.RootCause != "" || got.Effective.ProductCategory != "legacy" || got.Effective.ProblemType != "故障" || got.LatestReview.Revision != 7 {
t.Fatalf("inline override/reset dependency/legacy preservation failed: %+v", got)
}
reverted := ProjectMasterWithEdits(got, nil, dobotaiops.CoverageCheck{}, map[string]string{"coverage": "否", "is_correct": "待确认", "problem_type": "咨询", "root_cause": "知识缺失"})
if reverted.Effective.Coverage != "uncovered" || reverted.Effective.ExclusionReason != "" || reverted.Effective.Correctness != "pending" || reverted.Effective.ProblemType != "咨询" || reverted.Effective.RootCause != "知识缺失" {
t.Fatalf("canonical labels/reset failed: %+v", reverted)
}
}
func TestMasterInlineEditChangesOnlyChosenFieldWithoutFabricatingReview(t *testing.T) {
v := View{State: "unreviewed"}
stored := map[string]string{"coverage": "是", "product_category": "CRV"}
got := ProjectMasterWithEdits(v, stored, dobotaiops.CheckMasterCoverage("existing answer", true), map[string]string{"product_category": "MG400"})
if got.Effective.ProductCategory != "MG400" || got.Effective.Correctness != "" || got.Effective.ProblemType != "" || got.State != "unreviewed" || got.LatestReview != nil {
t.Fatalf("single-field edit lost or implicitly created other conclusions: %+v", got)
}
if stored["product_category"] != "CRV" {
t.Fatal("mutated source labels")
}
}
+11 -8
View File
@@ -10,6 +10,7 @@ import (
var ErrInvalid = errors.New("invalid quality request")
var ErrConflict = errors.New("quality input or review revision changed")
var ErrDownvoted = errors.New("active downvote forces incorrect correctness")
var ErrUnavailable = errors.New("quality store unavailable")
var ErrNotFound = errors.New("quality input snapshot not found")
var ErrSnapshotMissing = errors.New("only quality metadata was observed for this input")
@@ -49,14 +50,16 @@ type Check struct {
CreatedAt time.Time `json:"created_at"`
}
type View struct {
EffectiveSource string `json:"effective_source,omitempty"`
InputHash string `json:"input_hash"`
InputEpoch int64 `json:"input_epoch"`
Revision int64 `json:"revision"`
State string `json:"state"`
Automatic Check `json:"automatic"`
LatestReview *Review `json:"latest_review"`
Effective Fields `json:"effective"`
FeedbackRule string `json:"feedback_rule,omitempty"`
MasterFeedback *dobotaiops.RecordFeedback `json:"-"`
EffectiveSource string `json:"effective_source,omitempty"`
InputHash string `json:"input_hash"`
InputEpoch int64 `json:"input_epoch"`
Revision int64 `json:"revision"`
State string `json:"state"`
Automatic Check `json:"automatic"`
LatestReview *Review `json:"latest_review"`
Effective Fields `json:"effective"`
}
type History struct {
Reviews []Review `json:"reviews"`
+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('总人数')
})
+434
View File
@@ -0,0 +1,434 @@
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 { currentQAWeekValue } from './qaWeeks'
import { bindOrganizationDepartments } from './qaOrg'
import type { RegionDefinition } from './qaOrg'
import { QARegions } from './QARegions'
import './qaDepartmentStatistics.css'
import { QAPeriodInput } from './QAPeriodInput'
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 = currentQAWeekValue
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' ? (
<QAPeriodInput
kind="month"
label="统计月份"
ariaLabel="部门统计月份"
value={month}
max={currentMonth()}
onChange={setMonth}
/>
) : null}
{period === 'week' ? (
<QAPeriodInput
kind="week"
label="统计周次(北京时间周一至周日)"
ariaLabel="部门统计周次"
value={week}
max={currentWeekValue()}
onChange={setWeek}
/>
) : 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>
)
}
+154
View File
@@ -0,0 +1,154 @@
import { useEffect, useRef, useState } from 'react'
import './qaPeriodInput.css'
import type { QARecord } from './qaOps'
import { qaColumns } from './qaOps'
import { editableFieldKeys, editableFieldValue, fetchFieldOptions, saveInlineField } from './qaInlineFields'
import type { EditableField, FieldOptions } from './qaInlineFields'
import { newOperationID } from './operationKey'
import { qaFieldColors } from './qaFieldColors'
export function QAInlineFields({
record,
onSaved,
onReload,
}: {
record: QARecord
onSaved: (record: QARecord) => void
onReload: () => void
}) {
const [options, setOptions] = useState<FieldOptions | null>(null),
[error, setError] = useState(''),
[notice, setNotice] = useState(''),
[saving, setSaving] = useState(false),
[reloadOptions, setReloadOptions] = useState(0)
const [pending, setPending] = useState<{
record: QARecord
field: EditableField
value: string
nonce: string
} | null>(null)
const writing = useRef<AbortController | null>(null)
useEffect(() => {
const c = new AbortController()
setError('')
void fetchFieldOptions(c.signal)
.then(setOptions)
.catch((e) => {
if (!c.signal.aborted) setError(e instanceof Error ? e.message : '主表选项读取失败')
})
return () => c.abort()
}, [reloadOptions])
useEffect(() => () => writing.current?.abort(), [])
const save = async (p: NonNullable<typeof pending>) => {
if (writing.current) return
const c = new AbortController()
writing.current = c
setSaving(true)
setError('')
setNotice('')
try {
const fresh = await saveInlineField(p.record, p.field, p.value, p.nonce, c.signal)
if (!c.signal.aborted) {
setPending(null)
onSaved(fresh)
setNotice('已保存')
}
} catch (e) {
if (!c.signal.aborted) setError(e instanceof Error ? e.message : '字段保存失败,选择尚未确认')
} finally {
writing.current = null
if (!c.signal.aborted) setSaving(false)
}
}
return (
<div className="qa-inline-fields">
<div className="qa-detail-quality" aria-label="固定质量字段">
{editableFieldKeys.map((field) => {
const value = pending?.field === field ? pending.value : editableFieldValue(record, field)
const rootNotNeeded = field === 'root_cause' && editableFieldValue(record, 'is_correct') === '是'
const downvoteLocked = field === 'is_correct' && record.quality?.feedback_rule === 'downvote-is-incorrect-v1'
return (
<div key={field} data-quality-field={field}>
<label>
<span>{qaColumns.find((c) => c.key === field)!.label}</span>
<select
aria-label={`修改${qaColumns.find((c) => c.key === field)!.label}`}
title={downvoteLocked ? '已点踩,是否正确固定为否' : '选择后自动保存'}
value={rootNotNeeded ? '' : value}
disabled={
saving ||
!!pending ||
!options ||
!record.record_origin ||
!record.quality ||
rootNotNeeded ||
downvoteLocked
}
style={qaFieldColors(field, value || '—')}
onChange={(e) => {
if (e.target.value === editableFieldValue(record, field)) return
try {
const next = { record, field, value: e.target.value, nonce: newOperationID() }
setPending(next)
void save(next)
} catch (e) {
setError(e instanceof Error ? e.message : '无法生成保存标识')
}
}}
>
<option value="" disabled>
{rootNotNeeded ? '无需根因' : '未设置'}
</option>
{value && !options?.[field].includes(value) ? (
<option value={value} disabled>
{value}
</option>
) : null}
{options?.[field].map((v) => (
<option key={v} value={v}>
{v}
</option>
))}
</select>
</label>
</div>
)
})}
</div>
{record.quality?.feedback_rule === 'downvote-is-incorrect-v1' ? (
<p className="qa-inline-save">已点踩,是否正确固定为否</p>
) : null}
{saving || notice ? (
<p className="qa-inline-save" role="status" aria-live="polite">
{saving ? '保存中…' : notice}
</p>
) : null}
{error ? (
<p role="alert" className="error-banner">
{error}{' '}
{pending ? (
<>
<button type="button" disabled={saving} onClick={() => void save(pending)}>
重试保存
</button>
<button
type="button"
disabled={saving}
onClick={() => {
setPending(null)
setError('')
onReload()
}}
>
放弃并重读
</button>
</>
) : (
<button type="button" onClick={() => setReloadOptions((v) => v + 1)}>
重试读取选项
</button>
)}
</p>
) : null}
</div>
)
}
+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>
+52 -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'
@@ -50,6 +52,15 @@ const props = {
}
describe('QA operations workbench', () => {
it('edits five fields directly in the first row without a separate review or feedback form', () => {
const html = renderToStaticMarkup(
<QAOperationsView {...props} detail={{ ...item, record_origin: 'historical_excel' }} />
)
const drawer = html.slice(html.indexOf('<aside'))
expect((drawer.match(/<select/g) ?? []).length).toBe(5)
for (const copy of ['人工复核与留档', '保存复核', '复核理由', '用户反馈', '质量留档/人工复核未配置'])
expect(drawer).not.toContain(copy)
})
it('shows each persisted AI task in the existing operation cell and explains positive master coverage', () => {
const withTasks = {
...item,
@@ -101,12 +112,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 +129,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 +194,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/)
})
+110 -120
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 { QAInlineFields } from './QAInlineFields'
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,14 @@ export function QAOperationsView(props: ViewProps) {
关闭详情
</button>
</header>
{detail ? (
<QAInlineFields
key={detail.id}
record={detail}
onSaved={props.onQualitySaved ?? (() => {})}
onReload={props.onReloadDetail ?? (() => {})}
/>
) : null}
{props.detailLoading ? <p role="status">正在读取完整问答…</p> : null}
{props.detailError ? (
<p className="error-banner" role="alert">
@@ -258,55 +300,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>
@@ -336,28 +330,6 @@ export function QAOperationsView(props: ViewProps) {
?.map((task) => task.updated_at)
.join(':')}
/>
{detail.quality ? (
<QAQualityEditor
key={detail.id}
recordId={detail.id}
dataset={detail.record_origin ? 'master' : undefined}
quality={detail.quality}
onSaved={props.onQualitySaved ?? (() => {})}
onReload={props.onReloadDetail ?? (() => {})}
/>
) : (
<p className="qa-ops-muted">质量留档/人工复核未配置。</p>
)}
<h4>用户反馈</h4>
<p>
提问人:
{detail.feedback.asker_value === 'up'
? '点赞'
: detail.feedback.asker_value === 'down'
? '点踩'
: '无反馈'}
;全部反馈:赞 {detail.feedback.up} / 踩 {detail.feedback.down}
</p>
<h4>引用知识</h4>
<pre>{JSON.stringify(detail.references, null, 2)}</pre>
<details>
@@ -381,6 +353,10 @@ function initialDraft() {
export function QAOperations() {
const [view, setView] = useState<QAOpsView>('records')
const weeklyBeforeLeave = useRef<(() => Promise<boolean>) | null>(null)
const registerWeeklyLeave = useCallback((guard: (() => Promise<boolean>) | null) => {
weeklyBeforeLeave.current = guard
}, [])
const auth = useOptionalAuth()
const canRead = auth?.identity?.role === 'admin'
const [draft, setDraft] = useState(initialDraft)
@@ -530,7 +506,16 @@ export function QAOperations() {
</p>
) : (
<>
<QAOperationsTabs view={view} onChange={setView} />
<QAOperationsTabs
view={view}
onChange={(next) => {
if (view === 'weekly' && next !== 'weekly' && weeklyBeforeLeave.current)
void weeklyBeforeLeave.current().then((ok) => {
if (ok) setView(next)
})
else setView(next)
}}
/>
{queryView ? (
<>
{mirrorChanged ? <p className="qa-ops-warning">数据已更新,关闭详情后刷新。</p> : null}
@@ -582,7 +567,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,9 +588,14 @@ export function QAOperations() {
</>
) : null}
{view === 'regions' ? (
<QARegions />
<QARegionalStatistics
onSaved={() => {
setRevision((v) => v + 1)
setQualityRevision((v) => v + 1)
}}
/>
) : view === 'weekly' ? (
<QAWeekly query={query} />
<QAWeekly onBeforeLeave={registerWeeklyLeave} />
) : view === 'dashboard' ? (
<QADashboard
query={query}
+17
View File
@@ -0,0 +1,17 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, it, expect, vi } from 'vitest'
import { QAPeriodInput } from './QAPeriodInput'
describe('one period value with two input methods', () => {
it('offers a text input and dropdown for both months and ISO weeks', () => {
for (const kind of ['month', 'week'] as const) {
const value = kind === 'month' ? '2026-10' : '2026-W43'
const html = renderToStaticMarkup(
<QAPeriodInput kind={kind} label="统计周期" ariaLabel="测试周期" value={value} max={value} onChange={vi.fn()} />
)
expect(html).toContain('type="text"')
expect(html).toContain('<select')
expect(html).toContain(`value="${value}"`)
expect(html).toContain('测试周期下拉选择')
}
})
})
+102
View File
@@ -0,0 +1,102 @@
import { useEffect, useId, useMemo, useState } from 'react'
import type { QAPeriodKind } from './qaPeriodInput'
import { periodInputOptions, validPeriodInput } from './qaPeriodInput'
import { qaWeek } from './qaWeeks'
import './qaPeriodInput.css'
export interface QAPeriodInputProps {
kind: QAPeriodKind
label: string
ariaLabel: string
value: string
max: string
onChange: (value: string) => void
disabled?: boolean
}
export function QAPeriodInput(p: QAPeriodInputProps) {
const id = useId(),
[text, setText] = useState(p.value),
[error, setError] = useState('')
useEffect(() => {
setText(p.value)
setError('')
}, [p.value, p.kind])
const options = useMemo(() => {
const values = periodInputOptions(p.kind, p.max)
if (validPeriodInput(p.kind, p.value, p.max) && !values.includes(p.value)) values.push(p.value)
return values
}, [p.kind, p.max, p.value])
const apply = () => {
if (text === p.value) return
if (!validPeriodInput(p.kind, text, p.max)) {
setError(
`请输入有效的${p.kind === 'month' ? 'YYYY-MM月份' : 'YYYY-Www自然周'},最早2000年、不晚于${p.max};仍显示${p.value}的结果`
)
return
}
setError('')
p.onChange(text)
}
return (
<div className="qa-period-input">
<label htmlFor={id}>{p.label}</label>
<div className="qa-period-combo">
<input
id={id}
type="text"
aria-label={p.ariaLabel}
aria-describedby={`${id}-hint`}
aria-invalid={!!error}
autoComplete="off"
spellCheck={false}
value={text}
disabled={p.disabled}
placeholder={p.kind === 'month' ? 'YYYY-MM' : 'YYYY-Www'}
onChange={(e) => {
setText(e.target.value)
setError('')
}}
onBlur={apply}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
apply()
}
if (e.key === 'Escape') {
setText(p.value)
setError('')
}
}}
/>
<select
aria-label={`${p.ariaLabel}下拉选择`}
value=""
disabled={p.disabled}
onChange={(e) => {
const value = e.target.value
if (!value) return
setText(value)
setError('')
p.onChange(value)
}}
>
<option value="" disabled>
选择
</option>
{options.map((v) => (
<option key={v} value={v}>
{p.kind === 'week' ? `${v} ${qaWeek(Number(v.slice(0, 4)), Number(v.slice(6))).label}` : v}
</option>
))}
</select>
</div>
<small id={`${id}-hint`} role={error ? 'alert' : undefined}>
{error ||
(text !== p.value
? '尚未应用,按回车或移开输入框确认'
: p.kind === 'week'
? qaWeek(Number(p.value.slice(0, 4)), Number(p.value.slice(6))).label
: '可下拉选择,也可直接输入')}
</small>
</div>
)
}
+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)}
+255 -79
View File
@@ -1,97 +1,273 @@
import { useEffect, useRef, useState } from 'react'
import { useDeferredValue, useEffect, useState, useSyncExternalStore } from 'react'
import type { QAQuery } from './qaOps'
import { fetchAllQARecords } from './qaOps'
import { fetchQADashboardQuality } from './qaDashboard'
import { fetchQAMirrorStatus } from './qaMirror'
import { buildQAWeeklyDraft, downloadQAWeekly } from './qaWeekly'
import type { QAWeeklyDraft } from './qaWeekly'
import { currentQAWeekValue, qaDateTimeToISO, qaWeekQueryRange } from './qaWeeks'
import { WeeklyDraftEditorModel } from './qaWeeklyDrafts'
import { weeklyTransport } from './qaWeeklyDraftAPI'
import { buildQAWeeklyCSV, downloadQAWeekly } from './qaWeekly'
import { QAAnswerMarkdown } from './QAAnswerMarkdown'
export function QAWeekly({ query }: { query: QAQuery | null }) {
const [draft, setDraft] = useState<QAWeeklyDraft | null>(null),
[loading, setLoading] = useState(false),
[error, setError] = useState('')
const request = useRef<AbortController | null>(null)
import { QAPeriodInput } from './QAPeriodInput'
import './qaWeeklyEditor.css'
type LeaveGuard = (() => Promise<boolean>) | null
interface Props {
query?: QAQuery | null
onBeforeLeave?: (guard: LeaveGuard) => void
}
export function QAWeekly({ onBeforeLeave }: Props) {
const [model] = useState(() => new WeeklyDraftEditorModel(currentQAWeekValue(), weeklyTransport))
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot)
const [mode, setMode] = useState<'edit' | 'preview' | 'both'>('both'),
[replaceConfirm, setReplaceConfirm] = useState(false),
[reloadConfirm, setReloadConfirm] = useState(false),
[periodReset, setPeriodReset] = useState(0),
[exporting, setExporting] = useState(false),
[exportError, setExportError] = useState('')
const preview = useDeferredValue(state.text)
useEffect(() => {
request.current?.abort()
setDraft(null)
setError('')
setLoading(false)
return () => request.current?.abort()
}, [query])
const generate = async () => {
if (!query || loading) return
request.current?.abort()
const controller = new AbortController()
request.current = controller
setLoading(true)
setDraft(null)
setError('')
void model.initialize()
const unload = (e: BeforeUnloadEvent) => {
if (model.dirty || model.uncertainPrefill) {
e.preventDefault()
e.returnValue = ''
}
}
window.addEventListener('beforeunload', unload)
return () => {
window.removeEventListener('beforeunload', unload)
if (model.dirty && !model.uncertainPrefill) void model.beforeLeave().finally(() => model.dispose())
else model.dispose()
}
}, [model])
useEffect(() => {
onBeforeLeave?.(() => model.beforeLeave())
return () => onBeforeLeave?.(null)
}, [model, onBeforeLeave])
const blocked = state.busy || state.loading || !state.document || model.uncertainPrefill
const status = state.loading
? 'loading'
: state.saving
? 'saving'
: state.busy
? 'working'
: state.error
? 'error'
: model.dirty
? 'dirty'
: state.document?.revision
? 'saved'
: 'empty'
const source = state.document?.seed
const generate = () => {
setReplaceConfirm(false)
setReloadConfirm(false)
void model.prefill()
}
const csv = async () => {
if (exporting) return
setExporting(true)
setExportError('')
try {
const before = await fetchQAMirrorStatus(controller.signal)
if (!before.ready || before.blocked) throw Error('本地同步未就绪,暂不能生成周报')
const [page, quality] = await Promise.all([
fetchAllQARecords(query, controller.signal),
fetchQADashboardQuality(query, controller.signal),
])
const after = await fetchQAMirrorStatus(controller.signal)
if (!after.ready || after.blocked || before.revision !== after.revision || page.local_revision !== after.revision)
throw Error('本地副本在生成期间已更新,请重新生成')
const result = buildQAWeeklyDraft(page, query, quality, new Date().toISOString())
if (!controller.signal.aborted) setDraft(result)
const range = qaWeekQueryRange(Number(state.week.slice(0, 4)), Number(state.week.slice(6)))
const start = typeof source?.start === 'string' ? source.start : qaDateTimeToISO(range.start),
end = typeof source?.end === 'string' ? source.end : qaDateTimeToISO(range.end)
const page = await fetchAllQARecords({ dataset: 'master', start, end, keyword: '', cursor: '' })
downloadQAWeekly(buildQAWeeklyCSV(page), `DobotAI-Questions-${state.week}.csv`, 'text/csv;charset=utf-8')
} catch (e) {
if (!controller.signal.aborted) setError(e instanceof Error ? e.message : '周报生成失败')
setExportError(e instanceof Error ? e.message : '明细导出失败')
} finally {
if (!controller.signal.aborted) setLoading(false)
setExporting(false)
}
}
const suffix = query ? new Date(Date.parse(query.start) + 8 * 60 * 60 * 1000).toISOString().slice(0, 10) : 'draft'
return (
<section className="qa-weekly" aria-label="周报生成">
<header className="qa-weekly-toolbar">
<div>
<h3>周报生成</h3>
{query ? (
<span>
{new Date(query.start).toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' })} 至{' '}
{new Date(Date.parse(query.end) - 1).toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' })}
</span>
) : null}
<section className="qa-weekly qa-weekly-editor" aria-label="周报生成" data-weekly-week={state.week}>
<header className="qa-weekly-editor-header">
<h3>周报草稿</h3>
<QAPeriodInput
key={`${state.week}:${periodReset}`}
kind="week"
label="周报周次"
ariaLabel="周报周次"
value={state.week}
max={currentQAWeekValue()}
disabled={state.busy || state.loading}
onChange={(week) => {
setReplaceConfirm(false)
setReloadConfirm(false)
setExportError('')
void model.switchWeek(week).then((ok) => {
if (!ok) setPeriodReset((v) => v + 1)
})
}}
/>
<div className="qa-weekly-editor-actions">
{replaceConfirm ? (
<>
<button type="button" className="qa-weekly-prefill" onClick={() => setReplaceConfirm(false)}>
取消
</button>
<button type="button" onClick={generate}>
确认替换预填
</button>
</>
) : (
<button
type="button"
className="qa-weekly-prefill"
disabled={blocked || state.errorKind === 'conflict'}
onClick={() => {
if (state.document?.revision || state.text) setReplaceConfirm(true)
else generate()
}}
>
{state.document?.revision ? '重新预填数据' : '生成并预填草稿'}
</button>
)}
<button
type="button"
disabled={blocked || !model.dirty || state.saving || state.errorKind === 'conflict'}
onClick={() => void model.beforeLeave()}
>
立即保存
</button>
<button
type="button"
disabled={!state.document}
onClick={() =>
downloadQAWeekly(state.text, `DobotAI_KB_Weekly_Report_${state.week}.md`, 'text/markdown;charset=utf-8')
}
>
下载 MD
</button>
<button type="button" disabled={!state.document || exporting || state.busy} onClick={() => void csv()}>
{exporting ? '导出中…' : '下载明细 CSV'}
</button>
</div>
<button type="button" onClick={() => void generate()} disabled={loading || !query}>
{loading ? '正在生成…' : '生成周报草稿'}
</button>
{draft ? (
<>
<span className="qa-weekly-badge">草稿 · {draft.questions} 条</span>
<button
type="button"
onClick={() =>
downloadQAWeekly(draft.markdown, `DobotAI-问答周报-${suffix}.md`, 'text/markdown;charset=utf-8')
}
>
下载 MD
</button>
<button
type="button"
onClick={() => downloadQAWeekly(draft.csv, `DobotAI-问题明细-${suffix}.csv`, 'text/csv;charset=utf-8')}
>
下载明细 CSV
</button>
</>
) : null}
</header>
{error ? (
<div className="qa-weekly-editor-toolbar">
<div className="qa-weekly-mode" aria-label="编辑与预览">
{(['edit', 'preview', 'both'] as const).map((value) => (
<button type="button" key={value} aria-pressed={mode === value} onClick={() => setMode(value)}>
{{ edit: '编辑', preview: '预览', both: '对照' }[value]}
</button>
))}
</div>
<span role="status" aria-live="polite" className="qa-weekly-editor-status" data-weekly-save-state={status}>
自动保存 ·{' '}
{
{
loading: '正在读取草稿…',
saving: '保存中…',
working: '正在处理…',
error: '未保存或尚未确认',
dirty: '待保存',
saved: '已保存',
empty: '尚未创建',
}[status]
}
{status === 'saved' && state.document?.updated_at
? ` · ${new Date(state.document.updated_at).toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })}`
: ''}
</span>
</div>
{replaceConfirm ? (
<p className="qa-ops-warning">将先保存当前文字,再用最新统计替换正文;旧保存版本保留。请确认后继续。</p>
) : null}
{state.error ? (
<div role="alert" className="error-banner">
{state.error}
{state.errorKind === 'load' ? (
<button type="button" disabled={state.busy} onClick={() => void model.reload()}>
重试读取
</button>
) : state.errorKind === 'save' ? (
<button type="button" disabled={state.saving || state.busy} onClick={() => void model.beforeLeave()}>
重试保存
</button>
) : state.errorKind === 'prefill' ? (
<button type="button" disabled={state.busy} onClick={generate}>
重试确认预填
</button>
) : null}
{reloadConfirm ? (
<>
<button type="button" className="qa-weekly-reload" onClick={() => setReloadConfirm(false)}>
取消
</button>
<button
type="button"
disabled={state.saving || state.busy}
onClick={() => {
setReloadConfirm(false)
void model.reload()
}}
>
放弃本地修改并读取
</button>
</>
) : (
<button
type="button"
className="qa-weekly-reload"
disabled={state.busy || state.saving}
onClick={() => setReloadConfirm(true)}
>
重新读取服务器版本
</button>
)}
</div>
) : null}
{exportError ? (
<p role="alert" className="error-banner">
{error}
{exportError}
</p>
) : null}
{draft ? (
<article className="qa-weekly-preview">
<QAAnswerMarkdown answer={draft.markdown} />
</article>
) : (
<div className="qa-weekly-empty">{loading ? '正在汇总本地问答…' : '尚未生成周报。'}</div>
)}
<div className="qa-weekly-editor-layout" data-mode={mode}>
{mode !== 'preview' ? (
<div className="qa-weekly-writing">
<label htmlFor="qa-weekly-body">
周报草稿正文 <small>Markdown</small>
</label>
<textarea
id="qa-weekly-body"
aria-label="周报草稿正文"
value={state.text}
disabled={blocked}
spellCheck={false}
placeholder="生成并预填草稿,或直接输入。英文完整部分在上,中文在下;输入后自动保存。"
onChange={(e) => model.setText(e.target.value)}
onKeyDown={(e) => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
e.preventDefault()
void model.beforeLeave()
}
}}
/>
</div>
) : null}
{mode !== 'edit' ? (
<article className="qa-weekly-preview" aria-label="周报预览">
{preview ? <QAAnswerMarkdown answer={preview} /> : <p className="qa-ops-muted">尚无草稿正文。</p>}
</article>
) : null}
</div>
{source && source.source === 'governance-master' ? (
<details className="qa-weekly-source">
<summary>预填来源</summary>
<p>
治理正式总表 · {String(source.week)} · 截至{' '}
{typeof source.end === 'string'
? new Date(source.end).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
: '—'}{' '}
·{' '}
{{ 'live-week': '当周实时质量指标', 'frozen-week': '已冻结周指标', 'reported-history': '历史上报指标' }[
String(source.quality_source)
] ?? '指标来源未确认'}
</p>
<p>
问题总数与新增是可编辑的系统统计建议;区域采用已保存配置及当前通讯录。未做新的FAQ调整,重点与英文文字请自行填写。草稿不会自动发送。
</p>
</details>
) : null}
</section>
)
}
+15
View File
@@ -0,0 +1,15 @@
import { renderToStaticMarkup } from 'react-dom/server'
import { describe, it, expect } from 'vitest'
import { QAWeekly } from './QAWeekly'
describe('weekly report editor surface', () => {
it('provides a weekly document editor, automatic-save status and a preview without an external-send action', () => {
const html = renderToStaticMarkup(<QAWeekly query={null} />)
expect(html).toContain('<textarea')
expect(html).toContain('周报草稿正文')
expect(html).toContain('自动保存')
expect(html).toContain('周报周次下拉选择')
expect(html).toContain('预览')
expect(html).not.toContain('发送周报')
expect(html).not.toContain('发布周报')
})
})
+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()
})
+43
View File
@@ -0,0 +1,43 @@
import { expect, it } from 'vitest'
import { createElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
import { parseQARecord, qaCellValue } from './qaOps'
import { fixtureRecord } from './qaOps.test'
import { fields, qualityFixture } from './qaQuality.fixture'
import { QAInlineFields } from './QAInlineFields'
const downvoted = {
...fixtureRecord,
record_origin: 'dobotai_2_0',
master_fields: { is_correct: '否' },
quality: {
...qualityFixture,
effective_source: 'master-effective-fields-v1',
feedback_rule: 'downvote-is-incorrect-v1',
effective: { ...fields, correctness: 'incorrect' },
},
}
it('accepts the explicit downvote rule while retaining the original positive human evidence', () => {
const row = parseQARecord(downvoted)
expect(qaCellValue(row, 'is_correct')).toBe('否')
expect(row.quality?.latest_review?.fields.correctness).toBe('correct')
})
it('does not accept a fabricated downvote rule or use it to change unrelated human fields', () => {
expect(() => parseQARecord({ ...downvoted, feedback: { asker_value: '', up: 0, down: 0 } })).toThrow()
expect(() => parseQARecord({ ...downvoted, record_origin: undefined })).toThrow()
expect(() => parseQARecord({ ...downvoted, quality: { ...downvoted.quality, feedback_rule: 'unknown' } })).toThrow()
expect(() =>
parseQARecord({
...downvoted,
quality: { ...downvoted.quality, effective: { ...fields, correctness: 'incorrect', coverage: 'uncovered' } },
})
).toThrow()
})
it('explains the fixed negative correctness without restoring the removed review form', () => {
const row = parseQARecord(downvoted)
const html = renderToStaticMarkup(
createElement(QAInlineFields, { record: row, onSaved: () => {}, onReload: () => {} })
)
expect(html).toContain('已点踩,是否正确固定为否')
expect(html).not.toContain('人工复核反馈')
})
+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
}
+73
View File
@@ -0,0 +1,73 @@
import { fetchQARecord, getPayload, qaCellValue } from './qaOps'
import type { QARecord } from './qaOps'
export const editableFieldKeys = ['coverage', 'is_correct', 'product_category', 'problem_type', 'root_cause'] as const
export type EditableField = (typeof editableFieldKeys)[number]
export type FieldOptions = Record<EditableField, string[]>
export function parseFieldOptions(raw: unknown): FieldOptions {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw Error('主表选项读取失败')
const v = raw as Record<string, unknown>
if (v.version !== 'qa-master-options-v1' || !v.fields || typeof v.fields !== 'object' || Array.isArray(v.fields))
throw Error('主表选项版本无效')
const fields = v.fields as Record<string, unknown>
if (Object.keys(fields).length !== editableFieldKeys.length) throw Error('主表选项不完整')
const result = {} as FieldOptions
for (const key of editableFieldKeys) {
const values = fields[key]
if (
!Array.isArray(values) ||
!values.length ||
values.some((v) => typeof v !== 'string' || !v.trim()) ||
new Set(values).size !== values.length
)
throw Error('主表选项不完整')
result[key] = values as string[]
}
return result
}
export async function fetchFieldOptions(signal?: AbortSignal) {
return parseFieldOptions(await getPayload('/api/v1/qa-ops/master/field-options', signal))
}
export function editableFieldValue(record: QARecord, field: EditableField): string {
if (field === 'root_cause' && qaCellValue(record, 'is_correct') === '是') return ''
const value = qaCellValue(record, field) ?? ''
return field === 'coverage' && value === '不计入' ? '否但不计入' : value
}
export async function saveInlineField(
record: QARecord,
field: EditableField,
value: string,
nonce: string,
signal?: AbortSignal
): Promise<QARecord> {
if (!record.record_origin || !record.quality) throw Error('此记录暂不可修改,请重新读取')
const q = record.quality
const raw = await getPayload(`/api/v1/qa-ops/master/records/${encodeURIComponent(record.id)}/fields`, signal, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-master-fields' },
body: JSON.stringify({
input_hash: q.input_hash,
input_epoch: q.input_epoch,
base_revision: record.field_edit_revision ?? 0,
base_review_revision: q.revision,
nonce,
fields: { [field]: value },
}),
})
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw Error('字段保存回执无效,请重试读取')
const receipt = raw as Record<string, unknown>
if (
!Number.isSafeInteger(receipt.saved_revision) ||
Number(receipt.saved_revision) < 1 ||
typeof receipt.replayed !== 'boolean'
)
throw Error('字段保存回执无效,请重试读取')
const fresh = await fetchQARecord(record.id, signal, 'master')
if (
fresh.field_edit_revision !== receipt.saved_revision ||
fresh.quality?.input_hash !== q.input_hash ||
fresh.quality.revision !== q.revision ||
editableFieldValue(fresh, field) !== value
)
throw Error('保存后字段再次变化,未将旧结果标为成功,请重新读取核对')
return fresh
}
+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);
}
+35 -4
View File
@@ -84,6 +84,7 @@ export function mergeQAPages(current: QARecordPage, next: QARecordPage): QARecor
}
}
export interface QARecord {
field_edit_revision?: number
background_tasks?: AIWorkState[]
record_origin?: 'dobotai_2_0' | 'historical_excel'
master_fields?: Partial<Record<QAColumn, string>>
@@ -184,7 +185,11 @@ export function parseQARecord(value: unknown): QARecord {
...(row.quality === undefined
? {}
: {
quality: parseQAQuality(row.quality, ['dobotai_2_0', 'historical_excel'].includes(String(row.record_origin))),
quality: parseQAQuality(
row.quality,
['dobotai_2_0', 'historical_excel'].includes(String(row.record_origin)),
askerValue === 'down' || count(feedback.down) > 0
),
}),
id: text(row.id),
status: text(row.status),
@@ -215,6 +220,7 @@ export function parseQARecord(value: unknown): QARecord {
if (typeof row.is_correct !== 'boolean' && row.is_correct !== null) return invalid()
item.is_correct = row.is_correct
}
if (row.field_edit_revision !== undefined) item.field_edit_revision = count(row.field_edit_revision)
if (row.record_origin !== undefined) {
if (row.record_origin !== 'dobotai_2_0' && row.record_origin !== 'historical_excel') return invalid()
item.record_origin = row.record_origin
@@ -291,6 +297,16 @@ export function parseQARecordPage(value: unknown): QARecordPage {
}
}
export class QARequestError extends Error {
constructor(
message: string,
public readonly status: number
) {
super(message)
this.name = 'QARequestError'
}
}
export async function getPayload(
path: string,
signal?: AbortSignal,
@@ -300,7 +316,10 @@ export async function getPayload(
const raw: unknown = await response.json().catch(() => null)
if (!response.ok) {
const payload = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : null
throw new Error(typeof payload?.error === 'string' ? payload.error : `问答数据读取失败(HTTP ${response.status})`)
throw new QARequestError(
typeof payload?.error === 'string' ? payload.error : `问答数据读取失败(HTTP ${response.status})`,
response.status
)
}
return object(raw).data
}
@@ -387,7 +406,20 @@ 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 === 'root_cause' && item.field_edit_revision && item.quality?.effective.correctness === 'correct')
return null
if (column === 'trigger_person') return triggerPersonName(item.master_fields?.trigger_person ?? item.trigger_person)
const reviewedQuality =
@@ -439,7 +471,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',
+89
View File
@@ -0,0 +1,89 @@
.qa-period-input {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
max-width: 100%;
font-size: 13px;
}
.qa-period-combo {
display: flex;
align-items: stretch;
width: 240px;
max-width: 100%;
border: 1px solid #d7e0eb;
border-radius: 8px;
background: #fff;
overflow: hidden;
}
.qa-period-combo input {
min-width: 0;
width: 100%;
flex: 1;
border: 0 !important;
border-radius: 0 !important;
background: transparent;
padding: 8px 10px;
font: inherit;
}
.qa-period-combo select {
width: 74px;
min-width: 74px;
border: 0 !important;
border-left: 1px solid #e3e9f0 !important;
border-radius: 0 !important;
background: #f5f8fc;
padding: 7px 5px;
font: inherit;
cursor: pointer;
}
.qa-period-combo:focus-within {
outline: 2px solid #83b6f4;
outline-offset: 1px;
}
.qa-period-input small {
font-size: 12px;
color: #64748b;
max-width: 360px;
white-space: normal;
}
.qa-period-input small[role='alert'] {
color: #b42318;
}
.qa-period-combo input[aria-invalid='true'] {
background: #fff4f2;
}
.qa-inline-fields {
flex: none;
min-width: 0;
}
.qa-inline-fields .qa-detail-quality label {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.qa-inline-fields .qa-detail-quality select {
min-width: 0;
width: 100%;
max-width: 100%;
border: 1px solid #d7e0eb;
border-radius: 6px;
padding: 6px 4px;
font: inherit;
font-weight: 600;
cursor: pointer;
}
.qa-inline-fields .qa-detail-quality select:disabled {
cursor: default;
opacity: 0.75;
}
.qa-inline-save {
margin: 2px 18px 6px;
font-size: 12px;
color: #35634c;
}
.qa-inline-fields > .error-banner {
margin: 4px 18px 8px;
font-size: 12px;
}
+17
View File
@@ -0,0 +1,17 @@
import { describe, it, expect } from 'vitest'
import { validPeriodInput, periodInputOptions } from './qaPeriodInput'
describe('typed or dropdown natural periods', () => {
it('accepts canonical months and real cross-year weeks and rejects incomplete, future or impossible inputs', () => {
expect(validPeriodInput('month', '2026-02', '2026-10')).toBe(true)
expect(validPeriodInput('week', '2020-W53', '2021-W01')).toBe(true)
for (const value of ['', '2026-1', '2026-00', '2026-13', '2027-01', ' 2026-02', '1999-12'])
expect(validPeriodInput('month', value, '2026-10')).toBe(false)
for (const value of ['', '2021-W53', '2021-W1', '2021-W00', '2026-W44', '2020-W+1', '2020-W53 '])
expect(validPeriodInput('week', value, '2026-W43')).toBe(false)
})
it('offers selectable periods across year boundaries without replacing the typed value with an invalid date', () => {
expect(periodInputOptions('week', '2021-W01').slice(0, 2)).toEqual(['2021-W01', '2020-W53'])
expect(periodInputOptions('month', '2026-01').slice(0, 2)).toEqual(['2026-01', '2025-12'])
expect(periodInputOptions('week', '2021-W53')).toEqual([])
})
})
+44
View File
@@ -0,0 +1,44 @@
import { qaWeek, currentQAWeek, qaWeekValue } from './qaWeeks'
export type QAPeriodKind = 'month' | 'week'
export function validPeriodInput(kind: QAPeriodKind, value: string, max?: string): boolean {
const pattern = kind === 'month' ? /^[0-9]{4}-[0-9]{2}$/ : /^[0-9]{4}-W[0-9]{2}$/
if (!pattern.test(value)) return false
const year = Number(value.slice(0, 4))
if (year < 2000 || year > 9998) return false
if (kind === 'month') {
const month = Number(value.slice(5))
if (month < 1 || month > 12) return false
} else {
try {
qaWeek(year, Number(value.slice(6)))
} catch {
return false
}
}
return !max || (validPeriodInput(kind, max) && value <= max)
}
export function periodInputOptions(kind: QAPeriodKind, max: string): string[] {
if (!validPeriodInput(kind, max)) return []
const result: string[] = []
if (kind === 'month') {
let year = Number(max.slice(0, 4)),
month = Number(max.slice(5))
for (let i = 0; i < 36 && year >= 2000; i++) {
result.push(`${year}-${String(month).padStart(2, '0')}`)
month--
if (month === 0) {
year--
month = 12
}
}
} else {
const start = qaWeek(Number(max.slice(0, 4)), Number(max.slice(6))).start
const monday = Date.parse(`${start}:00Z`)
for (let i = 0; i < 156; i++) {
const p = currentQAWeek(new Date(monday - i * 7 * 86400000))
if (p.year < 2000) break
result.push(qaWeekValue(p))
}
}
return result
}
+11 -2
View File
@@ -26,6 +26,7 @@ export interface QualityReview {
}
export interface QAQuality {
effective_source?: 'master-effective-fields-v1'
feedback_rule?: 'downvote-is-incorrect-v1'
input_hash: string
input_epoch: number
revision: number
@@ -192,7 +193,7 @@ function review(value: unknown): QualityReview {
created_at: stamp(v.created_at),
}
}
export function parseQAQuality(value: unknown, allowMasterProjection = false): QAQuality {
export function parseQAQuality(value: unknown, allowMasterProjection = false, hasDownvote = false): QAQuality {
const v = obj(value),
state = text(v.state)
if (!['unreviewed', 'reviewed', 'stale'].includes(state)) return bad()
@@ -219,11 +220,18 @@ export function parseQAQuality(value: unknown, allowMasterProjection = false): Q
state === 'reviewed' ? latest_review!.fields : { ...emptyQualityFields, coverage: automatic.result.verdict || '' }
const master = v.effective_source === 'master-effective-fields-v1'
if (v.effective_source !== undefined && (!master || !allowMasterProjection)) return bad()
const downvoteRule = v.feedback_rule === 'downvote-is-incorrect-v1'
if (
v.feedback_rule !== undefined &&
(!downvoteRule || !master || !allowMasterProjection || !hasDownvote || effective.correctness !== 'incorrect')
)
return bad()
for (const key of Object.keys(expected) as (keyof QualityFields)[]) {
// The versioned master layer may fill missing fields, but never change an explicit human decision.
// Only the explicit feedback rule may override correctness; the human evidence stays intact.
if (master) {
if (
state === 'reviewed' &&
!(downvoteRule && key === 'correctness') &&
(expected[key] !== '' || (key === 'root_cause' && expected.correctness === 'correct')) &&
expected[key] !== effective[key]
)
@@ -239,6 +247,7 @@ export function parseQAQuality(value: unknown, allowMasterProjection = false): Q
latest_review,
effective,
...(master ? { effective_source: 'master-effective-fields-v1' as const } : {}),
...(downvoteRule ? { feedback_rule: 'downvote-is-incorrect-v1' as const } : {}),
}
}
function qualityRate(value: unknown): QualityRate {
+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()
})

Some files were not shown because too many files have changed in this diff Show More