Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f5e0f8d20f | |||
| 6e67034fbd | |||
| 76671e0784 | |||
| 8835a473dd | |||
| 93aabc8a81 | |||
| 3e7fcce0b1 | |||
| 74ba737b1e |
@@ -76,6 +76,97 @@
|
||||
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯,
|
||||
> 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。
|
||||
|
||||
## 开发快照 snapshot/v0.1.33 - 2026-10-19
|
||||
|
||||
### Added
|
||||
|
||||
- 问题流水读取治理侧独立正式总表,合并历史 Excel 与已收录的 2.0 问答;历史译文、答案、覆盖/正确标注、分类及人员字段保留原值,缺失不造值,来源可辨。
|
||||
- 新增受输入哈希、已批准逐行清单和真实恢复备份约束的历史导入命令,固定首表与提问时间/提问人/原始问题组合;保留批次、原字段、行号、重复跳过与缺字段暂缓证据。重复导入只读回收据,不覆盖后续主表修改。
|
||||
|
||||
### Changed
|
||||
|
||||
- 新增治理侧加表迁移 53。2.0 镜像仍独立同步,正式主表只接收新事件;稳定来源关联与原始事件键不随本地修改丢失,源端更新和删除不覆盖或清除主表。
|
||||
- 主表评估/复核与可替换的源副本分开持久化;首次收录保留已有评估及审计来源,后续人工复核绑定主表自身的输入版本,不被源同步失效。原 2.0 看板、历史冻结及周报统计范围不因导入被静默混算。
|
||||
|
||||
### Security
|
||||
|
||||
- 主表列表、详情、复核与历史接口复用固定租户、管理员会话、严格参数、同源写意图、乐观锁和幂等回执;拒绝缓存、稳定 ID 与原始溯源不可漂移。字段计数和质量范围只读标量元数据,不为全范围统计解压长答案。
|
||||
- 导入仅连接本地治理库,不连接或修改 DobotAI 2.0 生产源、现有隧道与外部表;应用回退保留加表,有历史导入、本地修改或新增复核时拒绝有损结构回退。
|
||||
|
||||
## 开发快照 snapshot/v0.1.32 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 问题统计看板按参考布局提供完整十一项:2.0 累计问题、本周新增、覆盖率与正确率半环、问题类型饼图、产品横条排行、所选自然周逐日折线、区域平均使用频率与使用覆盖率、两条历史质量周趋势。未知分类保留为未分类,未知分母及历史缺失点不伪造为零。
|
||||
- 支持导出当前完整看板 PNG,包含所有图形、中文、图例与数值,独立于屏幕滚动高度;不包含导航、筛选控件、按钮或个人月明细。桌面与窄屏共享同一份数据及响应式图形。
|
||||
- 治理侧保存自然周质量冻结快照与逐条标量贡献;普通 worker 在符合采集条件的下一周一自动冻结上一周,保存实际时点、源观测、版本和分子分母。首次启用前、错过采集或没有完整观测的历史周保持空白,后续人工改判不回写已冻结比率。
|
||||
|
||||
### Changed
|
||||
|
||||
- 看板通过单一只读一致性接口聚合治理副本、有效质量与组织版本,不连接源端、不下载全部长答案;累计、所选自然周和截止月分别计算,原问题关键词按字面筛选。区域分母使用配置后的通讯录去重人数,仅用于使用统计,个人月明细与四页共享查询保留。
|
||||
- 新增加表迁移 52。应用回退保留加表;发现冻结历史时拒绝有损 down。未接入翻译/AI 评估模型、绩效名单、1.0 归档或自动发送。
|
||||
|
||||
### Security
|
||||
|
||||
- 统计接口维持固定租户、管理员会话、同源动作头、严格 JSON 和 no-store;输入指纹变化返回冲突,不混合新旧结论。数据库拒绝修改、删除或追加已提交的冻结贡献;浏览器查询不写指标,PNG 使用自包含 SVG,不加载外部图片或执行原始 HTML。
|
||||
|
||||
## 开发快照 snapshot/v0.1.31 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 区域配置支持新增、改名业务区域;稳定区域 ID 与部门映射同版本保存,改名不丢失归属。部门按一级、二级、三级及更深层级展示,支持层级/完整路径筛选、多选及批量归属。
|
||||
- 勾选、批量应用、预览和保存分离;取消本次勾选不删除既有映射,批量配置父部门不清除未选子部门的显式规则。预览核对去重人数,保存后独立读取并校验配置版本。
|
||||
|
||||
### Changed
|
||||
|
||||
- 新增治理库迁移 51,为历史区域修订补齐原四区目录;业务目录与映射原子留档,跨页问答、看板、使用统计、个人月明细和周报共用同一版本及名称。旧请求未传目录时沿用当前目录,不恢复固定四区白名单。
|
||||
- 迁移回退发现自定义区域历史时拒绝丢失目录;应用回退可保留加列迁移。统计人数不升级为在职或绩效分母,不改钉钉组织、DobotAI 原始数据及旧 Excel 流程。
|
||||
|
||||
### Security
|
||||
|
||||
- 配置请求拒绝缺失版本、重复 JSON 字段及嵌套 null;区域目录校验稳定 ID、重名及保留键,名称按文本展示,自定义名称不读取原型属性。保留管理员同源写入、租户隔离和双版本冲突保护。
|
||||
|
||||
## 开发快照 snapshot/v0.1.30 - 2026-10-18
|
||||
|
||||
### Changed
|
||||
|
||||
- 继续清理问答运营的冗余提示:质量统计移除完整范围留档、模型接入和读取时间说明;个人月明细移除重复的绩效/零记录解释及读取时间,保留实际数量、范围版本、分页和真实错误。质量统计按钮使用简短名称,不改统计与审计逻辑。
|
||||
|
||||
## 开发快照 snapshot/v0.1.29 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 问答运营调整为“问题流水、问题统计看板、区域配置、周报生成”四页,流水与看板共用年份、自然周和查询条件;区域页不再显示问题查询框,完整字段及人工复核入口保留。
|
||||
- 重做统计看板:展示完整筛选范围的问题量、覆盖率、正确率、人工复核、北京时间每日趋势、质量分布、区域、问题类型和产品分类;个人月明细折叠保留,未知分类与零分母不虚构结论。
|
||||
- 周报页提供手动草稿、Markdown 预览及 MD/完整明细 CSV 下载。核对副本版本、完整数量、质量范围与覆盖分布后生成;CSV 保留完整十五列并防护公式注入,不发送、不归档、不作为正式持久化周报验收。
|
||||
|
||||
### Changed
|
||||
|
||||
- 删除问答记录、同步栏和区域页中的冗余解释文字、读取时间与源连接提示,保留真实错误、未同步、权限阻断和安全告警。
|
||||
|
||||
## 开发快照 snapshot/v0.1.28 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 问答运营新增持久本地副本,每 5 分钟后台同步并支持立即同步;列表、详情、检索、质量范围和使用统计改为读取本地数据库。
|
||||
- AI 答案详情提供安全 Markdown 预览与原文查看,支持表格、代码块和链接;不执行原始 HTML,外部图片默认不请求。
|
||||
|
||||
### Changed
|
||||
|
||||
- 增加治理侧问答副本表与同步状态;同步由普通 worker 执行,使用独立只读源连接,源失败保留最后成功副本,权限校验失败阻断读取。
|
||||
- 副本激活与质量输入变化的复核失效同事务提交;同步持久去重、租约校验及重启恢复不改变源问答或现有生产写入。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 本地读取不再逐条重复写质量留档或解压完整范围长答案来统计字段,保留完整列、输入版本一致性和真实缺失值。
|
||||
- 初次观察即已同步完成时自动重查列表,避免较早的首次未同步错误一直停留。
|
||||
|
||||
## 开发快照 snapshot/v0.1.27 - 2026-10-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- 并行分支存在同号开发提交时,历史变更说明与补记标签计划按完整 SHA 选择,不再被前一条同号记录遮蔽;不强改推导版本号或移动既有标签。
|
||||
|
||||
## 开发快照 snapshot/v0.1.26 - 2026-10-18
|
||||
|
||||
### Fixed
|
||||
|
||||
+548
-2
@@ -48,6 +48,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":"管理员只读本地一致性看板:2.0累计、所选周、新增/质量/类别及截止月区域统计;历史质量仅真实冻结快照,缺失留空","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/organization": {
|
||||
"get": {
|
||||
"tags": ["QA operations"],
|
||||
@@ -69,7 +70,7 @@
|
||||
"operationId": "previewQAOrganizationRegions",
|
||||
"summary": "预览当前通讯录版本下的父子部门区域归属和去重人数,不保存修改",
|
||||
"parameters": [{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-organization"}}],
|
||||
"requestBody": {"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["directory_id","base_revision","rules"],"properties":{"directory_id":{"type":"string"},"base_revision":{"type":"string"},"rules":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["department_id","region"],"properties":{"department_id":{"type":"string"},"region":{"enum":["国内工业","APAC","EMEA","America"]}}}}}}}}},
|
||||
"requestBody": {"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["directory_id","base_revision","rules"],"properties":{"directory_id":{"type":"string"},"base_revision":{"type":"string"},"regions":{"type":"array","maxItems":100,"description":"可选业务区域目录;缺省沿用当前目录,空数组表示无区域;ID稳定不随名称改动。与rules同一版本原子预览/保存。","items":{"type":"object","additionalProperties":false,"required":["id","name"],"properties":{"id":{"type":"string","minLength":1,"maxLength":256},"name":{"type":"string","minLength":1,"maxLength":256}}}},"rules":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["department_id","region"],"properties":{"department_id":{"type":"string"},"region":{"type":"string","description":"目录中稳定的区域ID,不是固定四区枚举"}}}}}}}}},
|
||||
"responses": {
|
||||
"200": {"$ref": "#/components/responses/Envelope"},
|
||||
"400": {"$ref": "#/components/responses/BadRequest"},
|
||||
@@ -99,12 +100,99 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/qa-ops/usage/people": {"post": {"tags": ["QA operations"], "operationId": "queryQAOperationsMonthlyPeople", "summary": "按北京时间自然月列出当前名册人员的2.0用量(含零记录),仅管理员,不返回原始员工标识,不作为在职/考核名单", "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "完整名册缺失或目录/区域版本变化,请同步/重新查询,不返回伪零"}}, "description": "只读查询,不写治理库或生产库;姓名筛选置于 JSON 请求体,不进入 URL;整名册指标不随人员筛选变化。第2页起须带首页目录、区域版本及 end 截止。", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "required": ["month"], "properties": {"month": {"type": "string", "pattern": "^(?!0000)[0-9]{4}-(0[1-9]|1[0-2])$"}, "cutoff": {"type": "string", "format": "date-time"}, "region": {"type": "string", "enum": ["国内工业", "APAC", "EMEA", "America", "unassigned", "cross_region"]}, "department_id": {"type": "string"}, "activity": {"type": "string", "enum": ["all", "used", "zero"]}, "search": {"type": "string", "maxLength": 100}, "page": {"type": "integer", "minimum": 1, "maximum": 100000, "default": 1}, "limit": {"type": "integer", "minimum": 1, "maximum": 100, "default": 30}, "directory_id": {"type": "string"}, "revision_id": {"type": "string"}}}}}}, "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-usage-read"]}}]}},
|
||||
"/api/v1/qa-ops/usage/people": {"post": {"tags": ["QA operations"], "operationId": "queryQAOperationsMonthlyPeople", "summary": "按北京时间自然月列出当前名册人员的2.0用量(含零记录),仅管理员,不返回原始员工标识,不作为在职/考核名单", "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "完整名册缺失或目录/区域版本变化,请同步/重新查询,不返回伪零"}}, "description": "只读查询,不写治理库或生产库;姓名筛选置于 JSON 请求体,不进入 URL;整名册指标不随人员筛选变化。第2页起须带首页目录、区域版本及 end 截止。", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "required": ["month"], "properties": {"month": {"type": "string", "pattern": "^(?!0000)[0-9]{4}-(0[1-9]|1[0-2])$"}, "cutoff": {"type": "string", "format": "date-time"}, "region": {"type": "string", "description": "当前组织版本中的区域显示名称,或unassigned/cross_region;无效名称拒绝查询"}, "department_id": {"type": "string"}, "activity": {"type": "string", "enum": ["all", "used", "zero"]}, "search": {"type": "string", "maxLength": 100}, "page": {"type": "integer", "minimum": 1, "maximum": 100000, "default": 1}, "limit": {"type": "integer", "minimum": 1, "maximum": 100, "default": 30}, "directory_id": {"type": "string"}, "revision_id": {"type": "string"}}}}}}, "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-usage-read"]}}]}},
|
||||
"/api/v1/qa-ops/usage": {"get": {"tags": ["QA operations"], "operationId": "getQAOperationsUsage", "summary": "完整筛选范围内按当前通讯录和区域版本回看2.0问答使用;固定租户、管理员访问,不输出绩效结论", "parameters": [{"name": "start", "in": "query", "required": true, "schema": {"type": "string", "format": "date-time"}}, {"name": "end", "in": "query", "required": true, "schema": {"type": "string", "format": "date-time"}}, {"name": "keyword", "in": "query", "schema": {"type": "string", "maxLength": 200}}], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}}}},
|
||||
"/api/v1/qa-ops/quality/query": {"post": {"operationId": "queryQAQualityCounts", "summary": "按完整筛选范围读取指纹/规则元数据并留档统计,最多5000条;summary.rates 返回 quality-rates-human-first-v1、原始分子/分母、百分比与分母构成。覆盖率=covered/(covered+uncovered+partial),正确率=covered_correct/(covered_correct+covered_incorrect);失效/不计入/相应待确认与未评估排除,零分母percent=null。原文仅在读取问答/复核时采集", "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-quality"]}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"start": {"type": "string", "format": "date-time"}, "end": {"type": "string", "format": "date-time"}, "keyword": {"type": "string", "maxLength": 200}}, "required": ["start", "end"]}}}}, "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
|
||||
"/api/v1/qa-ops/records/{id}/reviews": {"post": {"operationId": "saveQAQualityReview", "summary": "治理库追加人工复核,登录身份审计,源端只读,输入/复核乐观锁和nonce幂等;正确时根因为空,不计入须说明原因", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}, {"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-quality"]}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"input_hash": {"type": "string", "pattern": "^[a-f0-9]{64}$"}, "input_epoch": {"type": "integer", "minimum": 1}, "base_revision": {"type": "integer", "minimum": 0}, "nonce": {"type": "string", "pattern": "^[A-Za-z0-9_-]{16,128}$"}, "fields": {"type": "object", "additionalProperties": false, "properties": {"coverage": {"type": "string", "enum": ["covered", "uncovered", "partial", "pending", "excluded"]}, "correctness": {"type": "string", "enum": ["correct", "incorrect", "pending"]}, "product_category": {"type": "string", "maxLength": 128}, "problem_type": {"type": "string", "maxLength": 128}, "root_cause": {"type": "string", "maxLength": 2000}, "exclusion_reason": {"type": "string", "maxLength": 2000}}, "required": ["coverage", "correctness"]}, "reason": {"type": "string", "minLength": 1, "maxLength": 4000}}, "required": ["input_hash", "input_epoch", "base_revision", "nonce", "fields", "reason"]}}}}, "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
|
||||
"/api/v1/qa-ops/records/{id}/quality/history": {"get": {"operationId": "listQAQualityHistory", "summary": "按当前固定租户查询不可变复检/人工历史,分别倒序分页,各20条", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}, {"name": "review_before", "in": "query", "schema": {"type": "integer", "minimum": 1}}, {"name": "check_before", "in": "query", "schema": {"type": "integer", "minimum": 1}}], "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
|
||||
"/api/v1/qa-ops/records/{id}/quality/inputs/{epoch}": {"get": {"operationId": "getQAQualityInputSnapshot", "summary": "管理员读取已采集的历史质量输入快照,不另存人员关联/反馈字段;元数据留档但未采集原文返回409,不编造空快照", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}, {"name": "epoch", "in": "path", "required": true, "schema": {"type": "integer", "minimum": 1}}], "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "该输入版本仅有指纹/规则元数据、原文未采集"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
|
||||
"/api/v1/qa-ops/sync": {
|
||||
"get": {
|
||||
"operationId": "getQALocalMirrorSync",
|
||||
"summary": "读取本地问答副本与后台同步状态(只读本地,不探测生产)",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "本地副本状态、最近成功时间、5分钟计划与安全作业进度;无问答原文/人员标识"
|
||||
},
|
||||
"400": {
|
||||
"description": "不接受查询参数"
|
||||
},
|
||||
"401": {
|
||||
"description": "未登录"
|
||||
},
|
||||
"403": {
|
||||
"description": "仅管理员"
|
||||
},
|
||||
"500": {
|
||||
"description": "治理库不可用"
|
||||
},
|
||||
"503": {
|
||||
"description": "本地同步未接线"
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"operationId": "enqueueQALocalMirrorSync",
|
||||
"summary": "同源管理员请求后台问答同步,持久去重,不同步阻塞查询",
|
||||
"parameters": [
|
||||
{
|
||||
"in": "header",
|
||||
"name": "X-Governance-Action",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"qa-records-sync"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"in": "header",
|
||||
"name": "Idempotency-Key",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 128
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"202": {
|
||||
"description": "已入队/重放/合并;须轮询状态,不代表同步成功"
|
||||
},
|
||||
"400": {
|
||||
"description": "非法参数、null、未知字段或缺nonce"
|
||||
},
|
||||
"401": {
|
||||
"description": "未登录"
|
||||
},
|
||||
"403": {
|
||||
"description": "非管理员/跨站/缺操作意图"
|
||||
},
|
||||
"409": {
|
||||
"description": "相同nonce的操作人/载荷冲突"
|
||||
},
|
||||
"500": {
|
||||
"description": "治理库不可用"
|
||||
},
|
||||
"503": {
|
||||
"description": "本地模式或执行器未接线;未创建任务"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/qa-ops/status": {
|
||||
"get": {
|
||||
"tags": ["QA operations"],
|
||||
@@ -119,6 +207,464 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/qa-ops/master/records": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"QA operations"
|
||||
],
|
||||
"operationId": "listQAOperationsRecordsMaster",
|
||||
"summary": "正式主表:按半开提问时间范围、原问题关键词、稳定游标列出钉钉问答;租户由后端固定;答案包含暂无已发布则治理侧未覆盖",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "start",
|
||||
"in": "query",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "end",
|
||||
"in": "query",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "keyword",
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"maxLength": 200
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "cursor",
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"maxLength": 2048
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "limit",
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 100,
|
||||
"default": 20
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录"
|
||||
},
|
||||
"403": {
|
||||
"description": "未获员工问答查看授权"
|
||||
},
|
||||
"503": {
|
||||
"description": "源库未接入、不可用或权限护栏阻断,不返回空列表伪装成功"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
}
|
||||
},
|
||||
"description": "仅读治理正式主表,不回退源库;评估/复核采用独立主表命名空间,不被2.0同步覆盖。历史Excel原标注保留,不冒充新AI评估。"
|
||||
}
|
||||
},
|
||||
"/api/v1/qa-ops/master/records/{id}": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"QA operations"
|
||||
],
|
||||
"operationId": "getQAOperationsRecordMaster",
|
||||
"summary": "正式主表:读取授权租户内的完整问答与源端覆盖对照;治理覆盖规则独立,不写回源库",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"maxLength": 256
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录"
|
||||
},
|
||||
"403": {
|
||||
"description": "未获员工问答查看授权"
|
||||
},
|
||||
"404": {
|
||||
"description": "当前授权范围内不存在此问答"
|
||||
},
|
||||
"503": {
|
||||
"description": "独立只读源不可用或权限校验阻断"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
}
|
||||
},
|
||||
"description": "仅读治理正式主表,不回退源库;评估/复核采用独立主表命名空间,不被2.0同步覆盖。历史Excel原标注保留,不冒充新AI评估。"
|
||||
}
|
||||
},
|
||||
"/api/v1/qa-ops/master/quality/query": {
|
||||
"post": {
|
||||
"operationId": "queryQAQualityCountsMaster",
|
||||
"summary": "正式主表:按完整筛选范围读取指纹/规则元数据并留档统计,最多5000条;summary.rates 返回 quality-rates-human-first-v1、原始分子/分母、百分比与分母构成。覆盖率=covered/(covered+uncovered+partial),正确率=covered_correct/(covered_correct+covered_incorrect);失效/不计入/相应待确认与未评估排除,零分母percent=null。原文仅在读取问答/复核时采集",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "X-Governance-Action",
|
||||
"in": "header",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"qa-quality"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"start": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"end": {
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"keyword": {
|
||||
"type": "string",
|
||||
"maxLength": 200
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"start",
|
||||
"end"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"QA operations"
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录"
|
||||
},
|
||||
"403": {
|
||||
"description": "仅管理员访问"
|
||||
},
|
||||
"503": {
|
||||
"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"409": {
|
||||
"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"
|
||||
},
|
||||
"404": {
|
||||
"description": "当前授权范围内未找到记录/历史输入"
|
||||
}
|
||||
},
|
||||
"description": "仅读治理正式主表,不回退源库;评估/复核采用独立主表命名空间,不被2.0同步覆盖。历史Excel原标注保留,不冒充新AI评估。"
|
||||
}
|
||||
},
|
||||
"/api/v1/qa-ops/master/records/{id}/reviews": {
|
||||
"post": {
|
||||
"operationId": "saveQAQualityReviewMaster",
|
||||
"summary": "正式主表:治理库追加人工复核,登录身份审计,源端只读,输入/复核乐观锁和nonce幂等;正确时根因为空,不计入须说明原因",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "X-Governance-Action",
|
||||
"in": "header",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"qa-quality"
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"input_hash": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-f0-9]{64}$"
|
||||
},
|
||||
"input_epoch": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"base_revision": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"nonce": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{16,128}$"
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"coverage": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"covered",
|
||||
"uncovered",
|
||||
"partial",
|
||||
"pending",
|
||||
"excluded"
|
||||
]
|
||||
},
|
||||
"correctness": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"correct",
|
||||
"incorrect",
|
||||
"pending"
|
||||
]
|
||||
},
|
||||
"product_category": {
|
||||
"type": "string",
|
||||
"maxLength": 128
|
||||
},
|
||||
"problem_type": {
|
||||
"type": "string",
|
||||
"maxLength": 128
|
||||
},
|
||||
"root_cause": {
|
||||
"type": "string",
|
||||
"maxLength": 2000
|
||||
},
|
||||
"exclusion_reason": {
|
||||
"type": "string",
|
||||
"maxLength": 2000
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"coverage",
|
||||
"correctness"
|
||||
]
|
||||
},
|
||||
"reason": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 4000
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"input_hash",
|
||||
"input_epoch",
|
||||
"base_revision",
|
||||
"nonce",
|
||||
"fields",
|
||||
"reason"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": [
|
||||
"QA operations"
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录"
|
||||
},
|
||||
"403": {
|
||||
"description": "仅管理员访问"
|
||||
},
|
||||
"503": {
|
||||
"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"409": {
|
||||
"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"
|
||||
},
|
||||
"404": {
|
||||
"description": "当前授权范围内未找到记录/历史输入"
|
||||
}
|
||||
},
|
||||
"description": "仅读治理正式主表,不回退源库;评估/复核采用独立主表命名空间,不被2.0同步覆盖。历史Excel原标注保留,不冒充新AI评估。"
|
||||
}
|
||||
},
|
||||
"/api/v1/qa-ops/master/records/{id}/quality/history": {
|
||||
"get": {
|
||||
"operationId": "listQAQualityHistoryMaster",
|
||||
"summary": "正式主表:按当前固定租户查询不可变复检/人工历史,分别倒序分页,各20条",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "review_before",
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "check_before",
|
||||
"in": "query",
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"tags": [
|
||||
"QA operations"
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录"
|
||||
},
|
||||
"403": {
|
||||
"description": "仅管理员访问"
|
||||
},
|
||||
"503": {
|
||||
"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"409": {
|
||||
"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"
|
||||
},
|
||||
"404": {
|
||||
"description": "当前授权范围内未找到记录/历史输入"
|
||||
}
|
||||
},
|
||||
"description": "仅读治理正式主表,不回退源库;评估/复核采用独立主表命名空间,不被2.0同步覆盖。历史Excel原标注保留,不冒充新AI评估。"
|
||||
}
|
||||
},
|
||||
"/api/v1/qa-ops/master/records/{id}/quality/inputs/{epoch}": {
|
||||
"get": {
|
||||
"operationId": "getQAQualityInputSnapshotMaster",
|
||||
"summary": "正式主表:管理员读取已采集的历史质量输入快照,不另存人员关联/反馈字段;元数据留档但未采集原文返回409,不编造空快照",
|
||||
"parameters": [
|
||||
{
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "epoch",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"tags": [
|
||||
"QA operations"
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"$ref": "#/components/responses/Envelope"
|
||||
},
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"401": {
|
||||
"description": "需要登录"
|
||||
},
|
||||
"403": {
|
||||
"description": "仅管理员访问"
|
||||
},
|
||||
"503": {
|
||||
"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"
|
||||
},
|
||||
"500": {
|
||||
"$ref": "#/components/responses/InternalError"
|
||||
},
|
||||
"409": {
|
||||
"description": "该输入版本仅有指纹/规则元数据、原文未采集"
|
||||
},
|
||||
"404": {
|
||||
"description": "当前授权范围内未找到记录/历史输入"
|
||||
}
|
||||
},
|
||||
"description": "仅读治理正式主表,不回退源库;评估/复核采用独立主表命名空间,不被2.0同步覆盖。历史Excel原标注保留,不冒充新AI评估。"
|
||||
}
|
||||
},
|
||||
"/api/v1/qa-ops/records": {
|
||||
"get": {
|
||||
"tags": ["QA operations"],
|
||||
|
||||
+1
-1
@@ -137,7 +137,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
qaReader, qaSettings := openQAOperations(ctx, getenv, config.DatabaseURL)
|
||||
qaReader, qaSettings := openQAOperations(ctx, getenv, config.DatabaseURL, pool)
|
||||
if closer, ok := qaReader.(interface{ Close() }); ok {
|
||||
defer closer.Close()
|
||||
}
|
||||
|
||||
+12
-7
@@ -2,20 +2,25 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/httpapi"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A failed optional source must not replace or take down the main database.
|
||||
func openQAOperations(ctx context.Context, getenv func(string) string, governanceDSN string) (httpapi.QAOpsReader, dobotaiops.Settings) {
|
||||
// API serving never constructs or probes a production-source client. The worker
|
||||
// alone synchronizes the explicitly authorized local copy; this is not a fallback.
|
||||
func openQAOperations(_ context.Context, getenv func(string) string, governanceDSN string, pool *pgxpool.Pool) (httpapi.QAOpsReader, dobotaiops.Settings) {
|
||||
settings := dobotaiops.LoadSettings(getenv, governanceDSN)
|
||||
if !settings.Enabled || settings.Problem != "" {
|
||||
if !settings.Enabled {
|
||||
return nil, settings
|
||||
}
|
||||
client, err := dobotaiops.Build(ctx, settings.Connection)
|
||||
if err != nil {
|
||||
settings.Problem = "source_connection_or_permissions_failed"
|
||||
if settings.TenantKey == "" || len(settings.TenantKey) > 128 || strings.ContainsRune(settings.TenantKey, 0) {
|
||||
settings.Problem = "local_mirror_tenant_invalid"
|
||||
return nil, settings
|
||||
}
|
||||
return client, settings
|
||||
// Missing/offline source credentials stop synchronization, not last-good local reads.
|
||||
settings.Problem = ""
|
||||
return qaopsmirror.NewStore(pool, settings.TenantKey), settings
|
||||
}
|
||||
|
||||
@@ -6,13 +6,13 @@ import (
|
||||
)
|
||||
|
||||
func TestQAOpsConnectionFailureIsContainedOutsideMainDatabase(t *testing.T) {
|
||||
reader, settings := openQAOperations(context.Background(), func(string) string { return "" }, "postgres://main@host/governance")
|
||||
reader, settings := openQAOperations(context.Background(), func(string) string { return "" }, "postgres://main@host/governance", nil)
|
||||
if reader != nil || settings.Enabled || settings.Problem != "" {
|
||||
t.Fatal("QA operations must be disabled by default")
|
||||
}
|
||||
env := map[string]string{"DOBOTAI_OPS_READ_ENABLED": "true", "DOBOTAI_OPS_TENANT_KEY": "approved-tenant", "DOBOTAI_OPS_READ_DSN_FILE": "/nonexistent-qaops-fixture-secret"}
|
||||
reader, settings = openQAOperations(context.Background(), func(k string) string { return env[k] }, "postgres://main@host/governance")
|
||||
if reader != nil || !settings.Enabled || settings.Problem == "" {
|
||||
t.Fatal("failed external connection must be a contained module error")
|
||||
reader, settings = openQAOperations(context.Background(), func(k string) string { return env[k] }, "postgres://main@host/governance", nil)
|
||||
if reader == nil || !settings.Enabled || settings.Problem != "" {
|
||||
t.Fatal("API serving still constructs a source connection instead of a local reader")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,6 +56,10 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
if syncErr := configureDirectorySync(pool, getenv, handlers); syncErr != nil {
|
||||
log.Print("QA directory synchronization unavailable; handler was not registered")
|
||||
}
|
||||
mirrorStore, mirrorErr := configureRecordsSync(pool, getenv, config.DatabaseURL, handlers)
|
||||
if mirrorErr != nil {
|
||||
log.Print("QA local mirror configuration invalid; handler was not registered")
|
||||
}
|
||||
worker, err := jobs.NewWorker(jobs.WorkerConfig{
|
||||
Queue: store,
|
||||
WorkerID: config.WorkerID,
|
||||
@@ -67,6 +71,9 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mirrorStore != nil {
|
||||
go runRecordsSyncScheduler(ctx, mirrorStore, func(error) { log.Print("QA local mirror scheduler unavailable; last committed data retained") })
|
||||
}
|
||||
go runSourceRefreshScheduler(ctx, store, config.SourceRefreshSchedulerInterval, func(err error) {
|
||||
log.Printf("worker %s source refresh scheduler error: %v", config.WorkerID, err)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
type recordsSyncSchedulerStore interface {
|
||||
EnqueueDue(context.Context) (bool, error)
|
||||
TrackQualityWeeks(context.Context, time.Time) error
|
||||
FreezePreviousQualityWeek(context.Context, time.Time) (bool, error)
|
||||
}
|
||||
|
||||
func runRecordsSyncCycle(ctx context.Context, store recordsSyncSchedulerStore, at time.Time) error {
|
||||
_, syncErr := store.EnqueueDue(ctx)
|
||||
trackingErr := store.TrackQualityWeeks(ctx, at)
|
||||
if trackingErr != nil {
|
||||
return errors.Join(syncErr, trackingErr)
|
||||
}
|
||||
_, freezeErr := store.FreezePreviousQualityWeek(ctx, at)
|
||||
return errors.Join(syncErr, freezeErr)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type frozenScheduleSpy struct {
|
||||
calls []string
|
||||
trackErr error
|
||||
}
|
||||
|
||||
func (s *frozenScheduleSpy) EnqueueDue(context.Context) (bool, error) {
|
||||
s.calls = append(s.calls, "sync")
|
||||
return true, nil
|
||||
}
|
||||
func (s *frozenScheduleSpy) TrackQualityWeeks(context.Context, time.Time) error {
|
||||
s.calls = append(s.calls, "track")
|
||||
return s.trackErr
|
||||
}
|
||||
func (s *frozenScheduleSpy) FreezePreviousQualityWeek(context.Context, time.Time) (bool, error) {
|
||||
s.calls = append(s.calls, "freeze")
|
||||
return true, nil
|
||||
}
|
||||
func TestRecordsSchedulerActuallyCapturesFrozenWeeklyMetrics(t *testing.T) {
|
||||
s := &frozenScheduleSpy{}
|
||||
if e := runRecordsSyncCycle(context.Background(), s, time.Now()); e != nil || !reflect.DeepEqual(s.calls, []string{"sync", "track", "freeze"}) {
|
||||
t.Fatal("weekly capture is not on the real scheduler invocation path", e, s.calls)
|
||||
}
|
||||
broken := &frozenScheduleSpy{trackErr: errors.New("isolated tracking unavailable")}
|
||||
if e := runRecordsSyncCycle(context.Background(), broken, time.Now()); e == nil || !reflect.DeepEqual(broken.calls, []string{"sync", "track"}) {
|
||||
t.Fatal("snapshot failure must not suppress source sync or freeze untracked history")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func configureRecordsSync(pool *pgxpool.Pool, getenv func(string) string, governanceDSN string, handlers map[string]jobs.Handler) (*qaopsmirror.Store, error) {
|
||||
settings := dobotaiops.LoadSettings(getenv, governanceDSN)
|
||||
if !settings.Enabled {
|
||||
return nil, nil
|
||||
}
|
||||
if settings.TenantKey == "" || len(settings.TenantKey) > 128 || strings.ContainsRune(settings.TenantKey, 0) {
|
||||
return nil, qaopsmirror.ErrInvalid
|
||||
}
|
||||
store := qaopsmirror.NewStore(pool, settings.TenantKey)
|
||||
handlers[store.SyncJobType()] = func(ctx context.Context, job jobs.Job) error {
|
||||
return store.HandleSync(ctx, job, func(ctx context.Context) (qaopsmirror.Source, error) {
|
||||
current := dobotaiops.LoadSettings(getenv, governanceDSN)
|
||||
if !current.Enabled || current.Problem != "" || current.TenantKey != settings.TenantKey {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
// One source connection, shared by every manifest and bounded payload read in this job.
|
||||
current.Connection.MaxConns = 1
|
||||
current.Connection.MinConns = 0
|
||||
return dobotaiops.Build(ctx, current.Connection)
|
||||
})
|
||||
}
|
||||
return store, nil
|
||||
}
|
||||
|
||||
// The next due time and automatic operation key live in PostgreSQL, so a worker
|
||||
// restart does not reset the five-minute cadence or duplicate an active import.
|
||||
func runRecordsSyncScheduler(ctx context.Context, store *qaopsmirror.Store, onError func(error)) {
|
||||
tick := time.NewTicker(15 * time.Second)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if e := runRecordsSyncCycle(ctx, store, time.Now()); e != nil && ctx.Err() == nil && onError != nil {
|
||||
onError(e)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLocalMirrorWorkerRegistrationNeverConnectsSource(t *testing.T) {
|
||||
values := map[string]string{}
|
||||
get := func(k string) string { return values[k] }
|
||||
handlers := map[string]jobs.Handler{}
|
||||
if store, e := configureRecordsSync(nil, get, "postgres://fixture@localhost/local", handlers); e != nil || store != nil || len(handlers) != 0 {
|
||||
t.Fatal("disabled mirror registered")
|
||||
}
|
||||
values["DOBOTAI_OPS_READ_ENABLED"] = "true"
|
||||
values["DOBOTAI_OPS_TENANT_KEY"] = "fixture-worker-tenant"
|
||||
values["DOBOTAI_OPS_READ_DSN_FILE"] = "/nonexistent-fixture-source-secret"
|
||||
store, e := configureRecordsSync(nil, get, "postgres://fixture@localhost/local", handlers)
|
||||
if e != nil || store == nil || handlers[qaopsmirror.NewStore(nil, "fixture-worker-tenant").SyncJobType()] == nil {
|
||||
t.Fatal("local mirror handler missing; registration must not connect to source", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const MaxMirrorRecords = 100000
|
||||
const mirrorFingerprintSQL = `encode(sha256(convert_to((payload-'_quality_observed_at')::text,'UTF8')),'hex')`
|
||||
|
||||
type MirrorKey struct {
|
||||
ID string
|
||||
Fingerprint string
|
||||
}
|
||||
type MirrorManifest struct {
|
||||
Keys []MirrorKey
|
||||
AsOf time.Time
|
||||
Safety SourceSafety
|
||||
}
|
||||
type MirrorRecord struct {
|
||||
Key MirrorKey
|
||||
Payload json.RawMessage
|
||||
}
|
||||
|
||||
func validMirrorTenant(tenant string) bool {
|
||||
return strings.TrimSpace(tenant) == tenant && len(tenant) > 0 && len(tenant) <= 128 && !strings.ContainsRune(tenant, 0)
|
||||
}
|
||||
|
||||
// Only a manifest (IDs and stable hashes), not all long answers, crosses the
|
||||
// network on unchanged polls. Each read retains the source ACL and read-only gates.
|
||||
func (c *Client) ReadMirrorManifest(ctx context.Context, tenant string) (MirrorManifest, error) {
|
||||
out := MirrorManifest{Keys: []MirrorKey{}}
|
||||
if !validMirrorTenant(tenant) {
|
||||
return out, ErrInvalidQuery
|
||||
}
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&out.AsOf) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
rows, e := q.Query(ctx, recordsBaseSQL+` SELECT id,`+mirrorFingerprintSQL+` FROM records ORDER BY id LIMIT 100001`, tenant)
|
||||
if e != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var k MirrorKey
|
||||
if rows.Scan(&k.ID, &k.Fingerprint) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if len(out.Keys) >= MaxMirrorRecords {
|
||||
return ErrInvalidQuery
|
||||
}
|
||||
out.Keys = append(out.Keys, k)
|
||||
}
|
||||
return rows.Err()
|
||||
})
|
||||
out.Safety = c.Safety()
|
||||
return out, err
|
||||
}
|
||||
func (c *Client) ReadMirrorRecords(ctx context.Context, tenant string, ids []string) ([]MirrorRecord, error) {
|
||||
if !validMirrorTenant(tenant) || len(ids) == 0 || len(ids) > 100 {
|
||||
return nil, ErrInvalidQuery
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, id := range ids {
|
||||
if id == "" || len(id) > 256 || strings.ContainsRune(id, 0) || seen[id] {
|
||||
return nil, ErrInvalidQuery
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
out := make([]MirrorRecord, 0, len(ids))
|
||||
size := 0
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
rows, e := q.Query(ctx, recordsBaseSQL+` SELECT id,`+mirrorFingerprintSQL+`,payload FROM records WHERE id=ANY($2::text[]) ORDER BY id`, tenant, ids)
|
||||
if e != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var r MirrorRecord
|
||||
if rows.Scan(&r.Key.ID, &r.Key.Fingerprint, &r.Payload) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
size += len(r.Payload)
|
||||
if len(r.Payload) > 8<<20 || size > 32<<20 {
|
||||
return ErrInvalidQuery
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if len(out) != len(ids) {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMirrorSourceManifestDetectsUpdatesWithoutVolatileTimes(t *testing.T) {
|
||||
p := fixturePool(t)
|
||||
c := buildReadOnlyClient(t, qaRecordsFixture(t, p))
|
||||
ctx := context.Background()
|
||||
a, e := c.ReadMirrorManifest(ctx, "default")
|
||||
if e != nil || len(a.Keys) != 4 || a.AsOf.IsZero() {
|
||||
t.Fatal("full fixed-channel manifest is missing", e, len(a.Keys))
|
||||
}
|
||||
b, e := c.ReadMirrorManifest(ctx, "default")
|
||||
if e != nil || len(b.Keys) != len(a.Keys) {
|
||||
t.Fatal(e)
|
||||
}
|
||||
old := map[string]string{}
|
||||
for i, k := range a.Keys {
|
||||
old[k.ID] = k.Fingerprint
|
||||
if k != b.Keys[i] {
|
||||
t.Fatal("source clock alone changed the content fingerprint")
|
||||
}
|
||||
}
|
||||
rows, e := c.ReadMirrorRecords(ctx, "default", []string{"turn-3"})
|
||||
if e != nil || len(rows) != 1 || rows[0].Key.Fingerprint != old["turn-3"] {
|
||||
t.Fatal("bounded safe payload fetch failed", e)
|
||||
}
|
||||
before, e := DecodeMirrorPayload(string(rows[0].Payload))
|
||||
if e != nil || before.Feedback.Up != 1 || before.Identity.StaffID == "" {
|
||||
t.Fatal("safe payload lost required fields", e)
|
||||
}
|
||||
execFixture(t, p, `UPDATE answer_feedback SET value='down' WHERE id='fb1'`)
|
||||
after, e := c.ReadMirrorRecords(ctx, "default", []string{"turn-3"})
|
||||
if e != nil || after[0].Key.Fingerprint == old["turn-3"] {
|
||||
t.Fatal("feedback update on old question was missed", e)
|
||||
}
|
||||
rec, _ := DecodeMirrorPayload(string(after[0].Payload))
|
||||
if rec.QualityInputHash != before.QualityInputHash {
|
||||
t.Fatal("feedback invalidated unrelated human quality input")
|
||||
}
|
||||
execFixture(t, p, `UPDATE turns SET answer='changed answer' WHERE id='turn-3'`)
|
||||
after, e = c.ReadMirrorRecords(ctx, "default", []string{"turn-3"})
|
||||
rec, _ = DecodeMirrorPayload(string(after[0].Payload))
|
||||
if e != nil || rec.QualityInputHash == before.QualityInputHash {
|
||||
t.Fatal("answer change was missed")
|
||||
}
|
||||
if _, e = c.ReadMirrorRecords(ctx, "default", make([]string, 101)); e == nil {
|
||||
t.Fatal("unbounded payload fetch allowed")
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ type ActorIdentity struct {
|
||||
UnionID string `json:"union_id"`
|
||||
}
|
||||
type OrganizationVersion struct {
|
||||
RegionNames []string `json:"region_names"`
|
||||
State string `json:"state"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
DirectorySource string `json:"directory_source"`
|
||||
@@ -57,7 +58,7 @@ func decodeRecord(raw string) (Record, error) {
|
||||
wire.Record.Coverage = CheckAnswerCoverage(wire.Record.Answer)
|
||||
return wire.Record, nil
|
||||
}
|
||||
func (c *Client) ReadUsageGroups(ctx context.Context, query RecordQuery) (UsageGroups, error) {
|
||||
func (c *RecordsRepository) ReadUsageGroups(ctx context.Context, query RecordQuery) (UsageGroups, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return UsageGroups{}, err
|
||||
}
|
||||
@@ -69,11 +70,11 @@ func (c *Client) ReadUsageGroups(ctx context.Context, query RecordQuery) (UsageG
|
||||
return UsageGroups{}, patternErr
|
||||
}
|
||||
result := UsageGroups{Groups: []UsageGroup{}}
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&result.AsOf) != nil {
|
||||
err := c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
if c.readAsOf(ctx, q, &result.AsOf) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
rows, err := q.Query(ctx, recordsBaseSQL+` SELECT identity::text,count(*),count(*) FILTER(WHERE status='succeeded'),count(*) FILTER(WHERE status='failed') FROM records WHERE `+recordFilterSQL+` GROUP BY identity`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern)
|
||||
rows, err := q.Query(ctx, c.baseSQL+` SELECT identity::text,count(*),count(*) FILTER(WHERE status='succeeded'),count(*) FILTER(WHERE status='failed') FROM records WHERE `+recordFilterSQL+` GROUP BY identity`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ type QualityScope struct {
|
||||
AsOf time.Time
|
||||
}
|
||||
|
||||
func (c *Client) ReadQualityScope(ctx context.Context, query RecordQuery) (QualityScope, error) {
|
||||
func (c *RecordsRepository) ReadQualityScope(ctx context.Context, query RecordQuery) (QualityScope, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return QualityScope{}, err
|
||||
}
|
||||
@@ -23,11 +23,15 @@ func (c *Client) ReadQualityScope(ctx context.Context, query RecordQuery) (Quali
|
||||
return QualityScope{}, err
|
||||
}
|
||||
result := QualityScope{Keys: []QualityKey{}}
|
||||
err = c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&result.AsOf) != nil {
|
||||
err = c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
if c.readAsOf(ctx, q, &result.AsOf) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
rows, err := q.Query(ctx, recordsBaseSQL+` SELECT id,quality_hash,strpos(payload->>'answer',$5)>0,(payload->'source_coverage')::text FROM records WHERE `+recordFilterSQL+` ORDER BY id LIMIT 5001`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern, noPublishedMarker)
|
||||
scopeSQL := c.baseSQL + ` SELECT id,quality_hash,strpos(payload->>'answer',$5)>0,(payload->'source_coverage')::text FROM records WHERE `
|
||||
if c.qualityScopeSQL != "" {
|
||||
scopeSQL = c.qualityScopeSQL
|
||||
}
|
||||
rows, err := q.Query(ctx, scopeSQL+recordFilterSQL+` ORDER BY id LIMIT 5001`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern, noPublishedMarker)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RecordQuerier and RecordTransaction keep the projection identical while an
|
||||
// explicitly selected reader supplies either source-ACL or local-snapshot transactions.
|
||||
type RecordRow = rowScanner
|
||||
type RecordQuerier = querier
|
||||
type RecordTransaction func(context.Context, func(context.Context, RecordQuerier) error) error
|
||||
type RecordsRepositoryOptions struct {
|
||||
BaseSQL string
|
||||
SummarySQL string
|
||||
QualityScopeSQL string
|
||||
Transaction RecordTransaction
|
||||
ValidateWindow func(Window) error
|
||||
ReadAsOf func(context.Context, RecordQuerier, *time.Time) error
|
||||
TenantKey string
|
||||
}
|
||||
type RecordsRepository struct {
|
||||
baseSQL string
|
||||
summarySQL string
|
||||
qualityScopeSQL string
|
||||
transact RecordTransaction
|
||||
validateQueryWindow func(Window) error
|
||||
readAsOf func(context.Context, RecordQuerier, *time.Time) error
|
||||
tenant string
|
||||
}
|
||||
|
||||
func NewRecordsRepository(o RecordsRepositoryOptions) *RecordsRepository {
|
||||
asOf := o.ReadAsOf
|
||||
if asOf == nil {
|
||||
asOf = func(ctx context.Context, q RecordQuerier, t *time.Time) error {
|
||||
return q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(t)
|
||||
}
|
||||
}
|
||||
return &RecordsRepository{summarySQL: o.SummarySQL, qualityScopeSQL: o.QualityScopeSQL, baseSQL: o.BaseSQL, transact: o.Transaction, validateQueryWindow: o.ValidateWindow, readAsOf: asOf, tenant: o.TenantKey}
|
||||
}
|
||||
func (c *Client) recordRepository() *RecordsRepository {
|
||||
return NewRecordsRepository(RecordsRepositoryOptions{BaseSQL: recordsBaseSQL, Transaction: c.withReadOnlyTx, ValidateWindow: c.validateQueryWindow})
|
||||
}
|
||||
func (c *Client) ListRecords(ctx context.Context, q RecordQuery) (RecordPage, error) {
|
||||
return c.recordRepository().ListRecords(ctx, q)
|
||||
}
|
||||
func (c *Client) GetRecord(ctx context.Context, tenant, id string) (Record, error) {
|
||||
return c.recordRepository().GetRecord(ctx, tenant, id)
|
||||
}
|
||||
func (c *Client) ReadUsageGroups(ctx context.Context, q RecordQuery) (UsageGroups, error) {
|
||||
return c.recordRepository().ReadUsageGroups(ctx, q)
|
||||
}
|
||||
func (c *Client) ReadQualityScope(ctx context.Context, q RecordQuery) (QualityScope, error) {
|
||||
return c.recordRepository().ReadQualityScope(ctx, q)
|
||||
}
|
||||
|
||||
// DecodeMirrorPayload accepts only the source adapter's fixed safe projection;
|
||||
// credentials and arbitrary source tables are never part of this protocol.
|
||||
func DecodeMirrorPayload(raw string) (Record, error) { return decodeRecord(raw) }
|
||||
@@ -54,6 +54,8 @@ type RecordFeedback struct {
|
||||
}
|
||||
|
||||
type Record struct {
|
||||
RecordOrigin string `json:"record_origin,omitempty"`
|
||||
MasterFields map[string]string `json:"master_fields,omitempty"`
|
||||
QualityObservedAt time.Time `json:"-"`
|
||||
QualityInputHash string `json:"-"`
|
||||
Quality json.RawMessage `json:"quality,omitempty"`
|
||||
@@ -91,15 +93,16 @@ type QualityKey struct {
|
||||
InputHash string `json:"input_hash"`
|
||||
}
|
||||
type RecordPage struct {
|
||||
ScopeQuality []QualityKey `json:"-"`
|
||||
ScopeActors []ActorIdentity `json:"-"`
|
||||
Organization *OrganizationVersion `json:"organization,omitempty"`
|
||||
Items []Record `json:"items"`
|
||||
Columns []string `json:"columns"`
|
||||
Total int64 `json:"total"`
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor string `json:"next_cursor"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
LocalRevision int64 `json:"local_revision,omitempty"`
|
||||
ScopeQuality []QualityKey `json:"-"`
|
||||
ScopeActors []ActorIdentity `json:"-"`
|
||||
Organization *OrganizationVersion `json:"organization,omitempty"`
|
||||
Items []Record `json:"items"`
|
||||
Columns []string `json:"columns"`
|
||||
Total int64 `json:"total"`
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor string `json:"next_cursor"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
}
|
||||
|
||||
type recordCursor struct {
|
||||
@@ -172,7 +175,7 @@ func recordKeywordPattern(keyword string) (string, error) {
|
||||
return "%" + strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(keyword) + "%", nil
|
||||
}
|
||||
|
||||
func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage, error) {
|
||||
func (c *RecordsRepository) ListRecords(ctx context.Context, query RecordQuery) (RecordPage, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return RecordPage{}, err
|
||||
}
|
||||
@@ -197,12 +200,16 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage
|
||||
}
|
||||
args := []any{query.Window.TenantKey, query.Window.Start, query.Window.End, pattern}
|
||||
page := RecordPage{Items: make([]Record, 0), Columns: make([]string, 0)}
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if err := q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&page.AsOf); err != nil {
|
||||
err := c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
if err := c.readAsOf(ctx, q, &page.AsOf); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
var rawColumns, rawActors, rawQuality string
|
||||
if err := q.QueryRow(ctx, recordsBaseSQL+recordColumnsSQL+recordFilterSQL, append(args, noPublishedMarker)...).Scan(&page.Total, &rawColumns, &rawActors, &rawQuality); err != nil {
|
||||
summarySQL := c.baseSQL + recordColumnsSQL
|
||||
if c.summarySQL != "" {
|
||||
summarySQL = c.summarySQL
|
||||
}
|
||||
if err := q.QueryRow(ctx, summarySQL+recordFilterSQL, append(args, noPublishedMarker)...).Scan(&page.Total, &rawColumns, &rawActors, &rawQuality); err != nil {
|
||||
return fmt.Errorf("%w: record count failed", ErrUnavailable)
|
||||
}
|
||||
if json.Unmarshal([]byte(rawQuality), &page.ScopeQuality) != nil {
|
||||
@@ -223,7 +230,7 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage
|
||||
page.Columns = append(page.Columns, column)
|
||||
}
|
||||
}
|
||||
rows, err := q.Query(ctx, recordsBaseSQL+` SELECT payload::text FROM records WHERE `+recordFilterSQL+`
|
||||
rows, err := q.Query(ctx, c.baseSQL+` SELECT payload::text FROM records WHERE `+recordFilterSQL+`
|
||||
AND ($5::timestamptz IS NULL OR (asked_at,id)<($5,$6)) ORDER BY asked_at DESC,id DESC LIMIT $7`, append(args, before, cursor.ID, query.Limit+1)...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: record list failed", ErrUnavailable)
|
||||
@@ -259,14 +266,14 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetRecord(ctx context.Context, tenantKey, id string) (Record, error) {
|
||||
if strings.TrimSpace(tenantKey) == "" || id == "" || len(id) > 256 || strings.ContainsRune(id, 0) {
|
||||
func (c *RecordsRepository) GetRecord(ctx context.Context, tenantKey, id string) (Record, error) {
|
||||
if strings.TrimSpace(tenantKey) == "" || (c.tenant != "" && tenantKey != c.tenant) || id == "" || len(id) > 256 || strings.ContainsRune(id, 0) {
|
||||
return Record{}, ErrInvalidQuery
|
||||
}
|
||||
var item Record
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
err := c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
var raw string
|
||||
err := q.QueryRow(ctx, recordsBaseSQL+` SELECT payload::text FROM records WHERE id=$2`, tenantKey, id).Scan(&raw)
|
||||
err := q.QueryRow(ctx, c.baseSQL+` SELECT payload::text FROM records WHERE id=$2`, tenantKey, id).Scan(&raw)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrRecordNotFound
|
||||
}
|
||||
|
||||
@@ -6,6 +6,12 @@ import (
|
||||
|
||||
// Development headings cannot replace the formal release baseline.
|
||||
func ExtractDevelopmentNotes(changelog, version string) string {
|
||||
return developmentNotes(changelog, version, "")
|
||||
}
|
||||
func ExtractDevelopmentNotesForCommit(changelog, version, sha string) string {
|
||||
return developmentNotes(changelog, version, sha)
|
||||
}
|
||||
func developmentNotes(changelog, version, sha string) string {
|
||||
if !SemverValid(version) {
|
||||
return ""
|
||||
}
|
||||
@@ -20,7 +26,15 @@ func ExtractDevelopmentNotes(changelog, version string) string {
|
||||
break
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(strings.Join(lines[i+1:end], "\n"))
|
||||
body := strings.TrimSpace(strings.Join(lines[i+1:end], "\n"))
|
||||
if sha == "" {
|
||||
return body
|
||||
}
|
||||
for _, field := range lines[i+1 : end] {
|
||||
if strings.TrimSpace(field) == "目标提交:"+sha {
|
||||
return body
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
|
||||
@@ -31,7 +31,7 @@ func recordAttribution(ctx context.Context, config Config) (*qaopsorg.Attributio
|
||||
return p, nil
|
||||
}
|
||||
func attributionVersion(p *qaopsorg.Attribution) dobotaiops.OrganizationVersion {
|
||||
return dobotaiops.OrganizationVersion{State: p.Metadata.State, DirectoryID: p.Metadata.DirectoryID, DirectorySource: p.Metadata.DirectorySource, SyncedAt: p.Metadata.DirectorySyncedAt, RevisionID: p.Metadata.RevisionID, Basis: "current_directory"}
|
||||
return dobotaiops.OrganizationVersion{State: p.Metadata.State, DirectoryID: p.Metadata.DirectoryID, DirectorySource: p.Metadata.DirectorySource, SyncedAt: p.Metadata.DirectorySyncedAt, RevisionID: p.Metadata.RevisionID, Basis: "current_directory", RegionNames: p.Metadata.RegionLabels()}
|
||||
}
|
||||
func enrichQARecord(item *dobotaiops.Record, p *qaopsorg.Attribution) {
|
||||
person := p.Resolve(item.Identity.StaffID, item.Identity.UnionID)
|
||||
@@ -92,7 +92,7 @@ type qaUsage struct {
|
||||
|
||||
func summarizeQAUsage(groups dobotaiops.UsageGroups, p *qaopsorg.Attribution, query dobotaiops.RecordQuery) qaUsage {
|
||||
result := qaUsage{Organization: attributionVersion(p), AsOf: groups.AsOf, Start: query.Window.Start, End: query.Window.End, Keyword: query.Keyword, Rows: []qaUsageRow{}}
|
||||
keys := append(append([]string{}, qaopsorg.RegionNames...), "unassigned", "cross_region", "unmatched", "identity_conflict", "no_identity", "directory_missing")
|
||||
keys := append(append([]string{}, p.Metadata.RegionLabels()...), "unassigned", "cross_region", "unmatched", "identity_conflict", "no_identity", "directory_missing")
|
||||
rows := map[string]*qaUsageRow{}
|
||||
members := map[string]map[string]bool{}
|
||||
all := map[string]bool{}
|
||||
@@ -108,7 +108,12 @@ func summarizeQAUsage(groups dobotaiops.UsageGroups, p *qaopsorg.Attribution, qu
|
||||
n = p.Metadata.View.ConflictingPeople
|
||||
default:
|
||||
var ok bool
|
||||
n, ok = p.Metadata.View.Regions[key]
|
||||
for _, region := range p.Metadata.RegionDefinitions() {
|
||||
if region.Name == key {
|
||||
n, ok = p.Metadata.View.Regions[region.ID]
|
||||
break
|
||||
}
|
||||
}
|
||||
valid = ok
|
||||
}
|
||||
if valid {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type qaDashboardReader interface {
|
||||
ReadDashboard(context.Context, dobotaiops.RecordQuery) (qaopsmirror.Dashboard, error)
|
||||
}
|
||||
|
||||
func qaOperationsDashboard(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-dashboard") {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
Keyword string `json:"keyword"`
|
||||
}
|
||||
if decodeQualityJSON(w, r, &request, "start", "end") != nil {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
reader, ok := c.QAOps.(qaDashboardReader)
|
||||
if !ok || c.QAOpsTenantKey == "" {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
window, e := dobotaiops.NewWindow(c.QAOpsTenantKey, request.Start, request.End, 90*24*time.Hour, c.Now())
|
||||
if e != nil {
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
dashboard, e := reader.ReadDashboard(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword})
|
||||
if e != nil {
|
||||
if errors.Is(e, qaopsquality.ErrConflict) {
|
||||
writeQualityError(w, e)
|
||||
return
|
||||
}
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": dashboard})
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type dashboardReaderSpy struct {
|
||||
attributedReader
|
||||
calls int
|
||||
query dobotaiops.RecordQuery
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *dashboardReaderSpy) ReadDashboard(_ context.Context, q dobotaiops.RecordQuery) (qaopsmirror.Dashboard, error) {
|
||||
s.calls++
|
||||
s.query = q
|
||||
return qaopsmirror.Dashboard{TotalIssues: 7, NewThisWeek: 2}, s.err
|
||||
}
|
||||
func TestQADashboardIsFixedTenantAdminAndReadOnly(t *testing.T) {
|
||||
reader := &dashboardReaderSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["dash-admin"] = "usr-boss"
|
||||
auth.sessions["dash-viewer"] = "usr-eye"
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, QAOps: reader, QAOpsTenantKey: "fixed-dashboard-tenant", Now: func() time.Time { return time.Date(2026, 10, 18, 12, 0, 0, 0, time.UTC) }, Auth: &AuthConfig{Store: auth}})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
good := `{"start":"2026-10-05T00:00:00+08:00","end":"2026-10-12T00:00:00+08:00","keyword":"100%_"}`
|
||||
for _, c := range []struct {
|
||||
token, action, origin, body string
|
||||
status int
|
||||
}{
|
||||
{"", "qa-dashboard", "", good, 401}, {"dash-viewer", "qa-dashboard", "", good, 403}, {"dash-admin", "", "", good, 403}, {"dash-admin", "qa-dashboard", "https://untrusted.invalid", good, 403},
|
||||
{"dash-admin", "qa-dashboard", "", `null`, 400}, {"dash-admin", "qa-dashboard", "", `{"start":null,"end":"2026-10-12T00:00:00+08:00"}`, 400},
|
||||
{"dash-admin", "qa-dashboard", "", `{"tenant":"other","start":"2026-10-05T00:00:00+08:00","end":"2026-10-12T00:00:00+08:00"}`, 400},
|
||||
{"dash-admin", "qa-dashboard", "", good, 200},
|
||||
} {
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/qa-ops/dashboard", strings.NewReader(c.body))
|
||||
if c.token != "" {
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: c.token})
|
||||
}
|
||||
r.Header.Set("X-Governance-Action", c.action)
|
||||
r.Header.Set("Origin", c.origin)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != c.status {
|
||||
t.Fatalf("dashboard status=%d want=%d", w.Code, c.status)
|
||||
}
|
||||
if w.Code == 200 && w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("private dashboard response may be cached")
|
||||
}
|
||||
}
|
||||
if reader.calls != 1 || reader.query.Window.TenantKey != "fixed-dashboard-tenant" || reader.query.Keyword != "100%_" {
|
||||
t.Fatal("rejected requests reached the reader or browser controlled the tenant")
|
||||
}
|
||||
reader.err = qaopsquality.ErrConflict
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/qa-ops/dashboard", strings.NewReader(good))
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "dash-admin"})
|
||||
r.Header.Set("X-Governance-Action", "qa-dashboard")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("quality input drift status=%d want409", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
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/") {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Pragma", "no-cache")
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// Master reads and reviews own their state; no source client is accepted as fallback.
|
||||
type qaMasterStore interface {
|
||||
ListMasterRecords(context.Context, dobotaiops.RecordQuery) (dobotaiops.RecordPage, error)
|
||||
GetMasterRecord(context.Context, string, string) (dobotaiops.Record, error)
|
||||
ReadMasterQualityScope(context.Context, dobotaiops.RecordQuery) (dobotaiops.QualityScope, error)
|
||||
MasterQualityStore() *qaopsquality.Store
|
||||
}
|
||||
type qaMasterReader struct {
|
||||
QAOpsReader
|
||||
master qaMasterStore
|
||||
}
|
||||
|
||||
func (s qaMasterReader) ListRecords(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
return s.master.ListMasterRecords(ctx, q)
|
||||
}
|
||||
func (s qaMasterReader) GetRecord(ctx context.Context, tenant, id string) (dobotaiops.Record, error) {
|
||||
return s.master.GetMasterRecord(ctx, tenant, id)
|
||||
}
|
||||
func (s qaMasterReader) ReadQualityScope(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.QualityScope, error) {
|
||||
return s.master.ReadMasterQualityScope(ctx, q)
|
||||
}
|
||||
func (s qaMasterReader) ReadStoredQuality(ctx context.Context, keys []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
|
||||
return s.master.MasterQualityStore().ReadViews(ctx, keys)
|
||||
}
|
||||
func withQAMaster(w http.ResponseWriter, r *http.Request, c Config, handler func(http.ResponseWriter, *http.Request, Config)) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
master, ok := c.QAOps.(qaMasterStore)
|
||||
if !ok {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
c.QAOps = qaMasterReader{QAOpsReader: c.QAOps, master: master}
|
||||
c.QAQuality = master.MasterQualityStore()
|
||||
if master.MasterQualityStore() == nil {
|
||||
c.QAQuality = nil
|
||||
}
|
||||
handler(w, r, c)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type masterFixtureReader struct {
|
||||
calls int
|
||||
tenant string
|
||||
}
|
||||
|
||||
func (f *masterFixtureReader) ListRecords(context.Context, dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
panic("master must never fall back to replaceable mirror/source reads")
|
||||
}
|
||||
func (f *masterFixtureReader) GetRecord(context.Context, string, string) (dobotaiops.Record, error) {
|
||||
panic("master must never fetch the production source")
|
||||
}
|
||||
func (f *masterFixtureReader) Available(context.Context) error { return nil }
|
||||
func (f *masterFixtureReader) Safety() dobotaiops.SourceSafety { return dobotaiops.SourceSafety{} }
|
||||
func (f *masterFixtureReader) MasterQualityStore() *qaopsquality.Store { return nil }
|
||||
func (f *masterFixtureReader) ListMasterRecords(_ context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
f.calls++
|
||||
f.tenant = q.Window.TenantKey
|
||||
return dobotaiops.RecordPage{Items: []dobotaiops.Record{}, Columns: []string{"question"}, AsOf: time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC), LocalRevision: 3}, nil
|
||||
}
|
||||
func (f *masterFixtureReader) GetMasterRecord(_ context.Context, tenant, id string) (dobotaiops.Record, error) {
|
||||
f.calls++
|
||||
f.tenant = tenant
|
||||
return dobotaiops.Record{ID: id, Question: "fixture master"}, nil
|
||||
}
|
||||
func (f *masterFixtureReader) ReadMasterQualityScope(context.Context, dobotaiops.RecordQuery) (dobotaiops.QualityScope, error) {
|
||||
return dobotaiops.QualityScope{}, nil
|
||||
}
|
||||
func TestQAMasterUsesFixedTenantAndNeverSourceFallback(t *testing.T) {
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["fixture-master-admin"] = "usr-boss"
|
||||
reader := &masterFixtureReader{}
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: reader, QAOpsTenantKey: "fixed-master-tenant", Now: func() time.Time { return time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC) }})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
base := "/api/v1/qa-ops/master/records"
|
||||
for _, c := range []struct {
|
||||
path string
|
||||
cookie bool
|
||||
status int
|
||||
}{{base + "?start=2026-10-05T00:00:00Z&end=2026-10-12T00:00:00Z", true, 200}, {base + "/fixture-id", true, 200}, {base + "?tenant=other", true, 400}, {base, false, 401}} {
|
||||
r := httptest.NewRequest(http.MethodGet, c.path, nil)
|
||||
if c.cookie {
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "fixture-master-admin"})
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != c.status {
|
||||
t.Fatalf("master route %s: got %d, wanted %d", c.path, w.Code, c.status)
|
||||
}
|
||||
if w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("master employee data was cacheable")
|
||||
}
|
||||
}
|
||||
if reader.calls != 2 || reader.tenant != "fixed-master-tenant" {
|
||||
t.Fatal("master fixed-tenant read path missing")
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodPost, base+"/fixture-id/reviews", strings.NewReader(`{}`))
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "fixture-master-admin"})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 403 {
|
||||
t.Fatal("master review lacked explicit same-origin intent gate", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type mirroredQualitySource struct {
|
||||
qualitySource
|
||||
reads int
|
||||
}
|
||||
|
||||
func (s *mirroredQualitySource) ReadStoredQuality(_ context.Context, keys []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
|
||||
s.reads++
|
||||
out := map[string]qaopsquality.View{}
|
||||
for _, key := range keys {
|
||||
out[key.ID] = qaopsquality.Project(key.InputHash, 1, 0, qaopsquality.Check{Result: dobotaiops.CheckMarkerCoverage(true)}, nil)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func TestMirroredQualityQueriesDoNotRepeatObservationWrites(t *testing.T) {
|
||||
source := &mirroredQualitySource{qualitySource: qualitySource{record: dobotaiops.Record{ID: "fixture-turn", Question: "fixture", Answer: "暂无已发布"}}}
|
||||
e, _ := qaopsquality.EvidenceFor(source.record)
|
||||
source.record.QualityInputHash = e.Hash
|
||||
legacy := &qualityFake{fail: true}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["quality-admin"] = "usr-boss"
|
||||
h, e2 := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: source, QAOpsTenantKey: "fixed", QAQuality: legacy, Now: func() time.Time { return time.Date(2026, 10, 17, 0, 0, 0, 0, time.UTC) }})
|
||||
if e2 != nil {
|
||||
t.Fatal(e2)
|
||||
}
|
||||
for _, q := range []struct{ method, path, body string }{{"GET", "/api/v1/qa-ops/records/fixture-turn", ""}, {"GET", "/api/v1/qa-ops/records?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z", ""}, {"POST", "/api/v1/qa-ops/quality/query", `{"start":"2026-10-14T00:00:00Z","end":"2026-10-15T00:00:00Z","keyword":""}`}} {
|
||||
w := qualityRequest(h, q.method, q.path, "quality-admin", q.body)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatal("local mirror read went back through observation writes", q.path, w.Code)
|
||||
}
|
||||
}
|
||||
if source.reads != 3 || legacy.calls != 0 {
|
||||
t.Fatal("batched stored projection not used", source.reads, legacy.calls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type qaMirrorSyncStore interface {
|
||||
GetSyncStatus(context.Context) (qaopsmirror.Status, error)
|
||||
EnqueueSync(context.Context, string, string) (qaopsmirror.SyncReceipt, bool, error)
|
||||
}
|
||||
|
||||
func qaRecordsSync(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if r.URL.RawQuery != "" {
|
||||
writeJSON(w, 400, map[string]string{"error": "同步入口不接受查询参数"})
|
||||
return
|
||||
}
|
||||
store, ok := c.QAOps.(qaMirrorSyncStore)
|
||||
if !ok || !c.QAOpsEnabled {
|
||||
writeJSON(w, 503, map[string]string{"error": "本地问答同步未接线,未创建任务"})
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodGet {
|
||||
state, e := store.GetSyncStatus(r.Context())
|
||||
if e != nil {
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": state})
|
||||
return
|
||||
}
|
||||
if !authorizeQAIntent(w, r, "qa-records-sync") {
|
||||
return
|
||||
}
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
if key == "" || len(key) > 128 || strings.TrimSpace(key) != key {
|
||||
writeJSON(w, 400, map[string]string{"error": "同步请求需要有效 Idempotency-Key,重试须复用原标识"})
|
||||
return
|
||||
}
|
||||
var body *struct{}
|
||||
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(&body) != nil || body == nil || d.Decode(&struct{}{}) != io.EOF {
|
||||
writeJSON(w, 400, map[string]string{"error": "同步请求体必须是空对象"})
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
receipt, replayed, e := store.EnqueueSync(r.Context(), key, identity.Username)
|
||||
if e != nil {
|
||||
status := 503
|
||||
message := "同步未成功入队,已有本地数据保持不变"
|
||||
if errors.Is(e, qaopsmirror.ErrInvalid) {
|
||||
status = 400
|
||||
message = "同步请求标识无效"
|
||||
}
|
||||
if errors.Is(e, qaopsmirror.ErrConflict) {
|
||||
status = 409
|
||||
message = "同步标识已用于另一操作,请重新发起"
|
||||
}
|
||||
if errors.Is(e, qaopsmirror.ErrWorkerUnavailable) {
|
||||
message = "问答同步执行器未在线,未创建任务"
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": message})
|
||||
return
|
||||
}
|
||||
operation := "created"
|
||||
if replayed {
|
||||
operation = "replayed"
|
||||
}
|
||||
writeJSON(w, 202, map[string]any{"data": receipt, "operation": operation})
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type mirrorSyncSpy struct {
|
||||
qaOpsSpy
|
||||
syncCalls int
|
||||
key, actor string
|
||||
}
|
||||
|
||||
func (s *mirrorSyncSpy) GetSyncStatus(context.Context) (qaopsmirror.Status, error) {
|
||||
return qaopsmirror.Status{Mode: "local", IntervalSeconds: 300, WorkerReady: true}, nil
|
||||
}
|
||||
func (s *mirrorSyncSpy) EnqueueSync(_ context.Context, key, actor string) (qaopsmirror.SyncReceipt, bool, error) {
|
||||
s.syncCalls++
|
||||
s.key = key
|
||||
s.actor = actor
|
||||
return qaopsmirror.SyncReceipt{JobID: "fixture-mirror-job"}, false, nil
|
||||
}
|
||||
func TestQAMirrorSyncRequiresSessionIntentAndIdempotency(t *testing.T) {
|
||||
spy := &mirrorSyncSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["mirror-admin"] = "usr-boss"
|
||||
auth.sessions["mirror-viewer"] = "usr-eye"
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, QAOps: spy, QAOpsEnabled: true, QAOpsTenantKey: "fixture-tenant", Auth: &AuthConfig{Store: auth}})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
method, token, key, intent, origin, body string
|
||||
status int
|
||||
}{
|
||||
{"GET", "", "", "", "", "", 401}, {"GET", "mirror-viewer", "", "", "", "", 403}, {"GET", "mirror-admin", "", "", "", "", 200},
|
||||
{"POST", "mirror-admin", "op-one", "", "", "{}", 403}, {"POST", "mirror-admin", "op-one", "qa-records-sync", "https://foreign.invalid", "{}", 403},
|
||||
{"POST", "mirror-admin", "", "qa-records-sync", "", "{}", 400}, {"POST", "mirror-admin", "op-one", "qa-records-sync", "", "null", 400},
|
||||
{"POST", "mirror-admin", "op-one", "qa-records-sync", "", `{"tenant":"forged"}`, 400}, {"POST", "mirror-admin", "op-one", "qa-records-sync", "", "{}", 202},
|
||||
} {
|
||||
req := httptest.NewRequest(tc.method, "/api/v1/qa-ops/sync", strings.NewReader(tc.body))
|
||||
if tc.token != "" {
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: tc.token})
|
||||
}
|
||||
req.Header.Set("Idempotency-Key", tc.key)
|
||||
req.Header.Set("X-Governance-Action", tc.intent)
|
||||
req.Header.Set("Origin", tc.origin)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != tc.status {
|
||||
t.Fatalf("%s %s got %d want %d: %s", tc.method, tc.body, w.Code, tc.status, w.Body.String())
|
||||
}
|
||||
}
|
||||
if spy.syncCalls != 1 || spy.key != "op-one" || spy.actor == "" {
|
||||
t.Fatal("invalid sync reached store or operator was not session-stamped")
|
||||
}
|
||||
req := httptest.NewRequest("GET", "/api/v1/qa-ops/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "mirror-admin"})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
var body struct {
|
||||
Data struct {
|
||||
Cache *qaopsmirror.Status `json:"cache"`
|
||||
}
|
||||
}
|
||||
if json.Unmarshal(w.Body.Bytes(), &body) != nil || body.Data.Cache == nil || body.Data.Cache.Mode != "local" {
|
||||
t.Fatal("local serving mode missing from status")
|
||||
}
|
||||
}
|
||||
func TestQAMirrorSyncNamespaceCannotBypassEntry(t *testing.T) {
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["mirror-admin"] = "usr-boss"
|
||||
h, _ := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}})
|
||||
req := httptest.NewRequest("POST", "/api/v1/jobs", strings.NewReader(`{"type":"qaops.records.sync.fixture","payload":{},"idempotency_key":"bypass"}`))
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "mirror-admin"})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != 400 {
|
||||
t.Fatal("generic jobs endpoint bypassed mirror sync admission", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -97,11 +97,7 @@ func parseMonthlyFilter(values url.Values, now time.Time) (monthlyFilter, error)
|
||||
if f.Activity != "all" && f.Activity != "used" && f.Activity != "zero" {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
validRegion := f.Region == "" || f.Region == "unassigned" || f.Region == "cross_region"
|
||||
for _, r := range qaopsorg.RegionNames {
|
||||
validRegion = validRegion || f.Region == r
|
||||
}
|
||||
if !validRegion {
|
||||
if !utf8.ValidString(f.Region) || len(f.Region) > 256 || strings.TrimSpace(f.Region) != f.Region || strings.ContainsAny(f.Region, "\x00\r\n") {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
if !utf8.ValidString(f.Search) || utf8.RuneCountInString(f.Search) > 100 || strings.ContainsRune(f.Search, 0) {
|
||||
@@ -288,6 +284,16 @@ func qaMonthlyPeople(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if f.Region != "" && f.Region != "unassigned" && f.Region != "cross_region" {
|
||||
found := false
|
||||
for _, name := range p.Metadata.RegionLabels() {
|
||||
found = found || f.Region == name
|
||||
}
|
||||
if !found {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
}
|
||||
if f.Department != "" {
|
||||
found := false
|
||||
for _, d := range p.Metadata.View.Departments {
|
||||
|
||||
@@ -61,7 +61,16 @@ func qaOpsStatus(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
warnings = append(warnings, "database_transport_unencrypted")
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"state": state, "code": code, "warnings": warnings, "read_only": true, "source_version": "2.0", "channel": "dingtalk"}})
|
||||
data := map[string]any{"state": state, "code": code, "warnings": warnings, "read_only": true, "source_version": "2.0", "channel": "dingtalk"}
|
||||
if mirror, ok := config.QAOps.(qaMirrorSyncStore); ok {
|
||||
cache, err := mirror.GetSyncStatus(r.Context())
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
data["cache"] = cache
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": data})
|
||||
}
|
||||
|
||||
func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
@@ -144,7 +153,7 @@ func getQAOpsRecord(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
func qaOpsError(w http.ResponseWriter, err error) {
|
||||
status := http.StatusServiceUnavailable
|
||||
code := "source_unavailable"
|
||||
message := "问答数据源不可用,请检查独立只读连接;原有知识治理功能不受影响"
|
||||
message := "问答记录当前不可用;本地模式请检查同步状态,原有知识治理功能不受影响"
|
||||
if errors.Is(err, errQAOrganization) {
|
||||
code = "organization_unavailable"
|
||||
message = "通讯录或区域配置读取失败,未将不可用数据伪装成空列,请重试"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -36,9 +37,14 @@ func qaOrganization(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
var request qaopsorg.SaveRequest
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
|
||||
raw, readErr := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
|
||||
check := json.NewDecoder(bytes.NewReader(raw))
|
||||
var fields map[string]json.RawMessage
|
||||
var extra any
|
||||
invalidJSON := readErr != nil || json.Unmarshal(raw, &fields) != nil || fields == nil || fields["base_revision"] == nil || walkQualityJSON(check) != nil || check.Decode(&extra) != io.EOF
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&request) != nil || decoder.Decode(&struct{}{}) != io.EOF || request.DirectoryID == "" || request.Rules == nil {
|
||||
if invalidJSON || decoder.Decode(&request) != nil || decoder.Decode(&extra) != io.EOF || request.DirectoryID == "" || request.Rules == nil {
|
||||
writeOrgError(w, qaopsorg.ErrInvalid)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -52,6 +52,12 @@ func TestQAOrganizationGuardsIdentityIntentAndErrors(t *testing.T) {
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{} {}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":null}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","regions":null,"rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","regions":[null],"rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","regions":[{"id":"edu","name":null}],"rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":[],"rules":[]}`, 400},
|
||||
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":[]}`, 200},
|
||||
{"POST", base + "/preview", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":[]}`, 200},
|
||||
} {
|
||||
|
||||
@@ -22,6 +22,21 @@ type QAQualityStore interface {
|
||||
Snapshot(context.Context, string, int64) (qaopsquality.Snapshot, error)
|
||||
}
|
||||
|
||||
type storedQAQualityReader interface {
|
||||
ReadStoredQuality(context.Context, []dobotaiops.QualityKey) (map[string]qaopsquality.View, error)
|
||||
}
|
||||
|
||||
func qaQualityViews(ctx context.Context, c Config, records []dobotaiops.Record) (map[string]qaopsquality.View, error) {
|
||||
if reader, ok := c.QAOps.(storedQAQualityReader); ok {
|
||||
keys := make([]dobotaiops.QualityKey, 0, len(records))
|
||||
for _, r := range records {
|
||||
keys = append(keys, dobotaiops.QualityKey{ID: r.ID, InputHash: r.QualityInputHash})
|
||||
}
|
||||
return reader.ReadStoredQuality(ctx, keys)
|
||||
}
|
||||
return c.QAQuality.Observe(ctx, records)
|
||||
}
|
||||
|
||||
type qaQualityReader interface {
|
||||
ReadQualityScope(context.Context, dobotaiops.RecordQuery) (dobotaiops.QualityScope, error)
|
||||
}
|
||||
@@ -44,7 +59,7 @@ func enrichQAQualityRecord(ctx context.Context, c Config, item *dobotaiops.Recor
|
||||
if c.QAQuality == nil {
|
||||
return nil
|
||||
}
|
||||
views, err := c.QAQuality.Observe(ctx, []dobotaiops.Record{*item})
|
||||
views, err := qaQualityViews(ctx, c, []dobotaiops.Record{*item})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -59,7 +74,7 @@ func enrichQAQualityPage(ctx context.Context, c Config, page *dobotaiops.RecordP
|
||||
if c.QAQuality == nil {
|
||||
return nil
|
||||
}
|
||||
views, err := c.QAQuality.Observe(ctx, page.Items)
|
||||
views, err := qaQualityViews(ctx, c, page.Items)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -197,7 +212,12 @@ func qaQualityQuery(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
views, err := c.QAQuality.ObserveKeys(r.Context(), scope.Keys)
|
||||
var views map[string]qaopsquality.View
|
||||
if stored, ok := c.QAOps.(storedQAQualityReader); ok {
|
||||
views, err = stored.ReadStoredQuality(r.Context(), scope.Keys)
|
||||
} else {
|
||||
views, err = c.QAQuality.ObserveKeys(r.Context(), scope.Keys)
|
||||
}
|
||||
if err != nil || len(views) != len(scope.Keys) {
|
||||
if err == nil {
|
||||
err = qaopsquality.ErrUnavailable
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestQAUsageConsumesTheCustomRegionCatalog(t *testing.T) {
|
||||
p, err := qaopsorg.BuildAttribution(qaopsorg.State{State: "ready", DirectoryID: "fixture-directory", Regions: []qaopsorg.RegionDefinition{{ID: "edu", Name: "国内教育"}}, Rules: []qaopsorg.Rule{{DepartmentID: "a", Region: "edu"}}}, qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "a", Name: "示例部门"}}, People: []qaopsorg.Person{{ID: "fixture-person", DepartmentIDs: []string{"a"}}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
usage := summarizeQAUsage(dobotaiops.UsageGroups{Groups: []dobotaiops.UsageGroup{{Identity: dobotaiops.ActorIdentity{StaffID: "fixture-person"}, Total: 3, Succeeded: 2, Failed: 1}}}, p, dobotaiops.RecordQuery{})
|
||||
if usage.Questions != 3 || usage.IdentifiedUsers != 1 {
|
||||
t.Fatal("the historical whitelist dropped custom-region events")
|
||||
}
|
||||
found := false
|
||||
for _, row := range usage.Rows {
|
||||
if row.Key == "国内教育" {
|
||||
found = true
|
||||
if row.Questions != 3 || row.RosterPeople == nil || *row.RosterPeople != 1 || row.Users == nil || *row.Users != 1 {
|
||||
t.Fatal("custom-region counts or roster denominator were lost")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("custom-region row missing")
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
)
|
||||
|
||||
@@ -176,6 +177,7 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
config.NewID = newID
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
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) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/records/{id}/quality/history", func(w http.ResponseWriter, r *http.Request) { qaQualityHistory(w, r, config) })
|
||||
@@ -188,9 +190,17 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/organization", func(w http.ResponseWriter, r *http.Request) { qaOrganization(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/organization/preview", func(w http.ResponseWriter, r *http.Request) { qaOrganization(w, r, config) })
|
||||
mux.HandleFunc("PUT /api/v1/qa-ops/organization/regions", func(w http.ResponseWriter, r *http.Request) { qaOrganization(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/sync", func(w http.ResponseWriter, r *http.Request) { qaRecordsSync(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/sync", func(w http.ResponseWriter, r *http.Request) { qaRecordsSync(w, r, config) })
|
||||
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/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) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/master/records/{id}/reviews", func(w http.ResponseWriter, r *http.Request) { withQAMaster(w, r, config, qaQualityReview) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/master/records/{id}/quality/history", func(w http.ResponseWriter, r *http.Request) { withQAMaster(w, r, config, qaQualityHistory) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/master/records/{id}/quality/inputs/{epoch}", func(w http.ResponseWriter, r *http.Request) { withQAMaster(w, r, config, qaQualitySnapshot) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/records", func(w http.ResponseWriter, r *http.Request) {
|
||||
listQAOpsRecords(w, r, config)
|
||||
})
|
||||
@@ -548,9 +558,9 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
}
|
||||
config.authRoutes(mux)
|
||||
config.userRoutes(mux)
|
||||
return config.Auth.authenticate(mux), nil
|
||||
return masterNoStore(config.Auth.authenticate(mux)), nil
|
||||
}
|
||||
return mux, nil
|
||||
return masterNoStore(mux), nil
|
||||
}
|
||||
|
||||
type createJobRequest struct {
|
||||
@@ -569,7 +579,7 @@ func createJob(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON request"})
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(input.Type, qaopsorg.SyncJobPrefix) {
|
||||
if strings.HasPrefix(input.Type, qaopsorg.SyncJobPrefix) || strings.HasPrefix(input.Type, qaopsmirror.SyncJobPrefix) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "通讯录同步任务只能从问答运营的管理员入口创建"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
DROP TABLE qa_ops_mirror_records;
|
||||
DROP TABLE qa_ops_mirror_state;
|
||||
@@ -0,0 +1,14 @@
|
||||
CREATE TABLE qa_ops_mirror_state (
|
||||
tenant_key TEXT PRIMARY KEY CHECK(length(tenant_key) BETWEEN 1 AND 128),
|
||||
ready BOOLEAN NOT NULL DEFAULT false, blocked BOOLEAN NOT NULL DEFAULT false,
|
||||
revision BIGINT NOT NULL DEFAULT 0 CHECK(revision>=0), record_count BIGINT NOT NULL DEFAULT 0 CHECK(record_count>=0),
|
||||
source_observed_at TIMESTAMPTZ, synced_at TIMESTAMPTZ, next_sync_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
last_error TEXT NOT NULL DEFAULT '', source_safety JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||
);
|
||||
CREATE TABLE qa_ops_mirror_records (
|
||||
tenant_key TEXT NOT NULL REFERENCES qa_ops_mirror_state(tenant_key), id TEXT NOT NULL,
|
||||
fingerprint TEXT NOT NULL CHECK(fingerprint ~ '^[a-f0-9]{64}$'), asked_at TIMESTAMPTZ NOT NULL,
|
||||
question TEXT NOT NULL, status TEXT NOT NULL, identity JSONB NOT NULL, quality_hash TEXT NOT NULL CHECK(quality_hash ~ '^[a-f0-9]{64}$'),
|
||||
payload JSONB NOT NULL CHECK(jsonb_typeof(payload)='object'), PRIMARY KEY(tenant_key,id)
|
||||
);
|
||||
CREATE INDEX idx_qa_mirror_records_window ON qa_ops_mirror_records(tenant_key,asked_at DESC,id DESC);
|
||||
@@ -0,0 +1,6 @@
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (SELECT 1 FROM qa_ops_region_revisions WHERE region_definitions <> '[{"id":"国内工业","name":"国内工业"},{"id":"APAC","name":"APAC"},{"id":"EMEA","name":"EMEA"},{"id":"America","name":"America"}]'::jsonb) THEN
|
||||
RAISE EXCEPTION 'custom region catalog exists; application rollback may keep migration 51, destructive catalog rollback refused';
|
||||
END IF;
|
||||
END $$;
|
||||
ALTER TABLE qa_ops_region_revisions DROP COLUMN region_definitions;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE qa_ops_region_revisions ADD COLUMN region_definitions JSONB NOT NULL DEFAULT '[{"id":"国内工业","name":"国内工业"},{"id":"APAC","name":"APAC"},{"id":"EMEA","name":"EMEA"},{"id":"America","name":"America"}]'::jsonb CHECK (jsonb_typeof(region_definitions)='array');
|
||||
@@ -0,0 +1,10 @@
|
||||
DO $$ BEGIN
|
||||
IF EXISTS(SELECT 1 FROM qa_ops_weekly_quality_snapshots) THEN
|
||||
RAISE EXCEPTION 'frozen weekly quality history exists; keep additive schema during application rollback';
|
||||
END IF;
|
||||
END $$;
|
||||
DROP TABLE qa_ops_weekly_quality_snapshot_records;
|
||||
DROP TABLE qa_ops_weekly_quality_snapshots;
|
||||
DROP TABLE qa_ops_weekly_quality_tracking;
|
||||
DROP FUNCTION qa_ops_require_new_weekly_quality_header();
|
||||
DROP FUNCTION qa_ops_reject_frozen_quality_mutation();
|
||||
@@ -0,0 +1,50 @@
|
||||
CREATE TABLE qa_ops_weekly_quality_tracking (
|
||||
tenant_key TEXT PRIMARY KEY CHECK(length(tenant_key) BETWEEN 1 AND 128),
|
||||
started_at TIMESTAMPTZ NOT NULL, first_data_at TIMESTAMPTZ
|
||||
);
|
||||
CREATE TABLE qa_ops_weekly_quality_snapshots (
|
||||
tenant_key TEXT NOT NULL, week_start TIMESTAMPTZ NOT NULL, week_end TIMESTAMPTZ NOT NULL,
|
||||
frozen_at TIMESTAMPTZ NOT NULL, mirror_revision BIGINT NOT NULL CHECK(mirror_revision>=0),
|
||||
source_observed_at TIMESTAMPTZ NOT NULL, policy_version TEXT NOT NULL,
|
||||
record_count INTEGER NOT NULL CHECK(record_count>=0),
|
||||
coverage_numerator INTEGER NOT NULL CHECK(coverage_numerator>=0), coverage_denominator INTEGER NOT NULL CHECK(coverage_denominator>=coverage_numerator),
|
||||
correctness_numerator INTEGER NOT NULL CHECK(correctness_numerator>=0), correctness_denominator INTEGER NOT NULL CHECK(correctness_denominator>=correctness_numerator),
|
||||
PRIMARY KEY(tenant_key,week_start), CHECK(week_end=week_start+interval '7 days'),
|
||||
CHECK(date_trunc('day',week_start AT TIME ZONE 'Asia/Shanghai')=week_start AT TIME ZONE 'Asia/Shanghai'),
|
||||
CHECK(EXTRACT(ISODOW FROM week_start AT TIME ZONE 'Asia/Shanghai')=1),
|
||||
CHECK(frozen_at>=week_end), CHECK(source_observed_at>=week_end AND source_observed_at<=frozen_at),
|
||||
CHECK(coverage_denominator<=record_count AND correctness_denominator<=record_count)
|
||||
);
|
||||
-- Frozen scalar contributions preserve the original formula under future policy
|
||||
-- changes and allow literal keyword filtering without recalculating old reviews.
|
||||
-- No answers, staff IDs, names or organization memberships are duplicated here.
|
||||
CREATE TABLE qa_ops_weekly_quality_snapshot_records (
|
||||
tenant_key TEXT NOT NULL, week_start TIMESTAMPTZ NOT NULL, record_id TEXT NOT NULL,
|
||||
question TEXT NOT NULL,
|
||||
coverage_numerator SMALLINT NOT NULL CHECK(coverage_numerator BETWEEN 0 AND 1),
|
||||
coverage_denominator SMALLINT NOT NULL CHECK(coverage_denominator BETWEEN coverage_numerator AND 1),
|
||||
correctness_numerator SMALLINT NOT NULL CHECK(correctness_numerator BETWEEN 0 AND 1),
|
||||
correctness_denominator SMALLINT NOT NULL CHECK(correctness_denominator BETWEEN correctness_numerator AND 1),
|
||||
PRIMARY KEY(tenant_key,week_start,record_id),
|
||||
FOREIGN KEY(tenant_key,week_start) REFERENCES qa_ops_weekly_quality_snapshots(tenant_key,week_start) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE FUNCTION qa_ops_reject_frozen_quality_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'committed weekly quality snapshots are immutable' USING ERRCODE='55000';
|
||||
END $$;
|
||||
CREATE TRIGGER immutable_weekly_quality_header BEFORE UPDATE OR DELETE ON qa_ops_weekly_quality_snapshots FOR EACH ROW EXECUTE FUNCTION qa_ops_reject_frozen_quality_mutation();
|
||||
CREATE TRIGGER immutable_weekly_quality_records BEFORE UPDATE OR DELETE ON qa_ops_weekly_quality_snapshot_records FOR EACH ROW EXECUTE FUNCTION qa_ops_reject_frozen_quality_mutation();
|
||||
|
||||
-- Contributions may only be inserted in the SAME transaction as their header.
|
||||
-- This rejects a later append while allowing the initial atomic CopyFrom batch.
|
||||
CREATE FUNCTION qa_ops_require_new_weekly_quality_header() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE parent_xid bigint;
|
||||
BEGIN
|
||||
SELECT xmin::text::bigint INTO parent_xid FROM qa_ops_weekly_quality_snapshots WHERE tenant_key=NEW.tenant_key AND week_start=NEW.week_start;
|
||||
IF parent_xid IS NULL OR parent_xid <> mod(pg_current_xact_id()::text::numeric,4294967296)::bigint THEN
|
||||
RAISE EXCEPTION 'cannot append to a committed weekly quality snapshot' USING ERRCODE='55000';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER append_only_new_weekly_quality BEFORE INSERT ON qa_ops_weekly_quality_snapshot_records FOR EACH ROW EXECUTE FUNCTION qa_ops_require_new_weekly_quality_header();
|
||||
@@ -0,0 +1,22 @@
|
||||
DO $$ BEGIN
|
||||
IF EXISTS(SELECT 1 FROM qa_ops_quality_reviews r JOIN qa_ops_master_records m ON r.tenant_key=m.tenant_key||'::master' AND r.record_id=m.id LEFT JOIN qa_ops_quality_reviews o ON o.tenant_key=m.tenant_key AND o.record_id=r.record_id AND o.revision=r.revision WHERE o.request_hash IS DISTINCT FROM r.request_hash) OR EXISTS(SELECT 1 FROM qa_ops_master_import_batches) OR EXISTS(SELECT 1 FROM qa_ops_master_records m LEFT JOIN qa_ops_mirror_records s ON s.tenant_key=m.tenant_key AND s.id=m.id WHERE m.origin<>'dobotai_2_0' OR s.id IS NULL OR m.payload IS DISTINCT FROM s.payload OR m.row_revision<>1) THEN
|
||||
RAISE EXCEPTION 'durable master/import/local edits exist; keep additive schema on application rollback';
|
||||
END IF;
|
||||
END $$;
|
||||
DROP TRIGGER qa_mirror_append_to_master ON qa_ops_mirror_records;
|
||||
DROP FUNCTION qa_ops_append_source_to_master();
|
||||
DELETE FROM qa_ops_quality_reviews q USING qa_ops_master_records m WHERE q.tenant_key=m.tenant_key||'::master' AND q.record_id=m.id;
|
||||
DELETE FROM qa_ops_quality_checks q USING qa_ops_master_records m WHERE q.tenant_key=m.tenant_key||'::master' AND q.record_id=m.id;
|
||||
DELETE FROM qa_ops_quality_inputs q USING qa_ops_master_records m WHERE q.tenant_key=m.tenant_key||'::master' AND q.record_id=m.id;
|
||||
DELETE FROM qa_ops_quality_records q USING qa_ops_master_records m WHERE q.tenant_key=m.tenant_key||'::master' AND q.record_id=m.id;
|
||||
DROP TABLE qa_ops_master_import_rows;
|
||||
DROP TABLE qa_ops_master_source_links;
|
||||
DROP TABLE qa_ops_master_records;
|
||||
DROP TABLE qa_ops_master_import_batches;
|
||||
DROP TABLE qa_ops_master_state;
|
||||
DROP FUNCTION qa_ops_master_protect_provenance();
|
||||
DROP FUNCTION qa_ops_master_revision();
|
||||
DROP FUNCTION qa_ops_master_observe_quality();
|
||||
DROP FUNCTION qa_ops_master_copy_source_quality(text,text);
|
||||
DROP FUNCTION qa_ops_master_event_key(timestamptz,text,text);
|
||||
DROP FUNCTION qa_ops_master_normalize(text);
|
||||
@@ -0,0 +1,119 @@
|
||||
-- A durable, locally-owned master is separate from the replaceable 2.0 mirror.
|
||||
LOCK TABLE qa_ops_mirror_records,qa_ops_quality_records,qa_ops_quality_inputs,qa_ops_quality_checks,qa_ops_quality_reviews IN SHARE ROW EXCLUSIVE MODE;
|
||||
CREATE TABLE qa_ops_master_state (
|
||||
tenant_key TEXT PRIMARY KEY, revision BIGINT NOT NULL DEFAULT 0 CHECK(revision>=0), updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE TABLE qa_ops_master_import_batches (
|
||||
tenant_key TEXT NOT NULL, id TEXT NOT NULL, source_sha256 TEXT NOT NULL CHECK(source_sha256~'^[a-f0-9]{64}$'),
|
||||
source_name TEXT NOT NULL, sheet_name TEXT NOT NULL, total_rows INTEGER NOT NULL CHECK(total_rows>=0),
|
||||
imported_rows INTEGER NOT NULL CHECK(imported_rows>=0), skipped_rows INTEGER NOT NULL CHECK(skipped_rows>=0), held_rows INTEGER NOT NULL CHECK(held_rows>=0),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY(tenant_key,id), UNIQUE(tenant_key,source_sha256,sheet_name),
|
||||
CHECK(total_rows=imported_rows+skipped_rows+held_rows)
|
||||
);
|
||||
CREATE TABLE qa_ops_master_records (
|
||||
tenant_key TEXT NOT NULL, id TEXT NOT NULL, event_key TEXT NOT NULL CHECK(event_key~'^[a-f0-9]{64}$'),
|
||||
origin TEXT NOT NULL CHECK(origin IN ('dobotai_2_0','historical_excel')),
|
||||
asked_at TIMESTAMPTZ NOT NULL, question TEXT NOT NULL, status TEXT NOT NULL, identity JSONB NOT NULL,
|
||||
quality_hash TEXT NOT NULL, payload JSONB NOT NULL CHECK(jsonb_typeof(payload)='object'),
|
||||
CHECK(payload?'id' AND jsonb_typeof(payload->'id')='string' AND payload->>'id'=id),
|
||||
original_fields JSONB NOT NULL DEFAULT '{}'::jsonb CHECK(jsonb_typeof(original_fields)='object'),
|
||||
batch_id TEXT, source_row INTEGER, row_revision BIGINT NOT NULL DEFAULT 1 CHECK(row_revision>0),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY(tenant_key,id), FOREIGN KEY(tenant_key,batch_id) REFERENCES qa_ops_master_import_batches(tenant_key,id),
|
||||
CHECK((origin='historical_excel' AND batch_id IS NOT NULL AND source_row>1) OR (origin='dobotai_2_0' AND batch_id IS NULL AND source_row IS NULL))
|
||||
);
|
||||
CREATE INDEX idx_qa_master_window ON qa_ops_master_records(tenant_key,asked_at DESC,id DESC);
|
||||
CREATE INDEX idx_qa_master_original_event ON qa_ops_master_records(tenant_key,event_key);
|
||||
CREATE TABLE qa_ops_master_source_links (
|
||||
tenant_key TEXT NOT NULL, source_kind TEXT NOT NULL, source_id TEXT NOT NULL, master_id TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY(tenant_key,source_kind,source_id),
|
||||
FOREIGN KEY(tenant_key,master_id) REFERENCES qa_ops_master_records(tenant_key,id)
|
||||
);
|
||||
CREATE TABLE qa_ops_master_import_rows (
|
||||
tenant_key TEXT NOT NULL, batch_id TEXT NOT NULL, row_number INTEGER NOT NULL CHECK(row_number>1),
|
||||
disposition TEXT NOT NULL CHECK(disposition IN ('imported','skipped_duplicate','held_missing_key')),
|
||||
original_fields JSONB NOT NULL CHECK(jsonb_typeof(original_fields)='object'), master_id TEXT,
|
||||
PRIMARY KEY(tenant_key,batch_id,row_number), FOREIGN KEY(tenant_key,batch_id) REFERENCES qa_ops_master_import_batches(tenant_key,id),
|
||||
FOREIGN KEY(tenant_key,master_id) REFERENCES qa_ops_master_records(tenant_key,id)
|
||||
);
|
||||
CREATE FUNCTION qa_ops_master_normalize(value text) RETURNS text LANGUAGE sql IMMUTABLE AS $$ SELECT btrim(replace(replace(COALESCE(value,''),E'\r\n',E'\n'),E'\r',E'\n'),chr(9)||chr(10)||chr(11)||chr(12)||chr(13)||chr(28)||chr(29)||chr(30)||chr(31)||chr(32)||chr(133)||chr(160)||chr(5760)||chr(8192)||chr(8193)||chr(8194)||chr(8195)||chr(8196)||chr(8197)||chr(8198)||chr(8199)||chr(8200)||chr(8201)||chr(8202)||chr(8232)||chr(8233)||chr(8239)||chr(8287)||chr(12288)) $$;
|
||||
CREATE FUNCTION qa_ops_master_event_key(at_time timestamptz,person text,original_question text) RETURNS text LANGUAGE sql STABLE AS $$
|
||||
SELECT encode(sha256(convert_to(jsonb_build_array(to_char(at_time AT TIME ZONE 'Asia/Shanghai','YYYY-MM-DD HH24:MI:SS'),qa_ops_master_normalize(person),qa_ops_master_normalize(original_question))::text,'UTF8')),'hex')
|
||||
$$;
|
||||
CREATE FUNCTION qa_ops_master_revision() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
INSERT INTO qa_ops_master_state(tenant_key,revision) VALUES(NEW.tenant_key,1) ON CONFLICT(tenant_key) DO UPDATE SET revision=qa_ops_master_state.revision+1,updated_at=clock_timestamp();
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER qa_master_revision AFTER INSERT OR UPDATE ON qa_ops_master_records FOR EACH ROW EXECUTE FUNCTION qa_ops_master_revision();
|
||||
CREATE FUNCTION qa_ops_master_protect_provenance() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF ROW(NEW.tenant_key,NEW.id,NEW.event_key,NEW.origin,NEW.original_fields,NEW.batch_id,NEW.source_row) IS DISTINCT FROM ROW(OLD.tenant_key,OLD.id,OLD.event_key,OLD.origin,OLD.original_fields,OLD.batch_id,OLD.source_row) THEN
|
||||
RAISE EXCEPTION 'master provenance and original deduplication key are immutable' USING ERRCODE='55000';
|
||||
END IF;
|
||||
NEW.row_revision=OLD.row_revision+1;NEW.updated_at=clock_timestamp();
|
||||
IF jsonb_build_array(NEW.payload->'status',NEW.payload->'question',NEW.payload->'answer',NEW.payload->'references',NEW.payload->'media') IS DISTINCT FROM jsonb_build_array(OLD.payload->'status',OLD.payload->'question',OLD.payload->'answer',OLD.payload->'references',OLD.payload->'media') THEN
|
||||
NEW.quality_hash=encode(sha256(convert_to(jsonb_build_array(NEW.id,NEW.payload->'status',NEW.payload->'question',NEW.payload->'answer',NEW.payload->'references',NEW.payload->'media')::text,'UTF8')),'hex');
|
||||
NEW.payload=NEW.payload||jsonb_build_object('_quality_hash',NEW.quality_hash,'_quality_observed_at',NEW.updated_at);
|
||||
END IF;
|
||||
IF NEW.payload IS DISTINCT FROM OLD.payload THEN
|
||||
NEW.question=NEW.payload->>'question';NEW.asked_at=(NEW.payload->>'asked_at')::timestamptz;NEW.status=NEW.payload->>'status';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER qa_master_provenance BEFORE UPDATE ON qa_ops_master_records FOR EACH ROW EXECUTE FUNCTION qa_ops_master_protect_provenance();
|
||||
-- Keep ALL existing 2.0 IDs, even pre-existing equal-key events; this is not an authorization to delete them.
|
||||
INSERT INTO qa_ops_master_records(tenant_key,id,event_key,origin,asked_at,question,status,identity,quality_hash,payload)
|
||||
SELECT tenant_key,id,qa_ops_master_event_key(asked_at,payload->>'asker',question),'dobotai_2_0',asked_at,question,status,identity,quality_hash,payload FROM qa_ops_mirror_records;
|
||||
INSERT INTO qa_ops_master_source_links(tenant_key,source_kind,source_id,master_id)
|
||||
SELECT tenant_key,'dobotai_2_0',id,id FROM qa_ops_mirror_records;
|
||||
-- Preserve copied audit identities/timestamps; the original namespace is never updated.
|
||||
CREATE FUNCTION qa_ops_master_copy_source_quality(source_tenant text,source_id text) RETURNS boolean LANGUAGE plpgsql AS $$
|
||||
DECLARE copied bigint;
|
||||
BEGIN
|
||||
INSERT INTO qa_ops_quality_records SELECT q.tenant_key||'::master',q.record_id,q.observed_at,q.input_hash,q.input_epoch,q.review_revision FROM qa_ops_quality_records q JOIN qa_ops_master_records m ON m.tenant_key=q.tenant_key AND m.id=q.record_id WHERE q.tenant_key=source_tenant AND m.origin='dobotai_2_0' AND (source_id IS NULL OR q.record_id=source_id) ON CONFLICT DO NOTHING;
|
||||
GET DIAGNOSTICS copied=ROW_COUNT; IF copied=0 THEN RETURN false; END IF;
|
||||
INSERT INTO qa_ops_quality_inputs SELECT q.tenant_key||'::master',q.record_id,q.input_epoch,q.input_hash,q.payload,q.created_at FROM qa_ops_quality_inputs q JOIN qa_ops_master_records m ON m.tenant_key=q.tenant_key AND m.id=q.record_id WHERE q.tenant_key=source_tenant AND m.origin='dobotai_2_0' AND (source_id IS NULL OR q.record_id=source_id);
|
||||
INSERT INTO qa_ops_quality_checks(tenant_key,record_id,input_epoch,rule_version,result,source,created_at) SELECT q.tenant_key||'::master',q.record_id,q.input_epoch,q.rule_version,q.result,q.source,q.created_at FROM qa_ops_quality_checks q JOIN qa_ops_master_records m ON m.tenant_key=q.tenant_key AND m.id=q.record_id WHERE q.tenant_key=source_tenant AND m.origin='dobotai_2_0' AND (source_id IS NULL OR q.record_id=source_id);
|
||||
INSERT INTO qa_ops_quality_reviews SELECT q.tenant_key||'::master',q.record_id,q.revision,q.input_epoch,q.input_hash,q.fields,q.reason,q.reviewer,q.nonce,q.request_hash,q.created_at FROM qa_ops_quality_reviews q JOIN qa_ops_master_records m ON m.tenant_key=q.tenant_key AND m.id=q.record_id WHERE q.tenant_key=source_tenant AND m.origin='dobotai_2_0' AND (source_id IS NULL OR q.record_id=source_id);
|
||||
RETURN true;
|
||||
END $$;
|
||||
SELECT qa_ops_master_copy_source_quality(tenant_key,NULL) FROM (SELECT DISTINCT tenant_key FROM qa_ops_master_records) tenants;
|
||||
CREATE FUNCTION qa_ops_master_observe_quality() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE quality_tenant text=NEW.tenant_key||'::master'; next_epoch bigint; assessment jsonb; evidence jsonb; observed timestamptz;
|
||||
BEGIN
|
||||
IF TG_OP='UPDATE' AND NEW.quality_hash=OLD.quality_hash THEN RETURN NEW; END IF;
|
||||
IF TG_OP='INSERT' AND NEW.origin='dobotai_2_0' THEN
|
||||
PERFORM qa_ops_master_copy_source_quality(NEW.tenant_key,NEW.id);
|
||||
IF EXISTS(SELECT 1 FROM qa_ops_quality_records WHERE tenant_key=quality_tenant AND record_id=NEW.id AND input_hash=NEW.quality_hash) THEN RETURN NEW; END IF;
|
||||
END IF;
|
||||
observed=COALESCE((NEW.payload->>'_quality_observed_at')::timestamptz,NEW.updated_at);
|
||||
INSERT INTO qa_ops_quality_records(tenant_key,record_id) VALUES(quality_tenant,NEW.id) ON CONFLICT DO NOTHING;
|
||||
SELECT input_epoch+1 INTO next_epoch FROM qa_ops_quality_records WHERE tenant_key=quality_tenant AND record_id=NEW.id FOR UPDATE;
|
||||
evidence=jsonb_build_object('version','governance-master-quality-v1','id',NEW.id,'status',NEW.status,'question',NEW.question,'answer',COALESCE(NEW.payload->>'answer',''),'references',COALESCE(NEW.payload->'references','null'::jsonb),'media',COALESCE(NEW.payload->'media','null'::jsonb));
|
||||
assessment=jsonb_build_object('state','pending','rule_version','governance-answer-substring-v1');
|
||||
IF position('暂无已发布' IN COALESCE(NEW.payload->>'answer',''))>0 THEN assessment=assessment||jsonb_build_object('state','checked','verdict','uncovered','matched_text','暂无已发布'); END IF;
|
||||
INSERT INTO qa_ops_quality_inputs(tenant_key,record_id,input_epoch,input_hash,payload) VALUES(quality_tenant,NEW.id,next_epoch,NEW.quality_hash,evidence);
|
||||
INSERT INTO qa_ops_quality_checks(tenant_key,record_id,input_epoch,rule_version,result,source) VALUES(quality_tenant,NEW.id,next_epoch,'governance-answer-substring-v1',assessment,COALESCE(NEW.payload->'source_coverage',jsonb_build_object('verdict','','reason_code','','evaluator_version','')));
|
||||
UPDATE qa_ops_quality_records SET input_epoch=next_epoch,input_hash=NEW.quality_hash,observed_at=observed WHERE tenant_key=quality_tenant AND record_id=NEW.id;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER qa_master_quality AFTER INSERT OR UPDATE ON qa_ops_master_records FOR EACH ROW EXECUTE FUNCTION qa_ops_master_observe_quality();
|
||||
CREATE FUNCTION qa_ops_append_source_to_master() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE key_value text; matched_id text; matches bigint;
|
||||
BEGIN
|
||||
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 RETURN NEW; END IF;
|
||||
key_value=qa_ops_master_event_key(NEW.asked_at,NEW.payload->>'asker',NEW.question);
|
||||
PERFORM pg_advisory_xact_lock(hashtextextended(NEW.tenant_key||key_value,254));
|
||||
SELECT count(*),min(id) INTO matches,matched_id FROM qa_ops_master_records WHERE tenant_key=NEW.tenant_key AND event_key=key_value;
|
||||
IF matches<>1 THEN
|
||||
matched_id=NEW.id;
|
||||
INSERT INTO qa_ops_master_records(tenant_key,id,event_key,origin,asked_at,question,status,identity,quality_hash,payload)
|
||||
VALUES(NEW.tenant_key,NEW.id,key_value,'dobotai_2_0',NEW.asked_at,NEW.question,NEW.status,NEW.identity,NEW.quality_hash,NEW.payload);
|
||||
END IF;
|
||||
INSERT INTO qa_ops_master_source_links(tenant_key,source_kind,source_id,master_id) VALUES(NEW.tenant_key,'dobotai_2_0',NEW.id,matched_id);
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
-- UPDATE only admits an unlinked source. A linked row never rewrites the master;
|
||||
-- DELETE deliberately has NO corresponding master trigger or cascading FK.
|
||||
CREATE TRIGGER qa_mirror_append_to_master AFTER INSERT OR UPDATE ON qa_ops_mirror_records FOR EACH ROW EXECUTE FUNCTION qa_ops_append_source_to_master();
|
||||
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 49 {
|
||||
t.Fatalf("migration count = %d, want 49", len(migrations))
|
||||
if len(migrations) != 53 {
|
||||
t.Fatalf("migration count = %d, want 53", 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,32 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDurableMasterMigrationOwnsDataAndRetainsAuditOnRollback(t *testing.T) {
|
||||
migrations, err := loadMigrations()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var up, down string
|
||||
for _, m := range migrations {
|
||||
if m.Version == 53 {
|
||||
up, down = m.UpSQL, m.DownSQL
|
||||
}
|
||||
}
|
||||
for _, required := range []string{"CREATE TABLE qa_ops_master_state", "CREATE TABLE qa_ops_master_records", "CREATE TABLE qa_ops_master_source_links", "CREATE TABLE qa_ops_master_import_batches", "CREATE TABLE qa_ops_master_import_rows", "CREATE FUNCTION qa_ops_master_copy_source_quality", "CREATE FUNCTION qa_ops_master_protect_provenance", "qa_ops_master_normalize(person)", "qa_ops_master_normalize(original_question)", "payload->>'id'=id", "AFTER INSERT OR UPDATE ON qa_ops_mirror_records", "source_id=NEW.id"} {
|
||||
if !strings.Contains(up, required) {
|
||||
t.Fatalf("migration 53 lacks durable-master contract %q", required)
|
||||
}
|
||||
}
|
||||
if strings.Contains(up, "AFTER DELETE ON qa_ops_mirror_records") || strings.Contains(up, "UPDATE qa_ops_mirror_records") || strings.Contains(up, "DELETE FROM qa_ops_mirror_records") {
|
||||
t.Fatal("master migration must neither rewrite mirror business rows nor follow source deletions")
|
||||
}
|
||||
for _, required := range []string{"qa_ops_master_import_batches", "row_revision<>1", "o.request_hash IS DISTINCT FROM r.request_hash", "keep additive schema on application rollback"} {
|
||||
if !strings.Contains(down, required) {
|
||||
t.Fatalf("down migration may lose locally-owned data: missing %q", required)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRegionCatalogMigrationIsAdditiveAndRefusesLossyDown(t *testing.T) {
|
||||
migrations, e := loadMigrations()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var up, down string
|
||||
for _, m := range migrations {
|
||||
if m.Version == 51 {
|
||||
up = m.UpSQL
|
||||
down = m.DownSQL
|
||||
}
|
||||
}
|
||||
for _, fragment := range []string{"ADD COLUMN region_definitions JSONB NOT NULL DEFAULT", "jsonb_typeof(region_definitions)='array'", "国内工业", "APAC", "EMEA", "America"} {
|
||||
if !strings.Contains(up, fragment) {
|
||||
t.Fatal("missing additive/backfill region contract", fragment)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(down, "RAISE EXCEPTION") || !strings.Contains(down, "region_definitions <>") || !strings.Contains(down, "DROP COLUMN region_definitions") {
|
||||
t.Fatal("lossy down migration was not guarded")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWeeklyQualityMigrationPreservesFrozenHistory(t *testing.T) {
|
||||
migrations, e := loadMigrations()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var up, down string
|
||||
for _, m := range migrations {
|
||||
if m.Version == 52 {
|
||||
up = m.UpSQL
|
||||
down = m.DownSQL
|
||||
}
|
||||
}
|
||||
for _, part := range []string{"CREATE TABLE qa_ops_weekly_quality_tracking", "first_data_at TIMESTAMPTZ", "CREATE TABLE qa_ops_weekly_quality_snapshots", "CREATE TABLE qa_ops_weekly_quality_snapshot_records", "AT TIME ZONE 'Asia/Shanghai'", "BEFORE UPDATE OR DELETE", "BEFORE INSERT", "pg_current_xact_id()", "coverage_denominator<=record_count"} {
|
||||
if !strings.Contains(up, part) {
|
||||
t.Fatal("missing frozen weekly quality contract", part)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(down, "IF EXISTS(SELECT 1 FROM qa_ops_weekly_quality_snapshots)") || !strings.Contains(down, "RAISE EXCEPTION") || !strings.Contains(down, "DROP FUNCTION qa_ops_require_new_weekly_quality_header()") {
|
||||
t.Fatal("lossy history rollback or stale trigger functions")
|
||||
}
|
||||
for _, forbidden := range []string{"ALTER TABLE qa_ops_mirror_records", "UPDATE qa_ops_quality_reviews", "answer TEXT", "staff_id TEXT"} {
|
||||
if strings.Contains(up, forbidden) {
|
||||
t.Fatal("snapshot migration widened into original records or employee identity")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"time"
|
||||
)
|
||||
|
||||
type DashboardCount struct {
|
||||
Label string `json:"label"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
type DashboardDaily struct {
|
||||
Date string `json:"date"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
type DashboardFrozen struct {
|
||||
WeekStart time.Time `json:"week_start"`
|
||||
WeekEnd time.Time `json:"week_end"`
|
||||
FrozenAt *time.Time `json:"frozen_at"`
|
||||
PolicyVersion string `json:"policy_version"`
|
||||
Records int `json:"records"`
|
||||
Coverage qaopsquality.Rate `json:"coverage"`
|
||||
Correctness qaopsquality.Rate `json:"correctness"`
|
||||
}
|
||||
type DashboardRegion struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Questions int `json:"questions"`
|
||||
Users *int `json:"users"`
|
||||
RosterPeople *int `json:"roster_people"`
|
||||
Frequency *float64 `json:"frequency"`
|
||||
UsageCoverage qaopsquality.Rate `json:"usage_coverage"`
|
||||
}
|
||||
type Dashboard struct {
|
||||
Start time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
Keyword string `json:"keyword"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
LocalRevision int64 `json:"local_revision"`
|
||||
Organization dobotaiops.OrganizationVersion `json:"organization"`
|
||||
TotalIssues int `json:"total_issues"`
|
||||
NewThisWeek int `json:"new_this_week"`
|
||||
WeekStart time.Time `json:"week_start"`
|
||||
MonthStart time.Time `json:"month_start"`
|
||||
Quality qaopsquality.Summary `json:"quality"`
|
||||
IssueTypes []DashboardCount `json:"issue_types"`
|
||||
Products []DashboardCount `json:"products"`
|
||||
Daily []DashboardDaily `json:"daily"`
|
||||
Regions []DashboardRegion `json:"regions"`
|
||||
FrozenWeeks []DashboardFrozen `json:"frozen_weeks"`
|
||||
}
|
||||
|
||||
var dashboardLocation = time.FixedZone("Asia/Shanghai", 8*60*60)
|
||||
|
||||
func dashboardDay(at time.Time) time.Time {
|
||||
t := at.In(dashboardLocation)
|
||||
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, dashboardLocation)
|
||||
}
|
||||
func dashboardWeek(at time.Time) time.Time {
|
||||
d := dashboardDay(at)
|
||||
return d.AddDate(0, 0, -((int(d.Weekday()) + 6) % 7))
|
||||
}
|
||||
func dashboardPeriods(end time.Time) (time.Time, time.Time) {
|
||||
cutoff := end.Add(-time.Nanosecond).In(dashboardLocation)
|
||||
return time.Date(cutoff.Year(), cutoff.Month(), 1, 0, 0, 0, 0, dashboardLocation), dashboardWeek(cutoff)
|
||||
}
|
||||
func dashboardFrozenSeries(first, end time.Time, snapshots map[string]DashboardFrozen) []DashboardFrozen {
|
||||
out := []DashboardFrozen{}
|
||||
if first.IsZero() || !first.Before(end) {
|
||||
return out
|
||||
}
|
||||
for at := dashboardWeek(first); at.Before(end) && len(out) < 5200; at = at.AddDate(0, 0, 7) {
|
||||
key := at.Format("2006-01-02")
|
||||
point, ok := snapshots[key]
|
||||
if !ok {
|
||||
point = DashboardFrozen{WeekStart: at, WeekEnd: at.AddDate(0, 0, 7)}
|
||||
}
|
||||
out = append(out, point)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Store) TrackQualityWeeks(ctx context.Context, at time.Time) error {
|
||||
if !s.valid() || at.IsZero() {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
_, e := s.pool.Exec(ctx, `INSERT INTO qa_ops_weekly_quality_tracking(tenant_key,started_at,first_data_at) VALUES($1,$2,(SELECT min(asked_at) FROM qa_ops_mirror_records WHERE tenant_key=$1 AND asked_at<=$2)) ON CONFLICT(tenant_key) DO UPDATE SET first_data_at=LEAST(qa_ops_weekly_quality_tracking.first_data_at,EXCLUDED.first_data_at) WHERE EXCLUDED.first_data_at IS NOT NULL AND (qa_ops_weekly_quality_tracking.first_data_at IS NULL OR EXCLUDED.first_data_at<qa_ops_weekly_quality_tracking.first_data_at)`, s.tenant, at)
|
||||
if e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Capture only during the following Monday, after a complete post-boundary
|
||||
// source observation. A missed capture remains a gap, never retrospective data.
|
||||
// Scheduling is local worker-owned; browser reads never freeze or write metrics.
|
||||
func (s *Store) FreezePreviousQualityWeek(ctx context.Context, at time.Time) (bool, error) {
|
||||
if !s.valid() || at.IsZero() {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if at.In(dashboardLocation).Weekday() != time.Monday {
|
||||
return false, nil
|
||||
}
|
||||
end := dashboardWeek(at)
|
||||
start := end.AddDate(0, 0, -7)
|
||||
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
defer cancel()
|
||||
tx, e := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead})
|
||||
if e != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
var locked bool
|
||||
if tx.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(hashtextextended($1,17))`, s.tenant+":qa-quality-freeze:"+start.Format("2006-01-02")).Scan(&locked) != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if !locked {
|
||||
return false, nil
|
||||
}
|
||||
var tracked time.Time
|
||||
if e = tx.QueryRow(ctx, `SELECT started_at FROM qa_ops_weekly_quality_tracking WHERE tenant_key=$1`, s.tenant).Scan(&tracked); e == pgx.ErrNoRows {
|
||||
return false, nil
|
||||
} else if e != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if !tracked.Before(end) {
|
||||
return false, nil
|
||||
}
|
||||
var exists bool
|
||||
if tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM qa_ops_weekly_quality_snapshots WHERE tenant_key=$1 AND week_start=$2)`, s.tenant, start).Scan(&exists) != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if exists {
|
||||
return false, nil
|
||||
}
|
||||
state, e := s.readState(ctx, txQuery{tx})
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
if state.Blocked || !state.Ready || state.SourceObservedAt == nil || state.LastSuccessAt == nil || state.SourceObservedAt.Before(end) || state.SourceObservedAt.After(at) || state.LastSuccessAt.Before(end) || state.LastSuccessAt.After(at) {
|
||||
return false, nil
|
||||
}
|
||||
rows, e := tx.Query(ctx, `SELECT id,question,quality_hash FROM qa_ops_mirror_records WHERE tenant_key=$1 AND asked_at>=$2 AND asked_at<$3 ORDER BY id LIMIT 100001`, s.tenant, start, end)
|
||||
if e != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
type frozenRecord struct {
|
||||
id, question, hash string
|
||||
coverage, correctness qaopsquality.Rate
|
||||
}
|
||||
records := []frozenRecord{}
|
||||
keys := []dobotaiops.QualityKey{}
|
||||
for rows.Next() {
|
||||
var r frozenRecord
|
||||
if rows.Scan(&r.id, &r.question, &r.hash) != nil {
|
||||
rows.Close()
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
records = append(records, r)
|
||||
keys = append(keys, dobotaiops.QualityKey{ID: r.id, InputHash: r.hash})
|
||||
if len(records) > dobotaiops.MaxMirrorRecords {
|
||||
rows.Close()
|
||||
return false, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
views := map[string]qaopsquality.View{}
|
||||
quality := qaopsquality.NewStore(s.pool, s.tenant)
|
||||
for begin := 0; begin < len(keys); begin += 5000 {
|
||||
stop := begin + 5000
|
||||
if stop > len(keys) {
|
||||
stop = len(keys)
|
||||
}
|
||||
batch, err := quality.ReadViewsInTx(ctx, tx, keys[begin:stop])
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for id, v := range batch {
|
||||
views[id] = v
|
||||
}
|
||||
}
|
||||
rates := qaopsquality.ComputeRates(views)
|
||||
for i := range records {
|
||||
r := &records[i]
|
||||
v, ok := views[r.id]
|
||||
if !ok {
|
||||
return false, qaopsquality.ErrUnavailable
|
||||
}
|
||||
if v.Automatic.CreatedAt.After(at) || (v.LatestReview != nil && v.LatestReview.CreatedAt.After(at)) {
|
||||
return false, qaopsquality.ErrConflict
|
||||
}
|
||||
one := qaopsquality.ComputeRates(map[string]qaopsquality.View{r.id: v})
|
||||
r.coverage = one.Coverage
|
||||
r.correctness = one.Correctness
|
||||
}
|
||||
tag, e := tx.Exec(ctx, `INSERT INTO qa_ops_weekly_quality_snapshots(tenant_key,week_start,week_end,frozen_at,mirror_revision,source_observed_at,policy_version,record_count,coverage_numerator,coverage_denominator,correctness_numerator,correctness_denominator) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) ON CONFLICT(tenant_key,week_start) DO NOTHING`, s.tenant, start, end, at, state.Revision, *state.SourceObservedAt, rates.PolicyVersion, len(records), rates.Coverage.Numerator, rates.Coverage.Denominator, rates.Correctness.Numerator, rates.Correctness.Denominator)
|
||||
if e != nil || tag.RowsAffected() != 1 {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
count, e := tx.CopyFrom(ctx, pgx.Identifier{"qa_ops_weekly_quality_snapshot_records"}, []string{"tenant_key", "week_start", "record_id", "question", "coverage_numerator", "coverage_denominator", "correctness_numerator", "correctness_denominator"}, pgx.CopyFromSlice(len(records), func(i int) ([]any, error) {
|
||||
r := records[i]
|
||||
return []any{s.tenant, start, r.id, r.question, r.coverage.Numerator, r.coverage.Denominator, r.correctness.Numerator, r.correctness.Denominator}, nil
|
||||
}))
|
||||
if e != nil || count != int64(len(records)) {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
var verified int
|
||||
if tx.QueryRow(ctx, `SELECT count(*) FROM qa_ops_weekly_quality_snapshot_records WHERE tenant_key=$1 AND week_start=$2`, s.tenant, start).Scan(&verified) != nil || verified != len(records) {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *Store) readFrozenDashboard(ctx context.Context, tx pgx.Tx, keyword string, end time.Time) (map[string]DashboardFrozen, error) {
|
||||
rows, e := tx.Query(ctx, `SELECT h.week_start,h.week_end,h.frozen_at,h.policy_version,h.record_count,count(r.record_id),count(r.record_id) FILTER(WHERE $2='' OR position(lower($2) IN lower(r.question))>0),COALESCE(sum(r.coverage_numerator) FILTER(WHERE $2='' OR position(lower($2) IN lower(r.question))>0),0),COALESCE(sum(r.coverage_denominator) FILTER(WHERE $2='' OR position(lower($2) IN lower(r.question))>0),0),COALESCE(sum(r.correctness_numerator) FILTER(WHERE $2='' OR position(lower($2) IN lower(r.question))>0),0),COALESCE(sum(r.correctness_denominator) FILTER(WHERE $2='' OR position(lower($2) IN lower(r.question))>0),0) FROM qa_ops_weekly_quality_snapshots h LEFT JOIN qa_ops_weekly_quality_snapshot_records r ON r.tenant_key=h.tenant_key AND r.week_start=h.week_start WHERE h.tenant_key=$1 AND h.week_start<$3 GROUP BY h.week_start,h.week_end,h.frozen_at,h.policy_version,h.record_count ORDER BY h.week_start`, s.tenant, keyword, end)
|
||||
if e != nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[string]DashboardFrozen{}
|
||||
for rows.Next() {
|
||||
var p DashboardFrozen
|
||||
var total, actual, cn, cd, an, ad int
|
||||
if rows.Scan(&p.WeekStart, &p.WeekEnd, &p.FrozenAt, &p.PolicyVersion, &total, &actual, &p.Records, &cn, &cd, &an, &ad) != nil || actual != total || cn > cd || an > ad || cd > p.Records || ad > p.Records {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
p.Coverage = dashboardRate(cn, cd)
|
||||
p.Correctness = dashboardRate(an, ad)
|
||||
out[p.WeekStart.In(dashboardLocation).Format("2006-01-02")] = p
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDashboardUsesLifetimeWeekMonthAndDeduplicatedRegionalRoster(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
s := NewStore(p, "fixture-dashboard")
|
||||
queue := pg.NewStore(p)
|
||||
dates := []string{"2026-09-28T08:00:00+08:00", "2026-10-02T08:00:00+08:00", "2026-10-06T08:00:00+08:00", "2026-10-10T08:00:00+08:00"}
|
||||
source := &fixtureSource{}
|
||||
for i, date := range dates {
|
||||
entry := fixtureEntry([]string{"older", "month", "covered", "uncovered"}[i], "暂无已发布")
|
||||
var wire map[string]any
|
||||
_ = json.Unmarshal(entry.Payload, &wire)
|
||||
wire["asked_at"] = date
|
||||
wire["question"] = "needle 100%_ fixture"
|
||||
entry.Payload, _ = json.Marshal(wire)
|
||||
source.rows = append(source.rows, entry)
|
||||
}
|
||||
job := claimMirrorJob(t, s, queue, "dashboard-seed")
|
||||
if e := s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
org := qaopsorg.NewStore(p, s.tenant)
|
||||
state, e := org.ReplaceDirectory(ctx, qaopsorg.Import{Source: "weekly_report_snapshot", SyncedAt: time.Date(2026, 10, 10, 0, 0, 0, 0, time.UTC), Complete: true, Directory: qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "root", Name: "示例组织"}}, People: []qaopsorg.Person{{ID: "s", DepartmentIDs: []string{"root"}}, {ID: "zero-use", DepartmentIDs: []string{"root"}}}}})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_, e = org.SaveRules(ctx, qaopsorg.SaveRequest{DirectoryID: state.DirectoryID, Regions: []qaopsorg.RegionDefinition{{ID: "education", Name: "国内教育"}}, Rules: []qaopsorg.Rule{{DepartmentID: "root", Region: "education"}}}, "fixture-admin")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
record, e := s.GetRecord(ctx, s.tenant, "covered")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
quality := qaopsquality.NewStore(p, s.tenant)
|
||||
views, e := quality.Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
v := views[record.ID]
|
||||
_, e = quality.Save(ctx, record, qaopsquality.SaveRequest{InputHash: v.InputHash, InputEpoch: v.InputEpoch, BaseRevision: v.Revision, Nonce: strings.Repeat("d", 32), Fields: qaopsquality.Fields{Coverage: "covered", Correctness: "correct", ProductCategory: "CR", ProblemType: "使用咨询"}, Reason: "explicit isolated test review"}, "fixture-admin")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
start, _ := time.Parse(time.RFC3339, "2026-10-05T00:00:00+08:00")
|
||||
end := start.AddDate(0, 0, 7)
|
||||
data, e := s.ReadDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}, Keyword: "100%_"})
|
||||
if e != nil {
|
||||
t.Fatal("dashboard must read one local snapshot without a source client", e)
|
||||
}
|
||||
if data.TotalIssues != 4 || data.NewThisWeek != 2 || data.Quality.Total != 2 || data.Quality.Rates.Coverage.Numerator != 1 || data.Quality.Rates.Coverage.Denominator != 2 {
|
||||
t.Fatal("lifetime/selected-week quality were mixed")
|
||||
}
|
||||
if len(data.Daily) != 7 || len(data.Regions) != 1 {
|
||||
t.Fatal("daily range or custom region catalog missing")
|
||||
}
|
||||
r := data.Regions[0]
|
||||
if r.Questions != 3 || r.Users == nil || *r.Users != 1 || r.RosterPeople == nil || *r.RosterPeople != 2 || r.Frequency == nil || *r.Frequency != 1.5 || r.UsageCoverage.Percent == nil || *r.UsageCoverage.Percent != 50 {
|
||||
t.Fatal("monthly regional scope or full-roster denominator was replaced by active users")
|
||||
}
|
||||
if len(data.FrozenWeeks) != 2 {
|
||||
t.Fatal("historical weeks did not start at first data week")
|
||||
}
|
||||
for _, point := range data.FrozenWeeks {
|
||||
if point.FrozenAt != nil || point.Coverage.Percent != nil || point.Correctness.Percent != nil {
|
||||
t.Fatal("current quality was backfilled into absent frozen history")
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("historical quality is frozen once and never backfilled", func(t *testing.T) {
|
||||
tracked := start.AddDate(0, 0, 2)
|
||||
if e := s.TrackQualityWeeks(ctx, tracked); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
freezeAt := end.Add(6 * time.Minute)
|
||||
// Explicit fake-clock fixture: the source snapshot and review existed before the closing capture.
|
||||
if _, e = p.Exec(ctx, "UPDATE qa_ops_mirror_state SET source_observed_at=$2,synced_at=$2 WHERE tenant_key=$1", s.tenant, freezeAt.Add(-time.Minute)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = p.Exec(ctx, "UPDATE qa_ops_quality_reviews SET created_at=$2 WHERE tenant_key=$1", s.tenant, end.Add(-time.Hour)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = p.Exec(ctx, "UPDATE qa_ops_quality_checks SET created_at=$2 WHERE tenant_key=$1", s.tenant, end.Add(-time.Hour)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
frozen, e := s.FreezePreviousQualityWeek(ctx, freezeAt)
|
||||
if e != nil || !frozen {
|
||||
t.Fatal("first eligible Monday capture was not frozen", e)
|
||||
}
|
||||
for _, statement := range []string{
|
||||
`UPDATE qa_ops_weekly_quality_snapshots SET policy_version=policy_version||'-changed' WHERE tenant_key=$1`,
|
||||
`UPDATE qa_ops_weekly_quality_snapshot_records SET question=question||' changed' WHERE tenant_key=$1`,
|
||||
`DELETE FROM qa_ops_weekly_quality_snapshots WHERE tenant_key=$1`,
|
||||
`DELETE FROM qa_ops_weekly_quality_snapshot_records WHERE tenant_key=$1`,
|
||||
`INSERT INTO qa_ops_weekly_quality_snapshot_records SELECT tenant_key,week_start,record_id||'-late',question,coverage_numerator,coverage_denominator,correctness_numerator,correctness_denominator FROM qa_ops_weekly_quality_snapshot_records WHERE tenant_key=$1 LIMIT 1`,
|
||||
} {
|
||||
mutation, err := p.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = mutation.Exec(ctx, statement, s.tenant)
|
||||
_ = mutation.Rollback(ctx)
|
||||
var dbError *pgconn.PgError
|
||||
if !errors.As(err, &dbError) || dbError.Code != "55000" {
|
||||
t.Fatal("committed snapshot mutation was not rejected by the immutable guard", err)
|
||||
}
|
||||
}
|
||||
historical, e := s.ReadDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}, Keyword: "100%_"})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
last := historical.FrozenWeeks[len(historical.FrozenWeeks)-1]
|
||||
if last.FrozenAt == nil || last.Coverage.Percent == nil || *last.Coverage.Percent != 50 || last.Correctness.Percent == nil || *last.Correctness.Percent != 100 {
|
||||
t.Fatal("frozen ratios or literal keyword projection were lost")
|
||||
}
|
||||
latest, e := quality.ReadViews(ctx, []dobotaiops.QualityKey{{ID: record.ID, InputHash: v.InputHash}})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
current := latest[record.ID]
|
||||
if _, e = quality.Save(ctx, record, qaopsquality.SaveRequest{InputHash: current.InputHash, InputEpoch: current.InputEpoch, BaseRevision: current.Revision, Nonce: strings.Repeat("e", 32), Fields: qaopsquality.Fields{Coverage: "uncovered", Correctness: "incorrect"}, Reason: "later isolated correction, must not rewrite frozen history"}, "fixture-admin"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
repeated, e := s.FreezePreviousQualityWeek(ctx, freezeAt.Add(time.Minute))
|
||||
if e != nil || repeated {
|
||||
t.Fatal("immutable weekly snapshot was replaced")
|
||||
}
|
||||
changed, e := s.ReadDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}, Keyword: "100%_"})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
point := changed.FrozenWeeks[len(changed.FrozenWeeks)-1]
|
||||
if changed.Quality.Rates.Coverage.Numerator != 0 || point.Coverage.Percent == nil || *point.Coverage.Percent != 50 || changed.FrozenWeeks[0].FrozenAt != nil {
|
||||
t.Fatal("current correction rewrote frozen history or backfilled pre-tracking weeks")
|
||||
}
|
||||
})
|
||||
raw, _ := json.Marshal(data)
|
||||
if strings.Contains(string(raw), "zero-use") || strings.Contains(string(raw), "needle") {
|
||||
t.Fatal("dashboard leaked identity or original question rows")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type dashboardRecord struct {
|
||||
id, hash string
|
||||
at time.Time
|
||||
identity dobotaiops.ActorIdentity
|
||||
}
|
||||
|
||||
func dashboardRate(n, d int) qaopsquality.Rate {
|
||||
r := qaopsquality.Rate{Numerator: n, Denominator: d}
|
||||
if d > 0 {
|
||||
p := 100 * float64(n) / float64(d)
|
||||
r.Percent = &p
|
||||
}
|
||||
return r
|
||||
}
|
||||
func dashboardCategories(counts map[string]int) []DashboardCount {
|
||||
out := []DashboardCount{}
|
||||
for label, count := range counts {
|
||||
out = append(out, DashboardCount{Label: label, Count: count})
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].Count == out[j].Count {
|
||||
return out[i].Label < out[j].Label
|
||||
}
|
||||
return out[i].Count > out[j].Count
|
||||
})
|
||||
return out
|
||||
}
|
||||
func dashboardCategory(value string) string {
|
||||
if value = strings.TrimSpace(value); value != "" {
|
||||
return value
|
||||
}
|
||||
return "未分类"
|
||||
}
|
||||
|
||||
// ReadDashboard never fetches answer payloads or opens a source connection. All
|
||||
// scopes, quality inputs and organizational attribution use ONE local snapshot.
|
||||
func (s *Store) ReadDashboard(ctx context.Context, q dobotaiops.RecordQuery) (Dashboard, error) {
|
||||
out := Dashboard{Start: q.Window.Start, End: q.Window.End, Keyword: q.Keyword, IssueTypes: []DashboardCount{}, Products: []DashboardCount{}, Daily: []DashboardDaily{}, Regions: []DashboardRegion{}, FrozenWeeks: []DashboardFrozen{}}
|
||||
if !s.valid() {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if q.Window.TenantKey != s.tenant || !utf8.ValidString(q.Keyword) || utf8.RuneCountInString(q.Keyword) > 200 || strings.ContainsRune(q.Keyword, 0) {
|
||||
return out, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
if _, e := dobotaiops.NewWindow(s.tenant, q.Window.Start.Format(time.RFC3339Nano), q.Window.End.Format(time.RFC3339Nano), 90*24*time.Hour, time.Now()); e != nil {
|
||||
return out, e
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
defer cancel()
|
||||
tx, e := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||
if e != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
state, e := s.readState(ctx, txQuery{tx})
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
if state.Blocked {
|
||||
return out, dobotaiops.ErrNotReadOnly
|
||||
}
|
||||
if !state.Ready || state.SourceObservedAt == nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
out.AsOf = *state.SourceObservedAt
|
||||
out.LocalRevision = state.Revision
|
||||
attribution, e := qaopsorg.NewStore(s.pool, s.tenant).GetAttributionInTx(ctx, tx)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
meta := attribution.Metadata
|
||||
out.Organization = dobotaiops.OrganizationVersion{State: meta.State, DirectoryID: meta.DirectoryID, DirectorySource: meta.DirectorySource, SyncedAt: meta.DirectorySyncedAt, RevisionID: meta.RevisionID, Basis: "current_directory", RegionNames: meta.RegionLabels()}
|
||||
out.MonthStart, out.WeekStart = dashboardPeriods(q.Window.End)
|
||||
var first *time.Time
|
||||
if e = tx.QueryRow(ctx, `SELECT count(*),LEAST((SELECT min(asked_at) FROM qa_ops_mirror_records WHERE tenant_key=$1 AND asked_at<$2),(SELECT first_data_at FROM qa_ops_weekly_quality_tracking WHERE tenant_key=$1),(SELECT min(week_start) FROM qa_ops_weekly_quality_snapshots WHERE tenant_key=$1 AND week_start<$2)) FROM qa_ops_mirror_records WHERE tenant_key=$1 AND asked_at<$2 AND ($3='' OR position(lower($3) IN lower(question))>0)`, s.tenant, q.Window.End, q.Keyword).Scan(&out.TotalIssues, &first); e != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
lower := q.Window.Start
|
||||
if out.MonthStart.Before(lower) {
|
||||
lower = out.MonthStart
|
||||
}
|
||||
if out.WeekStart.Before(lower) {
|
||||
lower = out.WeekStart
|
||||
}
|
||||
rows, e := tx.Query(ctx, `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`, s.tenant, lower, q.Window.End, q.Keyword)
|
||||
if e != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
records := []dashboardRecord{}
|
||||
keys := []dobotaiops.QualityKey{}
|
||||
for rows.Next() {
|
||||
var r dashboardRecord
|
||||
var identity []byte
|
||||
if rows.Scan(&r.id, &r.at, &identity, &r.hash) != nil || json.Unmarshal(identity, &r.identity) != nil {
|
||||
rows.Close()
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
records = append(records, r)
|
||||
if len(records) > dobotaiops.MaxMirrorRecords {
|
||||
rows.Close()
|
||||
return out, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
if !r.at.Before(q.Window.Start) {
|
||||
keys = append(keys, dobotaiops.QualityKey{ID: r.id, InputHash: r.hash})
|
||||
}
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
views := map[string]qaopsquality.View{}
|
||||
quality := qaopsquality.NewStore(s.pool, s.tenant)
|
||||
for begin := 0; begin < len(keys); begin += 5000 {
|
||||
end := begin + 5000
|
||||
if end > len(keys) {
|
||||
end = len(keys)
|
||||
}
|
||||
batch, err := quality.ReadViewsInTx(ctx, tx, keys[begin:end])
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
for id, v := range batch {
|
||||
views[id] = v
|
||||
}
|
||||
}
|
||||
out.Quality = qaopsquality.Summarize(views)
|
||||
products, types, daily := map[string]int{}, map[string]int{}, map[string]int{}
|
||||
for day := out.WeekStart; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) {
|
||||
daily[day.Format("2006-01-02")] = 0
|
||||
}
|
||||
regionIndex := map[string]int{}
|
||||
users := map[string]map[string]bool{}
|
||||
for _, region := range meta.RegionDefinitions() {
|
||||
r := DashboardRegion{ID: region.ID, Name: region.Name}
|
||||
if meta.State == "ready" {
|
||||
n := meta.View.Regions[region.ID]
|
||||
r.RosterPeople = &n
|
||||
r.Users = new(int)
|
||||
}
|
||||
regionIndex[region.Name] = len(out.Regions)
|
||||
users[region.Name] = map[string]bool{}
|
||||
out.Regions = append(out.Regions, r)
|
||||
}
|
||||
for _, r := range records {
|
||||
if !r.at.Before(out.WeekStart) {
|
||||
out.NewThisWeek++
|
||||
daily[r.at.In(dashboardLocation).Format("2006-01-02")]++
|
||||
}
|
||||
if !r.at.Before(q.Window.Start) {
|
||||
v, ok := views[r.id]
|
||||
if !ok {
|
||||
return out, qaopsquality.ErrUnavailable
|
||||
}
|
||||
products[dashboardCategory(v.Effective.ProductCategory)]++
|
||||
types[dashboardCategory(v.Effective.ProblemType)]++
|
||||
}
|
||||
if !r.at.Before(out.MonthStart) {
|
||||
person := attribution.Resolve(r.identity.StaffID, r.identity.UnionID)
|
||||
if index, ok := regionIndex[person.Region]; ok && person.PersonID != "" {
|
||||
out.Regions[index].Questions++
|
||||
users[person.Region][person.PersonID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
out.Products = dashboardCategories(products)
|
||||
out.IssueTypes = dashboardCategories(types)
|
||||
for day := out.WeekStart; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) {
|
||||
date := day.Format("2006-01-02")
|
||||
out.Daily = append(out.Daily, DashboardDaily{Date: date, Count: daily[date]})
|
||||
}
|
||||
for i := range out.Regions {
|
||||
r := &out.Regions[i]
|
||||
if r.Users != nil {
|
||||
*r.Users = len(users[r.Name])
|
||||
if *r.Users > *r.RosterPeople {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
r.UsageCoverage = dashboardRate(*r.Users, *r.RosterPeople)
|
||||
if *r.RosterPeople > 0 {
|
||||
frequency := float64(r.Questions) / float64(*r.RosterPeople)
|
||||
r.Frequency = &frequency
|
||||
}
|
||||
}
|
||||
}
|
||||
if first != nil {
|
||||
snapshots, err := s.readFrozenDashboard(ctx, tx, q.Keyword, q.Window.End)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.FrozenWeeks = dashboardFrozenSeries(*first, q.Window.End, snapshots)
|
||||
if len(out.FrozenWeeks) > 0 && out.FrozenWeeks[len(out.FrozenWeeks)-1].WeekEnd.Before(q.Window.End) {
|
||||
return out, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDashboardPeriodsUseBeijingAndPreviousSundayAtExclusiveEnd(t *testing.T) {
|
||||
end := time.Date(2026, 11, 2, 0, 0, 0, 0, time.FixedZone("CST", 8*3600))
|
||||
month, week := dashboardPeriods(end)
|
||||
if month.Format(time.RFC3339) != "2026-11-01T00:00:00+08:00" || week.Format(time.RFC3339) != "2026-10-26T00:00:00+08:00" {
|
||||
t.Fatal("exclusive Monday end was assigned to the wrong source week/month")
|
||||
}
|
||||
}
|
||||
func TestDashboardFrozenGapsNeverUseCurrentRates(t *testing.T) {
|
||||
start := time.Date(2026, 9, 28, 0, 0, 0, 0, time.FixedZone("CST", 8*3600))
|
||||
end := start.AddDate(0, 0, 21)
|
||||
points := dashboardFrozenSeries(start, end, nil)
|
||||
if len(points) != 3 {
|
||||
t.Fatal("must include each source natural week including missing snapshots")
|
||||
}
|
||||
for _, point := range points {
|
||||
if point.FrozenAt != nil || point.Coverage.Percent != nil || point.Correctness.Percent != nil {
|
||||
t.Fatal("missing historical snapshots were fabricated from current data")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/jobs"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLocalMirrorFailuresUpdatesAndReviewPreservation(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
s := NewStore(p, "fixture-failures")
|
||||
q := pg.NewStore(p)
|
||||
ctx := context.Background()
|
||||
first := &fixtureSource{rows: []dobotaiops.MirrorRecord{fixtureEntry("one", "old answer")}}
|
||||
run := func(source *fixtureSource, key string) error {
|
||||
j := claimMirrorJob(t, s, q, key)
|
||||
e := s.HandleSync(ctx, *j, func(context.Context) (Source, error) { return source, nil })
|
||||
if e == nil {
|
||||
if e = q.Complete(ctx, j.ID, j.LeaseOwner, time.Now()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
} else {
|
||||
if _, cleanupErr := p.Exec(ctx, `UPDATE jobs SET state='failed',lease_owner=NULL,lease_until=NULL WHERE id=$1`, j.ID); cleanupErr != nil {
|
||||
t.Fatal(cleanupErr)
|
||||
}
|
||||
}
|
||||
return e
|
||||
}
|
||||
if e := run(first, "initial-good"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
quality := qaopsquality.NewStore(p, s.tenant)
|
||||
record, _ := s.GetRecord(ctx, s.tenant, "one")
|
||||
views, e := quality.Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
v := views["one"]
|
||||
saved, e := quality.Save(ctx, record, qaopsquality.SaveRequest{InputHash: v.InputHash, InputEpoch: v.InputEpoch, BaseRevision: v.Revision, Nonce: strings.Repeat("a", 32), Fields: qaopsquality.Fields{Coverage: "covered", Correctness: "correct"}, Reason: "explicit synthetic review"}, "fixture-admin")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
unchanged := &fixtureSource{rows: first.rows}
|
||||
if e = run(unchanged, "unchanged-check"); e != nil || unchanged.payloadCalls != 0 {
|
||||
t.Fatal("unchanged poll transferred long answers", e)
|
||||
}
|
||||
state, _ := s.GetSyncStatus(ctx)
|
||||
if state.Revision != 1 {
|
||||
t.Fatal("unchanged poll invalidated query generations")
|
||||
}
|
||||
current, e := quality.Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil || current["one"].State != "reviewed" || current["one"].Revision != saved.SavedRevision {
|
||||
t.Fatal("unchanged synchronization damaged review", e)
|
||||
}
|
||||
partial := &fixtureSource{payloadError: errors.New("fixture interrupted payload"), failAfter: 2}
|
||||
partial.rows = append(partial.rows, fixtureEntry("one", "new answer"))
|
||||
for n := 0; n < 101; n++ {
|
||||
partial.rows = append(partial.rows, fixtureEntry(fmt.Sprintf("extra-%03d", n), "additional answer"))
|
||||
}
|
||||
if e = run(partial, "interrupted-full-copy"); e == nil {
|
||||
t.Fatal("partial fetch was called complete")
|
||||
}
|
||||
old, e := s.GetRecord(ctx, s.tenant, "one")
|
||||
state, _ = s.GetSyncStatus(ctx)
|
||||
if e != nil || old.Answer != "old answer" || state.Records != 1 || state.Revision != 1 || state.ErrorCode == "" || !state.Ready {
|
||||
t.Fatal("partial failure mutated last-good local copy", e)
|
||||
}
|
||||
current, e = quality.Observe(ctx, []dobotaiops.Record{old})
|
||||
if e != nil || current["one"].State != "reviewed" {
|
||||
t.Fatal("partial source fetch advanced review input", e)
|
||||
}
|
||||
changed := &fixtureSource{rows: []dobotaiops.MirrorRecord{fixtureEntry("one", "changed answer")}}
|
||||
if e = run(changed, "changed-old-record"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
fresh, _ := s.GetRecord(ctx, s.tenant, "one")
|
||||
current, e = quality.Observe(ctx, []dobotaiops.Record{fresh})
|
||||
if e != nil || current["one"].State != "stale" || current["one"].LatestReview == nil || current["one"].LatestReview.Revision != saved.SavedRevision {
|
||||
t.Fatal("answer change lost history or retained an obsolete judgment", e)
|
||||
}
|
||||
denied := &fixtureSource{err: dobotaiops.ErrNotReadOnly}
|
||||
if e = run(denied, "authorization-denied"); e == nil {
|
||||
t.Fatal("source authorization failure ignored")
|
||||
}
|
||||
if e = s.Available(ctx); !errors.Is(e, dobotaiops.ErrNotReadOnly) {
|
||||
t.Fatal("revoked source left local reads enabled", e)
|
||||
}
|
||||
recovered := &fixtureSource{rows: changed.rows}
|
||||
if e = run(recovered, "authorization-recovered"); e != nil || s.Available(ctx) != nil {
|
||||
t.Fatal("verified recovery failed", e)
|
||||
}
|
||||
}
|
||||
func TestLocalMirrorRejectsUnadmittedJobsBeforeSource(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
s := NewStore(p, "fixture-unadmitted")
|
||||
q := pg.NewStore(p)
|
||||
ctx := context.Background()
|
||||
_, e := q.Enqueue(ctx, jobs.EnqueueRequest{ID: "fixture-bypass", Type: s.SyncJobType(), Payload: []byte(`{}`), AvailableAt: time.Now(), MaxAttempts: 1, IdempotencyKey: "fixture-bypass"}, time.Now())
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
j, e := q.Claim(ctx, "fixture-bypass-worker", []string{s.SyncJobType()}, time.Now(), time.Minute)
|
||||
if e != nil || j == nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
calls := 0
|
||||
e = s.HandleSync(ctx, *j, func(context.Context) (Source, error) { calls++; return &fixtureSource{}, nil })
|
||||
if !errors.Is(e, ErrLease) || calls != 0 {
|
||||
t.Fatal("unadmitted job reached source", e, calls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (s *Store) MasterQualityStore() *qaopsquality.Store {
|
||||
return qaopsquality.NewStore(s.pool, s.tenant+"::master")
|
||||
}
|
||||
|
||||
const masterBaseSQL = `WITH records AS (SELECT id,asked_at,question,status,identity,quality_hash,payload||jsonb_build_object('record_origin',origin) AS payload FROM qa_ops_master_records WHERE tenant_key=$1)`
|
||||
|
||||
var masterMetadataBase = strings.NewReplacer("qa_ops_mirror_records", "qa_ops_master_records", "h.tenant_key=m.tenant_key", "h.tenant_key=m.tenant_key||'::master'").Replace(localMetadataBase)
|
||||
var masterSummarySQL = masterMetadataBase + ` SELECT count(*),'{}'::text,COALESCE(jsonb_agg(DISTINCT identity),'[]'::jsonb)::text,COALESCE(jsonb_agg(jsonb_build_object('id',id,'input_hash',quality_hash,'marker',marker,'source',source_coverage)),'[]'::jsonb)::text FROM records WHERE $5::text IS NOT NULL AND `
|
||||
var masterQualityScopeSQL = masterMetadataBase + ` SELECT id,quality_hash,marker,source_coverage::text FROM records WHERE $5::text IS NOT NULL AND `
|
||||
|
||||
func (s *Store) ListMasterRecords(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
var revision int64
|
||||
p, e := s.repositoryFor(&revision, true).ListRecords(ctx, q)
|
||||
p.LocalRevision = revision
|
||||
p.Columns = []string{"question_chinese", "answer", "coverage", "is_correct", "product_category", "problem_type", "root_cause", "asked_at", "asker", "question", "language", "trigger_person", "department", "region", "feedback"}
|
||||
return p, e
|
||||
}
|
||||
func (s *Store) ReadMasterQualityScope(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.QualityScope, error) {
|
||||
return s.repositoryFor(nil, true).ReadQualityScope(ctx, q)
|
||||
}
|
||||
func (s *Store) GetMasterRecord(ctx context.Context, tenant, id string) (dobotaiops.Record, error) {
|
||||
return s.repositoryFor(nil, true).GetRecord(ctx, tenant, id)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMasterAdmissionPreservesPreExistingSourceReviewHistory(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
s := NewStore(p, "fixture-pre-master-review")
|
||||
queue := pg.NewStore(p)
|
||||
entry := fixtureEntry("preexisting-review", "retained original answer")
|
||||
record, e := dobotaiops.DecodeMirrorPayload(string(entry.Payload))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
original := qaopsquality.NewStore(p, s.tenant)
|
||||
views, e := original.Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
v := views[record.ID]
|
||||
receipt, e := original.Save(ctx, record, qaopsquality.SaveRequest{InputHash: v.InputHash, InputEpoch: v.InputEpoch, BaseRevision: v.Revision, Nonce: "fixture_pre_master_review_01", Reason: "existing fixture review", Fields: qaopsquality.Fields{Coverage: "covered", Correctness: "correct"}}, "fixture-original-reviewer")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
job := claimMirrorJob(t, s, queue, "admit-reviewed")
|
||||
source := &fixtureSource{rows: []dobotaiops.MirrorRecord{entry}}
|
||||
if e = s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
copy, e := s.MasterQualityStore().ReadViews(ctx, []dobotaiops.QualityKey{{ID: record.ID, InputHash: record.QualityInputHash}})
|
||||
if e != nil || copy[record.ID].State != "reviewed" || copy[record.ID].Revision != receipt.SavedRevision || copy[record.ID].LatestReview.Reviewer != "fixture-original-reviewer" {
|
||||
t.Fatal("existing source review/audit provenance was lost when admitted to master", e)
|
||||
}
|
||||
if _, e = original.History(ctx, record.ID, 0, 0); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMasterTableKeepsLocalEditsAcrossSourceRefreshAndDeletion(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
s := NewStore(p, "fixture-master")
|
||||
queue := pg.NewStore(p)
|
||||
entry := fixtureEntry("master-source", "source original answer")
|
||||
var wire map[string]any
|
||||
if e := json.Unmarshal(entry.Payload, &wire); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
wire["asked_at"] = "2026-10-06T08:00:00+08:00"
|
||||
wire["asker"] = "fixture asker"
|
||||
entry.Payload, _ = json.Marshal(wire)
|
||||
keeper := fixtureEntry("other-outside-window", "unrelated retained row")
|
||||
source := &fixtureSource{rows: []dobotaiops.MirrorRecord{entry, keeper}}
|
||||
job := claimMirrorJob(t, s, queue, "master-first")
|
||||
if e := s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
start, _ := time.Parse(time.RFC3339, "2026-10-05T00:00:00+08:00")
|
||||
q := dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: start.AddDate(0, 0, 7)}, Limit: 100}
|
||||
if err := queue.Complete(ctx, job.ID, job.LeaseOwner, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page, e := s.ListMasterRecords(ctx, q)
|
||||
if e != nil || page.Total != 1 || len(page.Items) != 1 {
|
||||
t.Fatal("new source record was not admitted into the durable master", e)
|
||||
}
|
||||
if _, e = p.Exec(ctx, `UPDATE qa_ops_master_records SET payload=jsonb_set(payload,'{answer}','"local edited answer"') WHERE tenant_key=$1 AND id='master-source'`, s.tenant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
wire["answer"] = "changed at source"
|
||||
entry.Payload, _ = json.Marshal(wire)
|
||||
entry.Key.Fingerprint = stringsForMasterFixture("b")
|
||||
source.rows = []dobotaiops.MirrorRecord{entry, keeper}
|
||||
job = claimMirrorJob(t, s, queue, "master-source-update")
|
||||
if e = s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if err := queue.Complete(ctx, job.ID, job.LeaseOwner, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page, e = s.ListMasterRecords(ctx, q)
|
||||
if e != nil || page.Items[0].Answer != "local edited answer" {
|
||||
t.Fatal("source refresh overwrote master edits", e)
|
||||
}
|
||||
source.rows = []dobotaiops.MirrorRecord{keeper}
|
||||
job = claimMirrorJob(t, s, queue, "master-source-delete")
|
||||
if e = s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if err := queue.Complete(ctx, job.ID, job.LeaseOwner, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
page, e = s.ListMasterRecords(ctx, q)
|
||||
if e != nil || page.Total != 1 || page.Items[0].Answer != "local edited answer" {
|
||||
t.Fatal("source deletion removed local master content", e)
|
||||
}
|
||||
if _, e = p.Exec(ctx, `UPDATE qa_ops_mirror_state SET ready=false,blocked=true WHERE tenant_key=$1`, s.tenant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
page, e = s.ListMasterRecords(ctx, q)
|
||||
if e != nil || page.Total != 1 {
|
||||
t.Fatal("source availability blocked independent master data", e)
|
||||
}
|
||||
if _, e = p.Exec(ctx, `UPDATE qa_ops_master_records SET payload=jsonb_set(payload,'{id}','"relabelled-id"') WHERE tenant_key=$1 AND id='master-source'`, s.tenant); e == nil {
|
||||
t.Fatal("master payload ID was allowed to diverge from the stable master ID")
|
||||
}
|
||||
}
|
||||
func stringsForMasterFixture(s string) string {
|
||||
out := ""
|
||||
for i := 0; i < 64; i++ {
|
||||
out += s
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMasterHumanReviewIsIndependentOfSourceInputUpdates(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
s := NewStore(p, "fixture-master-quality")
|
||||
queue := pg.NewStore(p)
|
||||
source := &fixtureSource{rows: []dobotaiops.MirrorRecord{fixtureEntry("master-review", "first")}}
|
||||
job := claimMirrorJob(t, s, queue, "review-first")
|
||||
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, "master-review")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
quality := s.MasterQualityStore()
|
||||
key := []dobotaiops.QualityKey{{ID: rec.ID, InputHash: rec.QualityInputHash}}
|
||||
views, e := quality.ReadViews(ctx, key)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
v := views[rec.ID]
|
||||
request := qaopsquality.SaveRequest{InputHash: v.InputHash, InputEpoch: v.InputEpoch, BaseRevision: v.Revision, Nonce: "fixture_master_review_001", Reason: "fixture only", Fields: qaopsquality.Fields{Coverage: "covered", Correctness: "correct", ProductCategory: "fixture-local"}}
|
||||
if _, e = quality.Save(ctx, rec, request, "fixture-admin"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
source.rows = []dobotaiops.MirrorRecord{fixtureEntry("master-review", "changed at source")}
|
||||
job = claimMirrorJob(t, s, queue, "review-source-change")
|
||||
if e = s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
views, e = quality.ReadViews(ctx, key)
|
||||
if e != nil || views[rec.ID].State != "reviewed" || views[rec.ID].Effective.ProductCategory != "fixture-local" {
|
||||
t.Fatal("source sync invalidated a locally-owned master review", e)
|
||||
}
|
||||
current, e := qaopsquality.NewStore(p, s.tenant).ReadViews(ctx, []dobotaiops.QualityKey{{ID: rec.ID, InputHash: sourceRecordHash(t, source.rows[0])}})
|
||||
if e != nil || current[rec.ID].Revision != 0 {
|
||||
t.Fatal("master review modified original source evaluation", e)
|
||||
}
|
||||
}
|
||||
func sourceRecordHash(t *testing.T, r dobotaiops.MirrorRecord) string {
|
||||
t.Helper()
|
||||
v, e := dobotaiops.DecodeMirrorPayload(string(r.Payload))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return v.QualityInputHash
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package qaopsmirror
|
||||
|
||||
import "knowledge-governance/internal/dobotaiops"
|
||||
|
||||
// The complete fixed-column UI does not need to repeatedly decompress every
|
||||
// large answer on every page just to rediscover which headings exist. Exact
|
||||
// marker/source evidence was committed atomically with each mirror payload.
|
||||
const localMetadataBase = `WITH records AS (SELECT m.id,m.asked_at,m.question,m.identity,m.quality_hash,COALESCE(c.result->>'verdict'='uncovered',false) AS marker,COALESCE(c.source,'{}'::jsonb) AS source_coverage FROM qa_ops_mirror_records m LEFT JOIN qa_ops_quality_records h ON h.tenant_key=m.tenant_key AND h.record_id=m.id AND h.input_hash=m.quality_hash LEFT JOIN qa_ops_quality_checks c ON c.tenant_key=h.tenant_key AND c.record_id=h.record_id AND c.input_epoch=h.input_epoch AND c.rule_version='` + dobotaiops.CoverageRuleVersion + `' WHERE m.tenant_key=$1)`
|
||||
const localSummarySQL = localMetadataBase + ` SELECT count(*),'{}'::text,COALESCE(jsonb_agg(DISTINCT identity),'[]'::jsonb)::text,COALESCE(jsonb_agg(jsonb_build_object('id',id,'input_hash',quality_hash,'marker',marker,'source',source_coverage)),'[]'::jsonb)::text FROM records WHERE $5::text IS NOT NULL AND `
|
||||
const localQualityScopeSQL = localMetadataBase + ` SELECT id,quality_hash,marker,source_coverage::text FROM records WHERE $5::text IS NOT NULL AND `
|
||||
@@ -0,0 +1,39 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLocalMirrorSchedulerRecoversExhaustedCrash(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
s := NewStore(p, "fixture-crashed-scheduler")
|
||||
q := pg.NewStore(p)
|
||||
ctx := context.Background()
|
||||
if _, e := q.Claim(ctx, "fixture-crashed-worker", []string{s.SyncJobType()}, time.Now(), time.Minute); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := p.Exec(ctx, `INSERT INTO qa_ops_mirror_state(tenant_key,next_sync_at) VALUES($1,now()-interval '1 hour')`, s.tenant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if yes, e := s.EnqueueDue(ctx); e != nil || !yes {
|
||||
t.Fatal(e)
|
||||
}
|
||||
job, e := q.Claim(ctx, "fixture-crashed-worker", []string{s.SyncJobType()}, time.Now(), time.Minute)
|
||||
if e != nil || job == nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// Model death after claiming the final attempt, before any failure checkpoint.
|
||||
if _, e = p.Exec(ctx, `UPDATE jobs SET attempt=max_attempts,lease_until=now()-interval '1 second' WHERE id=$1`, job.ID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.EnqueueDue(ctx); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
state, e := s.GetSyncStatus(ctx)
|
||||
if e != nil || state.NextSyncAt == nil || !state.NextSyncAt.After(time.Now()) || state.ErrorCode != "mirror_sync_interrupted" {
|
||||
t.Fatal("scheduler replayed an exhausted operation forever instead of persisting a new retry due time", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
// Package qaopsmirror serves an explicitly synchronized local copy, never an implicit source fallback.
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func NewStore(pool *pgxpool.Pool, tenant string) *Store { return &Store{pool: pool, tenant: tenant} }
|
||||
|
||||
type Status struct {
|
||||
Mode string `json:"mode"`
|
||||
Ready bool `json:"ready"`
|
||||
Blocked bool `json:"blocked"`
|
||||
Revision int64 `json:"revision"`
|
||||
Records int64 `json:"records"`
|
||||
SourceObservedAt *time.Time `json:"source_observed_at"`
|
||||
LastSuccessAt *time.Time `json:"last_success_at"`
|
||||
NextSyncAt *time.Time `json:"next_sync_at"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
IntervalSeconds int `json:"interval_seconds"`
|
||||
WorkerReady bool `json:"worker_ready"`
|
||||
Job *SyncJob `json:"job"`
|
||||
Safety dobotaiops.SourceSafety `json:"-"`
|
||||
}
|
||||
type SyncJob struct {
|
||||
ID string `json:"id"`
|
||||
State string `json:"state"`
|
||||
Loaded int `json:"loaded"`
|
||||
Expected int `json:"expected"`
|
||||
Changed int `json:"changed"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
}
|
||||
|
||||
func (s *Store) valid() bool {
|
||||
return s != nil && s.pool != nil && strings.TrimSpace(s.tenant) == s.tenant && len(s.tenant) > 0 && len(s.tenant) <= 128 && !strings.ContainsRune(s.tenant, 0)
|
||||
}
|
||||
func (s *Store) readState(ctx context.Context, q dobotaiops.RecordQuerier) (Status, error) {
|
||||
out := Status{Mode: "local", IntervalSeconds: int(Interval / time.Second)}
|
||||
var safety []byte
|
||||
err := q.QueryRow(ctx, `SELECT ready,blocked,revision,record_count,source_observed_at,synced_at,next_sync_at,last_error,source_safety FROM qa_ops_mirror_state WHERE tenant_key=$1`, s.tenant).Scan(&out.Ready, &out.Blocked, &out.Revision, &out.Records, &out.SourceObservedAt, &out.LastSuccessAt, &out.NextSyncAt, &out.ErrorCode, &safety)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
out.ErrorCode = "initial_sync_pending"
|
||||
return out, nil
|
||||
}
|
||||
if err != nil || json.Unmarshal(safety, &out.Safety) != nil {
|
||||
return Status{}, dobotaiops.ErrUnavailable
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.safety = out.Safety
|
||||
s.mu.Unlock()
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type txQuery struct{ pgx.Tx }
|
||||
|
||||
func (q txQuery) QueryRow(ctx context.Context, sql string, args ...any) dobotaiops.RecordRow {
|
||||
return q.Tx.QueryRow(ctx, sql, args...)
|
||||
}
|
||||
|
||||
type poolQuery struct{ *pgxpool.Pool }
|
||||
|
||||
func (q poolQuery) QueryRow(ctx context.Context, sql string, args ...any) dobotaiops.RecordRow {
|
||||
return q.Pool.QueryRow(ctx, sql, args...)
|
||||
}
|
||||
func (s *Store) Available(ctx context.Context) error {
|
||||
if !s.valid() {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
state, e := s.readState(ctx, poolQuery{s.pool})
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if state.Blocked {
|
||||
return dobotaiops.ErrNotReadOnly
|
||||
}
|
||||
if !state.Ready {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) Safety() dobotaiops.SourceSafety { s.mu.RLock(); defer s.mu.RUnlock(); return s.safety }
|
||||
func (s *Store) repository(revision *int64) *dobotaiops.RecordsRepository {
|
||||
return s.repositoryFor(revision, false)
|
||||
}
|
||||
func (s *Store) repositoryFor(revision *int64, master bool) *dobotaiops.RecordsRepository {
|
||||
base, summary, scope := localBaseSQL, localSummarySQL, localQualityScopeSQL
|
||||
if master {
|
||||
base, summary, scope = masterBaseSQL, masterSummarySQL, masterQualityScopeSQL
|
||||
}
|
||||
return dobotaiops.NewRecordsRepository(dobotaiops.RecordsRepositoryOptions{
|
||||
BaseSQL: base, SummarySQL: summary, QualityScopeSQL: scope, TenantKey: s.tenant,
|
||||
ValidateWindow: func(w dobotaiops.Window) error {
|
||||
if w.TenantKey != s.tenant {
|
||||
return dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
_, e := dobotaiops.NewWindow(w.TenantKey, w.Start.Format(time.RFC3339Nano), w.End.Format(time.RFC3339Nano), 90*24*time.Hour, time.Now())
|
||||
return e
|
||||
},
|
||||
ReadAsOf: func(ctx context.Context, q dobotaiops.RecordQuerier, t *time.Time) error {
|
||||
if master {
|
||||
return q.QueryRow(ctx, `SELECT updated_at FROM qa_ops_master_state WHERE tenant_key=$1`, s.tenant).Scan(t)
|
||||
}
|
||||
return q.QueryRow(ctx, `SELECT source_observed_at FROM qa_ops_mirror_state WHERE tenant_key=$1`, s.tenant).Scan(t)
|
||||
},
|
||||
Transaction: func(ctx context.Context, fn func(context.Context, dobotaiops.RecordQuerier) error) error {
|
||||
if !s.valid() {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
defer cancel()
|
||||
tx, e := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||
if e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
q := txQuery{tx}
|
||||
if master {
|
||||
if revision != nil {
|
||||
if e = q.QueryRow(ctx, `SELECT COALESCE((SELECT revision FROM qa_ops_master_state WHERE tenant_key=$1),0)`, s.tenant).Scan(revision); e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
}
|
||||
} else {
|
||||
state, err := s.readState(ctx, q)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if state.Blocked {
|
||||
return dobotaiops.ErrNotReadOnly
|
||||
}
|
||||
if !state.Ready {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
if revision != nil {
|
||||
*revision = state.Revision
|
||||
}
|
||||
}
|
||||
if e = fn(ctx, q); e != nil {
|
||||
return e
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
},
|
||||
})
|
||||
}
|
||||
func (s *Store) ListRecords(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
var rev int64
|
||||
p, e := s.repository(&rev).ListRecords(ctx, q)
|
||||
p.LocalRevision = rev
|
||||
p.Columns = []string{"question_chinese", "answer", "coverage", "is_correct", "product_category", "problem_type", "root_cause", "asked_at", "asker", "question", "language", "trigger_person", "department", "region", "feedback"}
|
||||
return p, e
|
||||
}
|
||||
func (s *Store) GetRecord(ctx context.Context, tenant, id string) (dobotaiops.Record, error) {
|
||||
return s.repository(nil).GetRecord(ctx, tenant, id)
|
||||
}
|
||||
func (s *Store) ReadUsageGroups(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.UsageGroups, error) {
|
||||
return s.repository(nil).ReadUsageGroups(ctx, q)
|
||||
}
|
||||
func (s *Store) ReadQualityScope(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.QualityScope, error) {
|
||||
return s.repository(nil).ReadQualityScope(ctx, q)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func mirrorFixture(t *testing.T) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("KG_QAOPS_MIRROR_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("explicit disposable mirror database required")
|
||||
}
|
||||
u, e := url.Parse(dsn)
|
||||
if e != nil || u.Hostname() != "127.0.0.1" || !strings.HasPrefix(u.Path, "/kg_qaops_mirror_test_") || os.Getenv("KG_QAOPS_MIRROR_TEST_ISOLATED") != "1" {
|
||||
t.Fatal("refusing shared mirror database")
|
||||
}
|
||||
p, e := pgxpool.New(context.Background(), dsn)
|
||||
if e != nil {
|
||||
t.Fatal("fixture connection failed")
|
||||
}
|
||||
t.Cleanup(p.Close)
|
||||
if e = pg.ApplyMigrations(context.Background(), p); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return p
|
||||
}
|
||||
func TestLocalMirrorQueriesNeverRequireSource(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
s := NewStore(p, "fixture-mirror")
|
||||
if s.Available(ctx) == nil {
|
||||
t.Fatal("an unsynchronized mirror pretended to be empty/ready")
|
||||
}
|
||||
asked := time.Now().UTC().Add(-time.Hour).Truncate(time.Second)
|
||||
wire := map[string]any{"id": "fixture-one", "status": "succeeded", "question": "literal 100%_ question", "answer": "# local answer\n暂无已发布", "asked_at": asked, "time_source": "turn.created_at", "asker": "fixture name", "trigger_person": "", "department": "", "region": "", "references": []any{}, "media": []any{}, "source_coverage": map[string]string{"verdict": "covered", "reason_code": "", "evaluator_version": "v5"}, "feedback": map[string]any{"asker_value": "up", "up": 1, "down": 0}, "_identity": map[string]string{"actor_id": "actor1", "staff_id": "staff1", "union_id": ""}, "_quality_hash": strings.Repeat("a", 64), "_quality_observed_at": time.Now().UTC()}
|
||||
raw, _ := json.Marshal(wire)
|
||||
if _, e := p.Exec(ctx, `INSERT INTO qa_ops_mirror_state(tenant_key,ready,revision,record_count,source_observed_at,synced_at) VALUES($1,true,1,1,now(),now())`, s.tenant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := p.Exec(ctx, `INSERT INTO qa_ops_mirror_records(tenant_key,id,fingerprint,asked_at,question,status,identity,quality_hash,payload) VALUES($1,'fixture-one',$2,$3,$4,'succeeded',$5,$2,$6)`, s.tenant, strings.Repeat("a", 64), asked, wire["question"], `{"actor_id":"actor1","staff_id":"staff1","union_id":""}`, raw); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// No source client or source credentials have been constructed anywhere in this test.
|
||||
if e := s.Available(ctx); e != nil {
|
||||
t.Fatal("local serving still requires a remote source", e)
|
||||
}
|
||||
q := dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: asked.Add(-time.Minute), End: asked.Add(time.Minute)}, Keyword: "100%_", Limit: 1}
|
||||
page, e := s.ListRecords(ctx, q)
|
||||
if e != nil || page.Total != 1 || len(page.Items) != 1 || page.Items[0].Answer != wire["answer"] {
|
||||
t.Fatal("local fixed-tenant literal query failed", e, page.Total)
|
||||
}
|
||||
if page.Items[0].Identity.StaffID != "staff1" || page.Items[0].Coverage.Verdict != "uncovered" {
|
||||
t.Fatal("local copy lost source identity or deterministic rule")
|
||||
}
|
||||
out, _ := json.Marshal(page)
|
||||
if strings.Contains(string(out), "staff1") || strings.Contains(string(out), "_identity") {
|
||||
t.Fatal("private identity leaked to browser")
|
||||
}
|
||||
got, e := s.GetRecord(ctx, s.tenant, "fixture-one")
|
||||
if e != nil || got.Answer != wire["answer"] {
|
||||
t.Fatal("detail is not served from local data", e)
|
||||
}
|
||||
if _, e = s.GetRecord(ctx, "other-tenant", "fixture-one"); !errors.Is(e, dobotaiops.ErrInvalidQuery) {
|
||||
t.Fatal("cross-tenant detail was not rejected", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
)
|
||||
|
||||
// Payload activation observes quality atomically. Browser reads must not repeat
|
||||
// per-record write transactions; mismatched inputs fail closed in ReadViews.
|
||||
func (s *Store) ReadStoredQuality(ctx context.Context, keys []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
|
||||
return qaopsquality.NewStore(s.pool, s.tenant).ReadViews(ctx, keys)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLocalMirrorMetadataDoesNotReadLargeAnswerPayload(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
tenant := "fixture-metadata-acl"
|
||||
record := dobotaiops.Record{ID: "metadata-one", Question: "fixture", Answer: "暂无已发布", QualityObservedAt: time.Now()}
|
||||
views, e := qaopsquality.NewStore(p, tenant).Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
hash := views[record.ID].InputHash
|
||||
if _, e = p.Exec(ctx, `INSERT INTO qa_ops_mirror_state(tenant_key,ready,revision,record_count,source_observed_at,synced_at) VALUES($1,true,1,1,now(),now());`, tenant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = p.Exec(ctx, `INSERT INTO qa_ops_mirror_records(tenant_key,id,fingerprint,asked_at,question,status,identity,quality_hash,payload) VALUES($1,$2,$3,now()-interval '1 hour','fixture','succeeded','{}',$3,jsonb_build_object('id',$2::text))`, tenant, record.ID, hash); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
role := fmt.Sprintf("kg_mirror_metadata_%d", time.Now().UnixNano())
|
||||
if _, e = p.Exec(ctx, "CREATE ROLE "+role+" NOLOGIN"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer func() { p.Exec(ctx, "DROP OWNED BY "+role); p.Exec(ctx, "DROP ROLE "+role) }()
|
||||
if _, e = p.Exec(ctx, "GRANT SELECT(tenant_key,id,fingerprint,asked_at,question,status,identity,quality_hash) ON qa_ops_mirror_records TO "+role+";GRANT SELECT(tenant_key,id,asked_at,question,status,identity,quality_hash) ON qa_ops_master_records TO "+role+";GRANT SELECT ON qa_ops_master_state,qa_ops_mirror_state,qa_ops_quality_records,qa_ops_quality_inputs,qa_ops_quality_checks TO "+role); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
config := p.Config().Copy()
|
||||
config.AfterConnect = func(ctx context.Context, c *pgx.Conn) error { _, e := c.Exec(ctx, "SET ROLE "+role); return e }
|
||||
limited, e := pgxpool.NewWithConfig(ctx, config)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer limited.Close()
|
||||
scope, e := NewStore(limited, tenant).ReadQualityScope(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: tenant, Start: time.Now().Add(-2 * time.Hour), End: time.Now()}, Limit: 100})
|
||||
if e != nil || len(scope.Keys) != 1 || !scope.Keys[0].Marker {
|
||||
t.Fatal("local metadata still requires SELECT on large payload instead of committed quality evidence", e)
|
||||
}
|
||||
scope, e = NewStore(limited, tenant).ReadMasterQualityScope(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: tenant, Start: time.Now().Add(-2 * time.Hour), End: time.Now()}, Limit: 100})
|
||||
if e != nil || len(scope.Keys) != 1 || !scope.Keys[0].Marker {
|
||||
t.Fatal("master metadata requires forbidden payload access or lost copied coverage evidence", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalMirrorStoredQualityUsesReadOnlyBatchedProjection(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
tenant := "fixture-read-stored"
|
||||
record := dobotaiops.Record{ID: "stored-one", Question: "fixture question", Answer: "暂无已发布", QualityObservedAt: time.Now()}
|
||||
views, e := qaopsquality.NewStore(p, tenant).Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
hash := views[record.ID].InputHash
|
||||
config := p.Config().Copy()
|
||||
config.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
|
||||
readonly, e := pgxpool.NewWithConfig(ctx, config)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer readonly.Close()
|
||||
store := NewStore(readonly, tenant)
|
||||
keys := []dobotaiops.QualityKey{{ID: record.ID, InputHash: hash}}
|
||||
got, e := store.ReadStoredQuality(ctx, keys)
|
||||
if e != nil || len(got) != 1 || got[record.ID].InputHash != hash {
|
||||
t.Fatal("synchronized quality must be readable without any write transaction", e)
|
||||
}
|
||||
keys[0].InputHash = strings.Repeat("f", 64)
|
||||
if _, e = store.ReadStoredQuality(ctx, keys); !errors.Is(e, qaopsquality.ErrConflict) {
|
||||
t.Fatal("stale mirror input paired with newer quality", e)
|
||||
}
|
||||
if _, e = NewStore(readonly, "other-tenant").ReadStoredQuality(ctx, []dobotaiops.QualityKey{{ID: record.ID, InputHash: hash}}); e == nil {
|
||||
t.Fatal("stored quality crossed tenant scope")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/jobs"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const SyncJobPrefix = "qaops.records.sync."
|
||||
|
||||
func (s *Store) EnqueueDue(ctx context.Context) (bool, error) {
|
||||
if !s.valid() {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
// A final-attempt process can die before recordFailure. Rotate the persisted
|
||||
// due time once, otherwise ExecuteOperation would replay its dead receipt forever.
|
||||
if _, e := s.pool.Exec(ctx, `WITH latest AS (SELECT state,attempt,max_attempts,lease_until,updated_at FROM jobs WHERE type=$2 ORDER BY created_at DESC,id DESC LIMIT 1) UPDATE qa_ops_mirror_state s SET next_sync_at=clock_timestamp()+interval '5 minutes',last_error='mirror_sync_interrupted' FROM latest j WHERE s.tenant_key=$1 AND s.next_sync_at<=j.updated_at AND(j.state='failed' OR(j.state='running' AND j.attempt>=j.max_attempts AND j.lease_until<clock_timestamp()))`, s.tenant, s.SyncJobType()); e != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
var next time.Time
|
||||
var due bool
|
||||
e := s.pool.QueryRow(ctx, `SELECT next_sync_at,next_sync_at<=clock_timestamp() FROM qa_ops_mirror_state WHERE tenant_key=$1`, s.tenant).Scan(&next, &due)
|
||||
if e != nil && !errors.Is(e, pgx.ErrNoRows) {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if e == nil && !due {
|
||||
return false, nil
|
||||
}
|
||||
key := "automatic:initial"
|
||||
if !next.IsZero() {
|
||||
key = "automatic:" + next.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
receipt, replayed, e := s.EnqueueSync(ctx, key, "system:qa-record-sync")
|
||||
return e == nil && !replayed && !receipt.Deduplicated, e
|
||||
}
|
||||
|
||||
var ErrWorkerUnavailable = errors.New("local mirror worker is unavailable")
|
||||
var ErrInvalid = errors.New("invalid local mirror request")
|
||||
var ErrConflict = errors.New("local mirror request conflict")
|
||||
var ErrLease = errors.New("local mirror lease lost")
|
||||
var ErrSync = errors.New("local mirror source synchronization failed; last committed data retained")
|
||||
|
||||
type SyncReceipt struct {
|
||||
JobID string `json:"job_id"`
|
||||
Deduplicated bool `json:"deduplicated"`
|
||||
}
|
||||
|
||||
func (s *Store) SyncJobType() string {
|
||||
h := sha256.Sum256([]byte(s.tenant))
|
||||
return SyncJobPrefix + hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
const workerReadySQL = `SELECT EXISTS(SELECT 1 FROM worker_heartbeats WHERE $1=ANY(string_to_array(job_types,',')) AND last_seen_at>clock_timestamp()-interval '2 minutes') OR EXISTS(SELECT 1 FROM jobs WHERE type=$1 AND state='running' AND lease_until>clock_timestamp())`
|
||||
|
||||
func validToken(v string, n int) bool {
|
||||
return strings.TrimSpace(v) == v && len(v) > 0 && len(v) <= n && utf8.ValidString(v) && !strings.ContainsRune(v, 0)
|
||||
}
|
||||
func (s *Store) EnqueueSync(ctx context.Context, key, actor string) (SyncReceipt, bool, error) {
|
||||
if !s.valid() {
|
||||
return SyncReceipt{}, false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if !validToken(key, 128) || !validToken(actor, 256) {
|
||||
return SyncReceipt{}, false, ErrInvalid
|
||||
}
|
||||
fp := sha256.Sum256([]byte(actor))
|
||||
now := time.Now()
|
||||
raw, replay, err := pg.NewStore(s.pool).ExecuteOperation(ctx, s.SyncJobType(), key, hex.EncodeToString(fp[:]), now, func(tx pgx.Tx) (json.RawMessage, error) {
|
||||
if _, e := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, s.SyncJobType()); e != nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if _, e := tx.Exec(ctx, `UPDATE jobs SET state='failed',last_error='local mirror worker interrupted',last_error_code='mirror_sync_interrupted',lease_owner=NULL,lease_until=NULL,updated_at=now() WHERE type=$1 AND state='running' AND lease_until<clock_timestamp() AND attempt>=max_attempts`, s.SyncJobType()); e != nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
var active string
|
||||
e := tx.QueryRow(ctx, `SELECT id FROM jobs WHERE type=$1 AND state IN ('pending','running','retry') ORDER BY created_at DESC,id DESC LIMIT 1`, s.SyncJobType()).Scan(&active)
|
||||
if e == nil {
|
||||
return json.Marshal(SyncReceipt{JobID: active, Deduplicated: true})
|
||||
}
|
||||
if !errors.Is(e, pgx.ErrNoRows) {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
var ready bool
|
||||
if tx.QueryRow(ctx, workerReadySQL, s.SyncJobType()).Scan(&ready) != nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if !ready {
|
||||
return nil, ErrWorkerUnavailable
|
||||
}
|
||||
if _, e = tx.Exec(ctx, `INSERT INTO qa_ops_mirror_state(tenant_key) VALUES($1) ON CONFLICT DO NOTHING`, s.tenant); e != nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
h := sha256.Sum256([]byte(s.SyncJobType() + ":" + key))
|
||||
payload, _ := json.Marshal(map[string]string{"triggered_by": actor})
|
||||
job, e := pg.NewStore(tx).Enqueue(ctx, jobs.EnqueueRequest{ID: "job-" + hex.EncodeToString(h[:16]), Type: s.SyncJobType(), Payload: payload, AvailableAt: now, MaxAttempts: 3, IdempotencyKey: s.SyncJobType() + ":" + key}, now)
|
||||
if e != nil || job == nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
return json.Marshal(SyncReceipt{JobID: job.ID})
|
||||
})
|
||||
if errors.Is(err, pg.ErrOperationRequestConflict) {
|
||||
return SyncReceipt{}, false, ErrConflict
|
||||
}
|
||||
if err != nil {
|
||||
return SyncReceipt{}, false, err
|
||||
}
|
||||
var receipt SyncReceipt
|
||||
if json.Unmarshal(raw, &receipt) != nil || receipt.JobID == "" {
|
||||
return receipt, false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
return receipt, replay, nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLocalMirrorDurableQueueCoalescesAndAudits(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
s := NewStore(p, "fixture-queue")
|
||||
q := pg.NewStore(p)
|
||||
ctx := context.Background()
|
||||
if _, _, e := s.EnqueueSync(ctx, "fixture-no-worker", "fixture-admin"); !errors.Is(e, ErrWorkerUnavailable) {
|
||||
t.Fatal("offline worker accepted work", e)
|
||||
}
|
||||
if _, e := q.Claim(ctx, "fixture-worker", []string{s.SyncJobType()}, time.Now(), time.Minute); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
ids := make(chan string, 8)
|
||||
errs := make(chan error, 8)
|
||||
for range 8 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
r, _, e := s.EnqueueSync(ctx, "fixture-same-action", "fixture-admin")
|
||||
if e != nil {
|
||||
errs <- e
|
||||
return
|
||||
}
|
||||
ids <- r.JobID
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
close(ids)
|
||||
for e := range errs {
|
||||
t.Fatal("durable enqueue failed", e)
|
||||
}
|
||||
id := ""
|
||||
n := 0
|
||||
for got := range ids {
|
||||
if got == "" || id != "" && got != id {
|
||||
t.Fatal("same action created different effects")
|
||||
}
|
||||
id = got
|
||||
n++
|
||||
}
|
||||
if n != 8 {
|
||||
t.Fatal("lost enqueue results")
|
||||
}
|
||||
again, _, e := s.EnqueueSync(ctx, "fixture-another-click", "fixture-admin")
|
||||
if e != nil || !again.Deduplicated || again.JobID != id {
|
||||
t.Fatal("in-flight synchronization did not coalesce", e)
|
||||
}
|
||||
if _, _, e = s.EnqueueSync(ctx, "fixture-same-action", "different-admin"); !errors.Is(e, ErrConflict) {
|
||||
t.Fatal("replay changed actor", e)
|
||||
}
|
||||
var count int
|
||||
if p.QueryRow(ctx, `SELECT count(*) FROM jobs WHERE type=$1`, s.SyncJobType()).Scan(&count) != nil || count != 1 {
|
||||
t.Fatal("duplicate jobs")
|
||||
}
|
||||
job, e := q.Claim(ctx, "fixture-worker", []string{s.SyncJobType()}, time.Now(), time.Minute)
|
||||
if e != nil || job == nil || job.ID != id {
|
||||
t.Fatal("job not durable", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"regexp"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Source interface {
|
||||
ReadMirrorManifest(context.Context, string) (dobotaiops.MirrorManifest, error)
|
||||
ReadMirrorRecords(context.Context, string, []string) ([]dobotaiops.MirrorRecord, error)
|
||||
}
|
||||
type SourceFactory func(context.Context) (Source, error)
|
||||
|
||||
var hashPattern = regexp.MustCompile(`^[a-f0-9]{64}$`)
|
||||
|
||||
func (s *Store) lease(ctx context.Context, q dobotaiops.RecordQuerier, j jobs.Job, lock bool) (bool, error) {
|
||||
if j.Type != s.SyncJobType() || j.LeaseOwner == "" {
|
||||
return false, ErrLease
|
||||
}
|
||||
sql := `SELECT payload ? 'mirror_result' FROM jobs WHERE id=$1 AND type=$2 AND state='running' AND lease_owner=$3 AND attempt=$4 AND lease_until>clock_timestamp() AND EXISTS(SELECT 1 FROM operation_requests op WHERE op.operation_type=jobs.type AND op.result->>'job_id'=jobs.id)`
|
||||
if lock {
|
||||
sql += " FOR UPDATE"
|
||||
}
|
||||
var done bool
|
||||
if q.QueryRow(ctx, sql, j.ID, s.SyncJobType(), j.LeaseOwner, j.Attempt).Scan(&done) != nil {
|
||||
return false, ErrLease
|
||||
}
|
||||
return done, nil
|
||||
}
|
||||
func (s *Store) progress(ctx context.Context, j jobs.Job, loaded, expected, changed int) error {
|
||||
p, _ := json.Marshal(map[string]int{"loaded": loaded, "expected": expected, "changed": changed})
|
||||
tag, e := s.pool.Exec(ctx, `UPDATE jobs SET payload=jsonb_set(payload,'{mirror_progress}',$5::jsonb),updated_at=now() WHERE id=$1 AND type=$2 AND lease_owner=$3 AND attempt=$4 AND state='running' AND lease_until>clock_timestamp()`, j.ID, s.SyncJobType(), j.LeaseOwner, j.Attempt, p)
|
||||
if e != nil || tag.RowsAffected() != 1 {
|
||||
return ErrLease
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) recordFailure(j jobs.Job, cause error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
code := "mirror_source_unavailable"
|
||||
blocked := errors.Is(cause, dobotaiops.ErrNotReadOnly)
|
||||
if blocked {
|
||||
code = "mirror_source_authorization_failed"
|
||||
}
|
||||
_, _ = s.pool.Exec(ctx, `UPDATE qa_ops_mirror_state SET last_error=$2,blocked=blocked OR $3,next_sync_at=clock_timestamp()+interval '5 minutes' WHERE tenant_key=$1 AND EXISTS(SELECT 1 FROM jobs WHERE id=$4 AND type=$5 AND state='running' AND lease_owner=$6 AND attempt=$7 AND lease_until>clock_timestamp())`, s.tenant, code, blocked, j.ID, s.SyncJobType(), j.LeaseOwner, j.Attempt)
|
||||
}
|
||||
func (s *Store) HandleSync(ctx context.Context, j jobs.Job, factory SourceFactory) (err error) {
|
||||
if !s.valid() || factory == nil {
|
||||
return ErrSync
|
||||
}
|
||||
done, e := s.lease(ctx, poolQuery{s.pool}, j, false)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if done {
|
||||
return nil
|
||||
}
|
||||
defer func() {
|
||||
if err != nil && !errors.Is(err, ErrLease) {
|
||||
s.recordFailure(j, err)
|
||||
if errors.Is(err, dobotaiops.ErrNotReadOnly) {
|
||||
err = jobs.Permanent("mirror_source_authorization_failed", ErrSync)
|
||||
} else {
|
||||
err = ErrSync
|
||||
}
|
||||
}
|
||||
}()
|
||||
source, e := factory(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if closer, ok := source.(interface{ Close() }); ok {
|
||||
defer closer.Close()
|
||||
}
|
||||
known := map[string]string{}
|
||||
rows, e := s.pool.Query(ctx, `SELECT id,fingerprint FROM qa_ops_mirror_records WHERE tenant_key=$1`, s.tenant)
|
||||
if e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
for rows.Next() {
|
||||
var id, fp string
|
||||
if rows.Scan(&id, &fp) != nil {
|
||||
rows.Close()
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
known[id] = fp
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
manifest, e := source.ReadMirrorManifest(ctx, s.tenant)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if manifest.AsOf.IsZero() || manifest.AsOf.After(time.Now().Add(5*time.Minute)) || len(manifest.Keys) > dobotaiops.MaxMirrorRecords {
|
||||
return ErrSync
|
||||
}
|
||||
// A sudden completely empty scope is not accepted as authority to erase a populated local history.
|
||||
if len(manifest.Keys) == 0 && len(known) > 0 {
|
||||
return ErrSync
|
||||
}
|
||||
keys := map[string]string{}
|
||||
changed := []string{}
|
||||
ids := make([]string, 0, len(manifest.Keys))
|
||||
for _, k := range manifest.Keys {
|
||||
if !validToken(k.ID, 256) || !hashPattern.MatchString(k.Fingerprint) || keys[k.ID] != "" {
|
||||
return ErrSync
|
||||
}
|
||||
keys[k.ID] = k.Fingerprint
|
||||
ids = append(ids, k.ID)
|
||||
if known[k.ID] != k.Fingerprint {
|
||||
changed = append(changed, k.ID)
|
||||
}
|
||||
}
|
||||
sort.Strings(changed)
|
||||
loaded := len(ids) - len(changed)
|
||||
if e = s.progress(ctx, j, loaded, len(ids), 0); e != nil {
|
||||
return e
|
||||
}
|
||||
collected := make([]dobotaiops.MirrorRecord, 0, len(changed))
|
||||
totalBytes := 0
|
||||
for start := 0; start < len(changed); start += 100 {
|
||||
if _, e = s.lease(ctx, poolQuery{s.pool}, j, false); e != nil {
|
||||
return e
|
||||
}
|
||||
batch := changed[start:min(start+100, len(changed))]
|
||||
got, e := source.ReadMirrorRecords(ctx, s.tenant, batch)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if len(got) != len(batch) {
|
||||
return ErrSync
|
||||
}
|
||||
expected := map[string]bool{}
|
||||
for _, id := range batch {
|
||||
expected[id] = true
|
||||
}
|
||||
for _, row := range got {
|
||||
if !expected[row.Key.ID] || !hashPattern.MatchString(row.Key.Fingerprint) {
|
||||
return ErrSync
|
||||
}
|
||||
delete(expected, row.Key.ID)
|
||||
record, e := dobotaiops.DecodeMirrorPayload(string(row.Payload))
|
||||
if e != nil || record.ID != row.Key.ID || !hashPattern.MatchString(record.QualityInputHash) || record.QualityObservedAt.IsZero() || record.AskedAt.IsZero() || len(row.Payload) > 8<<20 {
|
||||
return ErrSync
|
||||
}
|
||||
totalBytes += len(row.Payload)
|
||||
if totalBytes > 256<<20 {
|
||||
return ErrSync
|
||||
}
|
||||
// A row can complete between manifest and payload reads. Keep that newer full
|
||||
// row, never store an old manifest hash against a different current payload.
|
||||
keys[row.Key.ID] = row.Key.Fingerprint
|
||||
if record.QualityObservedAt.After(manifest.AsOf) {
|
||||
manifest.AsOf = record.QualityObservedAt
|
||||
}
|
||||
collected = append(collected, row)
|
||||
}
|
||||
loaded += len(got)
|
||||
if e = s.progress(ctx, j, loaded, len(ids), len(collected)); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return s.activate(ctx, j, manifest, ids, known, collected)
|
||||
}
|
||||
func (s *Store) activate(ctx context.Context, j jobs.Job, m dobotaiops.MirrorManifest, ids []string, known map[string]string, rows []dobotaiops.MirrorRecord) error {
|
||||
tx, e := s.pool.Begin(ctx)
|
||||
if e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
if _, e = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, s.SyncJobType()); e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
done, e := s.lease(ctx, txQuery{tx}, j, true)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if done {
|
||||
return nil
|
||||
}
|
||||
quality := qaopsquality.NewStore(s.pool, s.tenant)
|
||||
for start := 0; start < len(rows); start += 100 {
|
||||
batch := rows[start:min(start+100, len(rows))]
|
||||
records := make([]dobotaiops.Record, 0, len(batch))
|
||||
for _, row := range batch {
|
||||
rec, e := dobotaiops.DecodeMirrorPayload(string(row.Payload))
|
||||
if e != nil {
|
||||
return ErrSync
|
||||
}
|
||||
records = append(records, rec)
|
||||
identity, _ := json.Marshal(rec.Identity)
|
||||
if _, e = tx.Exec(ctx, `INSERT INTO qa_ops_mirror_records(tenant_key,id,fingerprint,asked_at,question,status,identity,quality_hash,payload) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT(tenant_key,id) DO UPDATE SET fingerprint=EXCLUDED.fingerprint,asked_at=EXCLUDED.asked_at,question=EXCLUDED.question,status=EXCLUDED.status,identity=EXCLUDED.identity,quality_hash=EXCLUDED.quality_hash,payload=EXCLUDED.payload`, s.tenant, rec.ID, row.Key.Fingerprint, rec.AskedAt, rec.Question, rec.Status, identity, rec.QualityInputHash, row.Payload); e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
}
|
||||
if e = quality.ObserveRecordsInTx(ctx, tx, records); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
deleted, e := tx.Exec(ctx, `DELETE FROM qa_ops_mirror_records WHERE tenant_key=$1 AND NOT(id=ANY($2::text[]))`, s.tenant, ids)
|
||||
if e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
changed := len(rows) > 0 || deleted.RowsAffected() > 0
|
||||
var revision int64
|
||||
var wasReady bool
|
||||
if tx.QueryRow(ctx, `SELECT revision,ready FROM qa_ops_mirror_state WHERE tenant_key=$1 FOR UPDATE`, s.tenant).Scan(&revision, &wasReady) != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
if changed || !wasReady {
|
||||
revision++
|
||||
}
|
||||
safety, _ := json.Marshal(m.Safety)
|
||||
if _, e = tx.Exec(ctx, `UPDATE qa_ops_mirror_state SET ready=true,blocked=false,revision=$2,record_count=$3,source_observed_at=$4,synced_at=clock_timestamp(),next_sync_at=clock_timestamp()+interval '5 minutes',last_error='',source_safety=$5 WHERE tenant_key=$1`, s.tenant, revision, len(ids), m.AsOf, safety); e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
result, _ := json.Marshal(map[string]any{"records": len(ids), "changed": len(rows), "deleted": deleted.RowsAffected(), "revision": revision})
|
||||
tag, e := tx.Exec(ctx, `UPDATE jobs SET payload=jsonb_set(payload,'{mirror_result}',$5::jsonb),updated_at=now() WHERE id=$1 AND type=$2 AND lease_owner=$3 AND attempt=$4 AND state='running' AND lease_until>clock_timestamp()`, j.ID, s.SyncJobType(), j.LeaseOwner, j.Attempt, result)
|
||||
if e != nil || tag.RowsAffected() != 1 {
|
||||
return ErrLease
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) GetSyncStatus(ctx context.Context) (Status, error) {
|
||||
if !s.valid() {
|
||||
return Status{}, dobotaiops.ErrUnavailable
|
||||
}
|
||||
state, e := s.readState(ctx, poolQuery{s.pool})
|
||||
if e != nil {
|
||||
return state, e
|
||||
}
|
||||
if s.pool.QueryRow(ctx, workerReadySQL, s.SyncJobType()).Scan(&state.WorkerReady) != nil {
|
||||
return Status{}, dobotaiops.ErrUnavailable
|
||||
}
|
||||
var j SyncJob
|
||||
var payload []byte
|
||||
var expired bool
|
||||
var attempt, maxAttempts int
|
||||
e = s.pool.QueryRow(ctx, `SELECT id,state,payload,COALESCE(last_error_code,''),COALESCE(state='running' AND lease_until<clock_timestamp(),false),attempt,max_attempts FROM jobs WHERE type=$1 ORDER BY created_at DESC,id DESC LIMIT 1`, s.SyncJobType()).Scan(&j.ID, &j.State, &payload, &j.ErrorCode, &expired, &attempt, &maxAttempts)
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
return state, nil
|
||||
}
|
||||
if e != nil {
|
||||
return Status{}, dobotaiops.ErrUnavailable
|
||||
}
|
||||
var data struct {
|
||||
Progress struct {
|
||||
Loaded int `json:"loaded"`
|
||||
Expected int `json:"expected"`
|
||||
Changed int `json:"changed"`
|
||||
} `json:"mirror_progress"`
|
||||
}
|
||||
if json.Unmarshal(payload, &data) != nil {
|
||||
return Status{}, dobotaiops.ErrUnavailable
|
||||
}
|
||||
j.Loaded = data.Progress.Loaded
|
||||
j.Expected = data.Progress.Expected
|
||||
j.Changed = data.Progress.Changed
|
||||
if expired {
|
||||
j.State = "retry"
|
||||
if attempt >= maxAttempts {
|
||||
j.State = "failed"
|
||||
}
|
||||
j.ErrorCode = "mirror_sync_interrupted"
|
||||
}
|
||||
state.Job = &j
|
||||
return state, nil
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/jobs"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type fixtureSource struct {
|
||||
rows []dobotaiops.MirrorRecord
|
||||
calls int
|
||||
payloadCalls int
|
||||
err error
|
||||
payloadError error
|
||||
failAfter int
|
||||
hook func()
|
||||
}
|
||||
|
||||
func (f *fixtureSource) ReadMirrorManifest(context.Context, string) (dobotaiops.MirrorManifest, error) {
|
||||
f.calls++
|
||||
m := dobotaiops.MirrorManifest{AsOf: time.Now().UTC(), Safety: dobotaiops.SourceSafety{SSL: true, TablesChecked: 5, ConnectionLimit: 1}}
|
||||
for _, r := range f.rows {
|
||||
m.Keys = append(m.Keys, r.Key)
|
||||
}
|
||||
return m, f.err
|
||||
}
|
||||
func (f *fixtureSource) ReadMirrorRecords(_ context.Context, _ string, ids []string) ([]dobotaiops.MirrorRecord, error) {
|
||||
f.payloadCalls++
|
||||
if f.payloadError != nil && f.payloadCalls >= f.failAfter {
|
||||
return nil, f.payloadError
|
||||
}
|
||||
out := []dobotaiops.MirrorRecord{}
|
||||
for _, id := range ids {
|
||||
for _, r := range f.rows {
|
||||
if r.Key.ID == id {
|
||||
out = append(out, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
if f.hook != nil {
|
||||
f.hook()
|
||||
}
|
||||
return out, f.err
|
||||
}
|
||||
func fixtureEntry(id, answer string) dobotaiops.MirrorRecord {
|
||||
qh := sha256.Sum256([]byte(id + answer))
|
||||
fp := sha256.Sum256([]byte("source:" + id + answer))
|
||||
now := time.Now().UTC()
|
||||
p, _ := json.Marshal(map[string]any{"id": id, "status": "succeeded", "question": "fixture question", "answer": answer, "asked_at": now.Add(-time.Hour), "time_source": "turn.created_at", "asker": "", "trigger_person": "", "department": "", "region": "", "references": []any{}, "media": []any{}, "source_coverage": map[string]string{"verdict": "covered", "reason_code": "", "evaluator_version": "v5"}, "feedback": map[string]any{"asker_value": "", "up": 0, "down": 0}, "_identity": map[string]string{"actor_id": "a", "staff_id": "s", "union_id": ""}, "_quality_hash": hex.EncodeToString(qh[:]), "_quality_observed_at": now})
|
||||
return dobotaiops.MirrorRecord{Key: dobotaiops.MirrorKey{ID: id, Fingerprint: hex.EncodeToString(fp[:])}, Payload: p}
|
||||
}
|
||||
func claimMirrorJob(t *testing.T, s *Store, q *pg.Store, key string) *jobs.Job {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
if _, e := q.Claim(ctx, "fixture-sync-worker", []string{s.SyncJobType()}, time.Now(), time.Minute); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_, _, e := s.EnqueueSync(ctx, key, "fixture-admin")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
j, e := q.Claim(ctx, "fixture-sync-worker", []string{s.SyncJobType()}, time.Now(), time.Minute)
|
||||
if e != nil || j == nil {
|
||||
t.Fatal("missing durable sync job", e)
|
||||
}
|
||||
return j
|
||||
}
|
||||
func TestLocalMirrorPeriodicSyncIsDurableAndDueOnly(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
s := NewStore(p, "fixture-periodic")
|
||||
q := pg.NewStore(p)
|
||||
ctx := context.Background()
|
||||
if _, e := q.Claim(ctx, "fixture-periodic-worker", []string{s.SyncJobType()}, time.Now(), time.Minute); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if enqueued, e := s.EnqueueDue(ctx); e != nil || !enqueued {
|
||||
t.Fatal("first automatic sync was not scheduled", e)
|
||||
}
|
||||
if _, e := s.EnqueueDue(ctx); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var count int
|
||||
if p.QueryRow(ctx, `SELECT count(*) FROM jobs WHERE type=$1`, s.SyncJobType()).Scan(&count) != nil || count != 1 {
|
||||
t.Fatal("scheduler duplicated active job")
|
||||
}
|
||||
job, e := q.Claim(ctx, "fixture-periodic-worker", []string{s.SyncJobType()}, time.Now(), time.Minute)
|
||||
if e != nil || job == nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
source := &fixtureSource{rows: []dobotaiops.MirrorRecord{fixtureEntry("auto-one", "automatic")}}
|
||||
if e = s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = q.Complete(ctx, job.ID, job.LeaseOwner, time.Now()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if enqueued, e := s.EnqueueDue(ctx); e != nil || enqueued {
|
||||
t.Fatal("automatic sync ignored the persisted five-minute interval", e)
|
||||
}
|
||||
if _, e = p.Exec(ctx, `UPDATE qa_ops_mirror_state SET next_sync_at=now()-interval '1 second' WHERE tenant_key=$1`, s.tenant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if enqueued, e := s.EnqueueDue(ctx); e != nil || !enqueued {
|
||||
t.Fatal("due sync did not resume", e)
|
||||
}
|
||||
}
|
||||
func TestLocalMirrorSyncActivatesAndCheckpoints(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
s := NewStore(p, "fixture-sync")
|
||||
q := pg.NewStore(p)
|
||||
ctx := context.Background()
|
||||
job := claimMirrorJob(t, s, q, "fixture-first-sync")
|
||||
source := &fixtureSource{rows: []dobotaiops.MirrorRecord{fixtureEntry("one", "# first answer")}}
|
||||
factory := func(context.Context) (Source, error) { return source, nil }
|
||||
if e := s.HandleSync(ctx, *job, factory); e != nil {
|
||||
t.Fatal("first full sync did not activate", e)
|
||||
}
|
||||
state, e := s.GetSyncStatus(ctx)
|
||||
if e != nil || !state.Ready || state.Records != 1 || state.Revision != 1 || state.LastSuccessAt == nil || state.NextSyncAt == nil || state.NextSyncAt.Sub(*state.LastSuccessAt) < Interval-time.Second {
|
||||
t.Fatal("incomplete local sync state", e, state)
|
||||
}
|
||||
record, e := s.GetRecord(ctx, s.tenant, "one")
|
||||
if e != nil || record.Answer != "# first answer" {
|
||||
t.Fatal("committed local answer missing", e)
|
||||
}
|
||||
var inputs int
|
||||
if p.QueryRow(ctx, `SELECT count(*) FROM qa_ops_quality_inputs WHERE tenant_key=$1 AND payload IS NOT NULL`, s.tenant).Scan(&inputs) != nil || inputs != 1 {
|
||||
t.Fatal("quality evidence did not commit with mirror")
|
||||
}
|
||||
calls := source.calls
|
||||
if e = s.HandleSync(ctx, *job, factory); e != nil || source.calls != calls {
|
||||
t.Fatal("restart after commit fetched source twice", e)
|
||||
}
|
||||
if e = q.Complete(ctx, job.ID, job.LeaseOwner, time.Now()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package qaopsorg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"sort"
|
||||
)
|
||||
|
||||
@@ -39,7 +40,7 @@ func BuildAttribution(state State, directory Directory) (*Attribution, error) {
|
||||
if state.State != "ready" || state.DirectoryID == "" {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
view, err := Preview(directory, state.Rules)
|
||||
view, err := PreviewRegions(directory, state.Rules, state.RegionDefinitions())
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
@@ -65,7 +66,7 @@ func BuildAttribution(state State, directory Directory) (*Attribution, error) {
|
||||
if len(regions) == 1 {
|
||||
item.State = "matched"
|
||||
for region := range regions {
|
||||
item.Region = region
|
||||
item.Region = state.RegionLabel(region)
|
||||
}
|
||||
} else if len(regions) > 1 {
|
||||
item.State = "cross_region"
|
||||
@@ -111,6 +112,16 @@ func (p *Attribution) Resolve(staff, union string) PersonAttribution {
|
||||
}
|
||||
return none
|
||||
}
|
||||
func (s *Store) GetAttributionInTx(ctx context.Context, tx pgx.Tx) (*Attribution, error) {
|
||||
if !s.available() {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
state, directory, err := s.read(ctx, tx, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return BuildAttribution(state, directory)
|
||||
}
|
||||
func (s *Store) GetAttribution(ctx context.Context) (*Attribution, error) {
|
||||
if !s.available() {
|
||||
return nil, ErrUnavailable
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package qaopsorg
|
||||
|
||||
import "unicode/utf8"
|
||||
|
||||
// IDs are immutable mapping keys; names are editable labels. Existing keys remain
|
||||
// intact when migrating the historical four-region configuration.
|
||||
type RegionDefinition struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func DefaultRegions() []RegionDefinition {
|
||||
result := make([]RegionDefinition, 0, len(RegionNames))
|
||||
for _, name := range RegionNames {
|
||||
result = append(result, RegionDefinition{ID: name, Name: name})
|
||||
}
|
||||
return result
|
||||
}
|
||||
func (s State) RegionDefinitions() []RegionDefinition {
|
||||
if s.Regions == nil {
|
||||
return DefaultRegions()
|
||||
}
|
||||
return s.Regions
|
||||
}
|
||||
func (s State) RegionLabels() []string {
|
||||
labels := []string{}
|
||||
for _, region := range s.RegionDefinitions() {
|
||||
labels = append(labels, region.Name)
|
||||
}
|
||||
return labels
|
||||
}
|
||||
func (s State) RegionLabel(id string) string {
|
||||
for _, region := range s.RegionDefinitions() {
|
||||
if region.ID == id {
|
||||
return region.Name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func validRegions(regions []RegionDefinition) bool {
|
||||
if len(regions) > 100 {
|
||||
return false
|
||||
}
|
||||
reserved := map[string]bool{"unassigned": true, "cross_region": true, "unmatched": true, "identity_conflict": true, "no_identity": true, "directory_missing": true, "__proto__": true, "constructor": true, "prototype": true}
|
||||
ids, names := map[string]bool{}, map[string]bool{}
|
||||
for _, region := range regions {
|
||||
if !validID(region.ID) || !validID(region.Name) || !utf8.ValidString(region.ID) || !utf8.ValidString(region.Name) || reserved[region.ID] || reserved[region.Name] || ids[region.ID] || names[region.Name] {
|
||||
return false
|
||||
}
|
||||
ids[region.ID] = true
|
||||
names[region.Name] = true
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCustomRegionCatalogRejectsAmbiguousOrReservedDefinitions(t *testing.T) {
|
||||
for _, regions := range [][]RegionDefinition{
|
||||
{{ID: "one", Name: "国内教育"}, {ID: "one", Name: "国外工业Amercia"}},
|
||||
{{ID: "one", Name: "国内教育"}, {ID: "two", Name: "国内教育"}},
|
||||
{{ID: "unassigned", Name: "区域"}}, {{ID: "one", Name: "cross_region"}},
|
||||
{{ID: "__proto__", Name: "区域"}}, {{ID: "one", Name: "constructor"}},
|
||||
{{ID: "one", Name: ""}}, {{ID: "one", Name: " 区域"}},
|
||||
} {
|
||||
if _, err := PreviewRegions(exampleDirectory(), nil, regions); err == nil {
|
||||
t.Fatal("invalid region catalog was accepted")
|
||||
}
|
||||
}
|
||||
if _, err := PreviewRegions(exampleDirectory(), []Rule{{DepartmentID: "sales", Region: "missing"}}, []RegionDefinition{{ID: "education", Name: "国内教育"}}); err == nil {
|
||||
t.Fatal("unknown mapping ID accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomRegionCatalogBindsStableIDAndRenamePreservesRules(t *testing.T) {
|
||||
directory := exampleDirectory()
|
||||
state := State{State: "ready", DirectoryID: "d", Rules: []Rule{}}
|
||||
var request SaveRequest
|
||||
if err := json.Unmarshal([]byte(`{"directory_id":"d","base_revision":"","regions":[{"id":"education","name":"国内教育"},{"id":"overseas","name":"国外工业Amercia"}],"rules":[{"department_id":"sales","region":"education"},{"department_id":"apac","region":"overseas"}]}`), &request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next, err := applyRequest(state, directory, request)
|
||||
if err != nil {
|
||||
t.Fatalf("custom business regions must not be rejected by the old four-name whitelist: %v", err)
|
||||
}
|
||||
if next.View.Regions["education"] != 1 || next.View.Regions["overseas"] != 1 || next.View.ConflictingPeople != 1 {
|
||||
t.Fatal("inheritance or stable-ID person dedup changed")
|
||||
}
|
||||
projection, err := BuildAttribution(next, directory)
|
||||
if err != nil || projection.Resolve("p2", "").Region != "国外工业Amercia" {
|
||||
t.Fatal("attribution did not use the same catalog display name")
|
||||
}
|
||||
raw, _ := json.Marshal(request)
|
||||
var body map[string]any
|
||||
_ = json.Unmarshal(raw, &body)
|
||||
body["regions"].([]any)[1].(map[string]any)["name"] = "国外工业 EMEA"
|
||||
raw, _ = json.Marshal(body)
|
||||
_ = json.Unmarshal(raw, &request)
|
||||
renamed, err := applyRequest(next, directory, request)
|
||||
if err != nil || renamed.Rules[0].Region != next.Rules[0].Region {
|
||||
t.Fatal("renaming changed the stable mapping")
|
||||
}
|
||||
projection, err = BuildAttribution(renamed, directory)
|
||||
if err != nil || projection.Resolve("p2", "").Region != "国外工业 EMEA" {
|
||||
t.Fatal("renamed catalog not consumed by attribution")
|
||||
}
|
||||
}
|
||||
@@ -46,12 +46,18 @@ type PreviewResult struct {
|
||||
|
||||
// Identity is department ID. Names and legacy keyword rules never decide ownership.
|
||||
func Preview(directory Directory, rules []Rule) (PreviewResult, error) {
|
||||
return PreviewRegions(directory, rules, DefaultRegions())
|
||||
}
|
||||
func PreviewRegions(directory Directory, rules []Rule, regions []RegionDefinition) (PreviewResult, error) {
|
||||
result := PreviewResult{Departments: []DepartmentView{}, Regions: map[string]int{}, MissingDepartments: []string{}, TotalPeople: len(directory.People)}
|
||||
if len(directory.Departments) == 0 || len(directory.Departments) > 20000 || len(directory.People) == 0 || len(directory.People) > 100000 || len(rules) > 20000 {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
for _, region := range RegionNames {
|
||||
result.Regions[region] = 0
|
||||
if !validRegions(regions) {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
for _, region := range regions {
|
||||
result.Regions[region.ID] = 0
|
||||
}
|
||||
departments := make(map[string]Department, len(directory.Departments))
|
||||
for _, d := range directory.Departments {
|
||||
|
||||
+32
-21
@@ -26,20 +26,22 @@ type Import struct {
|
||||
Directory Directory `json:"directory"`
|
||||
}
|
||||
type SaveRequest struct {
|
||||
DirectoryID string `json:"directory_id"`
|
||||
BaseRevision string `json:"base_revision"`
|
||||
Rules []Rule `json:"rules"`
|
||||
Regions []RegionDefinition `json:"regions,omitempty"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
BaseRevision string `json:"base_revision"`
|
||||
Rules []Rule `json:"rules"`
|
||||
}
|
||||
type State struct {
|
||||
State string `json:"state"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
DirectorySource string `json:"directory_source"`
|
||||
DirectorySyncedAt *time.Time `json:"directory_synced_at"`
|
||||
RevisionID string `json:"revision_id"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
Rules []Rule `json:"rules"`
|
||||
View PreviewResult `json:"view"`
|
||||
Regions []RegionDefinition `json:"regions"`
|
||||
State string `json:"state"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
DirectorySource string `json:"directory_source"`
|
||||
DirectorySyncedAt *time.Time `json:"directory_synced_at"`
|
||||
RevisionID string `json:"revision_id"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
Rules []Rule `json:"rules"`
|
||||
View PreviewResult `json:"view"`
|
||||
}
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
@@ -53,12 +55,14 @@ type orgQuerier interface {
|
||||
QueryRow(context.Context, string, ...any) pgx.Row
|
||||
}
|
||||
|
||||
const readStateSQL = `SELECT d.id,d.source,d.synced_at,d.payload,COALESCE(r.id,''),COALESCE(r.rules,'[]'::jsonb),COALESCE(r.updated_by,''),r.created_at
|
||||
const defaultRegionsJSON = `[{"id":"国内工业","name":"国内工业"},{"id":"APAC","name":"APAC"},{"id":"EMEA","name":"EMEA"},{"id":"America","name":"America"}]`
|
||||
|
||||
const readStateSQL = `SELECT d.id,d.source,d.synced_at,d.payload,COALESCE(r.id,''),COALESCE(r.rules,'[]'::jsonb),COALESCE(r.updated_by,''),r.created_at,COALESCE(r.region_definitions,'` + defaultRegionsJSON + `'::jsonb)
|
||||
FROM qa_ops_organization_state st JOIN qa_ops_directory_snapshots d ON d.tenant_key=st.tenant_key AND d.id=st.directory_id
|
||||
LEFT JOIN qa_ops_region_revisions r ON r.tenant_key=st.tenant_key AND r.id=st.revision_id WHERE st.tenant_key=$1`
|
||||
|
||||
func (s *Store) read(ctx context.Context, q orgQuerier, lock bool) (State, Directory, error) {
|
||||
state := State{State: "empty", Rules: []Rule{}, View: PreviewResult{Departments: []DepartmentView{}, Regions: map[string]int{}, MissingDepartments: []string{}}}
|
||||
state := State{Regions: DefaultRegions(), State: "empty", Rules: []Rule{}, View: PreviewResult{Departments: []DepartmentView{}, Regions: map[string]int{}, MissingDepartments: []string{}}}
|
||||
for _, r := range RegionNames {
|
||||
state.View.Regions[r] = 0
|
||||
}
|
||||
@@ -67,15 +71,15 @@ func (s *Store) read(ctx context.Context, q orgQuerier, lock bool) (State, Direc
|
||||
if lock {
|
||||
query += " FOR UPDATE OF st"
|
||||
}
|
||||
var payload, rules []byte
|
||||
err := q.QueryRow(ctx, query, s.tenant).Scan(&state.DirectoryID, &state.DirectorySource, &state.DirectorySyncedAt, &payload, &state.RevisionID, &rules, &state.UpdatedBy, &state.UpdatedAt)
|
||||
var payload, rules, regions []byte
|
||||
err := q.QueryRow(ctx, query, s.tenant).Scan(&state.DirectoryID, &state.DirectorySource, &state.DirectorySyncedAt, &payload, &state.RevisionID, &rules, &state.UpdatedBy, &state.UpdatedAt, ®ions)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return state, directory, nil
|
||||
}
|
||||
if err != nil || json.Unmarshal(payload, &directory) != nil || json.Unmarshal(rules, &state.Rules) != nil {
|
||||
if err != nil || json.Unmarshal(payload, &directory) != nil || json.Unmarshal(rules, &state.Rules) != nil || json.Unmarshal(regions, &state.Regions) != nil || state.Regions == nil {
|
||||
return State{}, directory, ErrUnavailable
|
||||
}
|
||||
state.View, err = Preview(directory, state.Rules)
|
||||
state.View, err = PreviewRegions(directory, state.Rules, state.RegionDefinitions())
|
||||
if err != nil {
|
||||
return State{}, directory, ErrUnavailable
|
||||
}
|
||||
@@ -106,7 +110,11 @@ func applyRequest(state State, directory Directory, request SaveRequest) (State,
|
||||
if request.DirectoryID != state.DirectoryID || request.BaseRevision != state.RevisionID {
|
||||
return State{}, ErrConflict
|
||||
}
|
||||
view, err := Preview(directory, request.Rules)
|
||||
regions := request.Regions
|
||||
if regions == nil {
|
||||
regions = state.RegionDefinitions()
|
||||
}
|
||||
view, err := PreviewRegions(directory, request.Rules, regions)
|
||||
if err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
@@ -123,6 +131,7 @@ func applyRequest(state State, directory Directory, request SaveRequest) (State,
|
||||
}
|
||||
}
|
||||
state.View = view
|
||||
state.Regions = append([]RegionDefinition{}, regions...)
|
||||
state.Rules = append([]Rule{}, request.Rules...)
|
||||
sort.Slice(state.Rules, func(i, j int) bool { return state.Rules[i].DepartmentID < state.Rules[j].DepartmentID })
|
||||
return state, nil
|
||||
@@ -151,7 +160,9 @@ func (s *Store) SaveRules(ctx context.Context, request SaveRequest, actor string
|
||||
sort.Slice(before, func(i, j int) bool { return before[i].DepartmentID < before[j].DepartmentID })
|
||||
oldJSON, _ := json.Marshal(before)
|
||||
newJSON, _ := json.Marshal(next.Rules)
|
||||
if current.RevisionID != "" && string(oldJSON) == string(newJSON) {
|
||||
oldRegions, _ := json.Marshal(current.RegionDefinitions())
|
||||
newRegions, _ := json.Marshal(next.RegionDefinitions())
|
||||
if current.RevisionID != "" && string(oldJSON) == string(newJSON) && string(oldRegions) == string(newRegions) {
|
||||
if tx.Commit(ctx) != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
@@ -164,7 +175,7 @@ func (s *Store) SaveRules(ctx context.Context, request SaveRequest, actor string
|
||||
next.RevisionID = "reg-" + hex.EncodeToString(nonce[:])
|
||||
next.UpdatedBy = actor
|
||||
var at time.Time
|
||||
if err = tx.QueryRow(ctx, `INSERT INTO qa_ops_region_revisions(tenant_key,id,directory_id,rules,updated_by) VALUES($1,$2,$3,$4,$5) RETURNING created_at`, s.tenant, next.RevisionID, next.DirectoryID, newJSON, actor).Scan(&at); err != nil {
|
||||
if err = tx.QueryRow(ctx, `INSERT INTO qa_ops_region_revisions(tenant_key,id,directory_id,rules,updated_by,region_definitions) VALUES($1,$2,$3,$4,$5,$6) RETURNING created_at`, s.tenant, next.RevisionID, next.DirectoryID, newJSON, actor, newRegions).Scan(&at); err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
next.UpdatedAt = &at
|
||||
|
||||
@@ -134,6 +134,78 @@ func TestOrganizationStoreRoundTripAndOptimisticConflict(t *testing.T) {
|
||||
if err = pool.QueryRow(ctx, "SELECT count(*) FROM qa_ops_region_revisions WHERE tenant_key=$1", "fixture-tenant").Scan(&revisions); err != nil || revisions != 2 {
|
||||
t.Fatal("revision history changed unexpectedly")
|
||||
}
|
||||
|
||||
t.Run("custom catalog persists with the mapping and rename advances revision", func(t *testing.T) {
|
||||
custom := qaopsorg.NewStore(pool, "catalog-fixture")
|
||||
imported, e := custom.ReplaceDirectory(ctx, input)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
request := qaopsorg.SaveRequest{DirectoryID: imported.DirectoryID, Regions: []qaopsorg.RegionDefinition{{ID: "education", Name: "国内教育"}}, Rules: []qaopsorg.Rule{{DepartmentID: "a", Region: "education"}}}
|
||||
preview, e := custom.PreviewRules(ctx, request)
|
||||
if e != nil || preview.View.Regions["education"] != 1 {
|
||||
t.Fatal("custom preview failed", e)
|
||||
}
|
||||
unchanged, _ := custom.GetView(ctx)
|
||||
if unchanged.RevisionID != "" {
|
||||
t.Fatal("catalog preview wrote data")
|
||||
}
|
||||
saved, e := custom.SaveRules(ctx, request, "catalog-admin")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
fresh, e := pgxpool.New(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer fresh.Close()
|
||||
read, e := qaopsorg.NewStore(fresh, "catalog-fixture").GetView(ctx)
|
||||
if e != nil || len(read.Regions) != 1 || read.Regions[0].Name != "国内教育" || read.Rules[0].Region != "education" {
|
||||
t.Fatal("catalog was not persisted with its rules", e)
|
||||
}
|
||||
request.BaseRevision = saved.RevisionID
|
||||
request.Regions[0].Name = "国外工业Amercia"
|
||||
renamed, e := custom.SaveRules(ctx, request, "catalog-admin")
|
||||
if e != nil || renamed.RevisionID == saved.RevisionID {
|
||||
t.Fatal("rename did not create an atomic revision", e)
|
||||
}
|
||||
projection, e := custom.GetAttribution(ctx)
|
||||
if e != nil || projection.Resolve("u1", "").Region != "国外工业Amercia" {
|
||||
t.Fatal("renamed labels not shared by the read paths")
|
||||
}
|
||||
if _, e = custom.SaveRules(ctx, request, "stale-admin"); !errors.Is(e, qaopsorg.ErrConflict) {
|
||||
t.Fatal("rename allowed stale overwrite")
|
||||
}
|
||||
request.BaseRevision = renamed.RevisionID
|
||||
repeated, e := custom.SaveRules(ctx, request, "catalog-admin")
|
||||
if e != nil || repeated.RevisionID != renamed.RevisionID {
|
||||
t.Fatal("unchanged catalog appended another revision")
|
||||
}
|
||||
// Pin the catalog down test to migration 51, not a later additive feature.
|
||||
for {
|
||||
var latest int64
|
||||
if err := pool.QueryRow(ctx, "SELECT max(version) FROM schema_migrations").Scan(&latest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if latest <= 51 {
|
||||
break
|
||||
}
|
||||
if err := postgresstore.RollbackLatestMigration(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if e = postgresstore.RollbackLatestMigration(ctx, pool); e == nil {
|
||||
t.Fatal("down migration discarded a custom catalog")
|
||||
}
|
||||
if _, e = custom.GetView(ctx); e != nil {
|
||||
t.Fatal("refused down migration damaged last-good catalog")
|
||||
}
|
||||
for _, table := range []string{"qa_ops_organization_state", "qa_ops_region_revisions", "qa_ops_directory_snapshots"} {
|
||||
if _, e = pool.Exec(ctx, "DELETE FROM "+table+" WHERE tenant_key=$1", "catalog-fixture"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
})
|
||||
// This test exercises migration 48, not whichever unrelated migration is latest.
|
||||
for {
|
||||
var latest int64
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package qaopsquality
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
)
|
||||
|
||||
// ReadViews projects quality already observed by mirror activation. It performs
|
||||
// one SELECT, never inserts inputs/checks or advances an observation epoch.
|
||||
type viewQuerier interface {
|
||||
Query(context.Context, string, ...any) (pgx.Rows, error)
|
||||
}
|
||||
|
||||
func (s *Store) ReadViews(ctx context.Context, keys []dobotaiops.QualityKey) (map[string]View, error) {
|
||||
return s.readViews(ctx, s.pool, keys)
|
||||
}
|
||||
|
||||
// ReadViewsInTx shares the caller's repeatable-read snapshot with mirror and organization metadata.
|
||||
func (s *Store) ReadViewsInTx(ctx context.Context, tx pgx.Tx, keys []dobotaiops.QualityKey) (map[string]View, error) {
|
||||
return s.readViews(ctx, tx, keys)
|
||||
}
|
||||
func (s *Store) readViews(ctx context.Context, q viewQuerier, keys []dobotaiops.QualityKey) (map[string]View, error) {
|
||||
if !s.available() {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
if len(keys) > 5000 {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
expected := map[string]string{}
|
||||
ids := make([]string, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
if !validID(k.ID) || !hashPattern.MatchString(k.InputHash) {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
if old, exists := expected[k.ID]; exists {
|
||||
if old != k.InputHash {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
continue
|
||||
}
|
||||
expected[k.ID] = k.InputHash
|
||||
ids = append(ids, k.ID)
|
||||
}
|
||||
out := map[string]View{}
|
||||
if len(ids) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
rows, e := q.Query(ctx, `SELECT h.record_id,h.input_hash,h.input_epoch,h.review_revision,`+checkObject+`::text,COALESCE((SELECT `+reviewObject+` FROM qa_ops_quality_reviews r WHERE r.tenant_key=h.tenant_key AND r.record_id=h.record_id AND r.revision=h.review_revision),'null'::jsonb)::text FROM qa_ops_quality_records h JOIN qa_ops_quality_inputs i ON i.tenant_key=h.tenant_key AND i.record_id=h.record_id AND i.input_epoch=h.input_epoch JOIN qa_ops_quality_checks c ON c.tenant_key=h.tenant_key AND c.record_id=h.record_id AND c.input_epoch=h.input_epoch AND c.rule_version=$3 WHERE h.tenant_key=$1 AND h.record_id=ANY($2::text[])`, s.tenant, ids, dobotaiops.CoverageRuleVersion)
|
||||
if e != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var id, hash, checkRaw, reviewRaw string
|
||||
var epoch, revision int64
|
||||
if rows.Scan(&id, &hash, &epoch, &revision, &checkRaw, &reviewRaw) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
if expected[id] != hash {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
var automatic Check
|
||||
var review *Review
|
||||
if json.Unmarshal([]byte(checkRaw), &automatic) != nil || json.Unmarshal([]byte(reviewRaw), &review) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
out[id] = Project(hash, epoch, revision, automatic, review)
|
||||
}
|
||||
if rows.Err() != nil || len(out) != len(ids) {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -131,6 +131,34 @@ func (s *Store) view(ctx context.Context, tx pgx.Tx, id string) (View, error) {
|
||||
}
|
||||
return Project(hash, epoch, revision, automatic, review), nil
|
||||
}
|
||||
|
||||
// ObserveRecordsInTx makes mirror activation and review invalidation one commit.
|
||||
// Only the caller owns commit/rollback; no remote I/O occurs while these locks are held.
|
||||
func (s *Store) ObserveRecordsInTx(ctx context.Context, tx pgx.Tx, records []dobotaiops.Record) error {
|
||||
if !s.available() || tx == nil || len(records) > 100 {
|
||||
return ErrInvalid
|
||||
}
|
||||
items := make([]Evidence, 0, len(records))
|
||||
size := 0
|
||||
for _, r := range records {
|
||||
e, err := EvidenceFor(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
size += len(e.Payload)
|
||||
if size > 32<<20 {
|
||||
return ErrInvalid
|
||||
}
|
||||
items = append(items, e)
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool { return items[i].Record.ID < items[j].Record.ID })
|
||||
for _, e := range items {
|
||||
if err := s.observeLocked(ctx, tx, e); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) Observe(ctx context.Context, records []dobotaiops.Record) (map[string]View, error) {
|
||||
if len(records) > 5000 {
|
||||
return nil, ErrInvalid
|
||||
|
||||
@@ -55,6 +55,14 @@ func TestHistoricDevelopmentArchiveBindsExactCommit(t *testing.T) {
|
||||
t.Fatal("archived notes missing")
|
||||
}
|
||||
}
|
||||
// Parallel branch histories may legitimately have the same derived number.
|
||||
input.DeliveryArchive = strings.ReplaceAll(archive, shaB, strings.Repeat("c", 40)) + "\n" + archive
|
||||
result = DeriveVersions(input)
|
||||
for _, v := range result.Records {
|
||||
if v.CommitSHA == shaB && !strings.Contains(v.ReleaseNotes, "historic delivery notes") {
|
||||
t.Fatal("same-number archive hid notes for exact commit")
|
||||
}
|
||||
}
|
||||
input.DeliveryArchive = strings.ReplaceAll(archive, shaB, strings.Repeat("c", 40))
|
||||
result = DeriveVersions(input)
|
||||
for _, v := range result.Records {
|
||||
|
||||
@@ -198,10 +198,7 @@ func DeriveVersions(in DeriveInput) DeriveResult {
|
||||
} else if kind == governance.RecordKindDevelopment {
|
||||
record.ReleaseNotes = governance.ExtractDevelopmentNotes(changelog, label)
|
||||
if record.ReleaseNotes == "" {
|
||||
archived := governance.ExtractDevelopmentNotes(in.DeliveryArchive, label)
|
||||
if strings.Contains(archived, "目标提交:"+commit.SHA) {
|
||||
record.ReleaseNotes = archived
|
||||
}
|
||||
record.ReleaseNotes = governance.ExtractDevelopmentNotesForCommit(in.DeliveryArchive, label, commit.SHA)
|
||||
}
|
||||
if record.ReleaseNotes == "" {
|
||||
for _, tag := range tagsByTarget[commit.SHA] {
|
||||
|
||||
@@ -8,10 +8,11 @@ def git(root,*args):
|
||||
p=subprocess.run(['git',*args],cwd=root,text=True,capture_output=True)
|
||||
if p.returncode:raise RuntimeError('git operation failed: '+args[0])
|
||||
return p.stdout.strip()
|
||||
def notes(text,version):
|
||||
heading=re.search(r'^## 开发快照 snapshot/v'+re.escape(version)+r' - \d{4}-\d{2}-\d{2}\s*$',text,re.M)
|
||||
if not heading:return ''
|
||||
tail=text[heading.end():];return re.split(r'^##\s',tail,maxsplit=1,flags=re.M)[0].strip()
|
||||
def notes(text,version,sha=None):
|
||||
for heading in re.finditer(r'^## 开发快照 snapshot/v'+re.escape(version)+r' - \d{4}-\d{2}-\d{2}\s*$',text,re.M):
|
||||
body=re.split(r'^##\s',text[heading.end():],maxsplit=1,flags=re.M)[0].strip()
|
||||
if sha is None or ('目标提交:'+sha) in body.splitlines():return body
|
||||
return ''
|
||||
def plan(root,sha,backfill=False):
|
||||
if not sha or not SHA.fullmatch(sha):raise ValueError('exact 40-character commit SHA required')
|
||||
if git(root,'cat-file','-t',sha)!='commit':raise ValueError('snapshot target must be a commit')
|
||||
@@ -24,7 +25,7 @@ def plan(root,sha,backfill=False):
|
||||
if n<=0:raise ValueError('formal baseline cannot be tagged as a development delivery')
|
||||
body=notes(text,version)
|
||||
if not body and backfill:
|
||||
body=notes(git(root,'show','HEAD:CHANGELOG.md'),version)
|
||||
body=notes(git(root,'show','HEAD:CHANGELOG.md'),version,sha)
|
||||
if '目标提交:'+sha not in body:raise ValueError('backfilled notes must bind the exact historic SHA')
|
||||
if not body:raise ValueError('this development version has no independent CHANGELOG entry')
|
||||
if not re.search(r'^### (Added|Changed|Fixed|Security)\s*$',body,re.M):raise ValueError('snapshot notes have no change category')
|
||||
@@ -60,6 +61,8 @@ def self_test():
|
||||
(r/'CHANGELOG.md').write_text('## 开发快照 snapshot/v0.1.1 - 2026-10-18\n\n### Fixed\n\n- specific fixture fix\n\n'+base);git(r,'add','CHANGELOG.md');git(r,'commit','-m','fix: fixture change')
|
||||
sha=git(r,'rev-parse','HEAD');before=git(r,'tag');p=plan(r,sha)
|
||||
assert p['tag']=='snapshot/v0.1.1' and 'specific fixture fix' in p['message']
|
||||
duplicate='## 开发快照 snapshot/v0.1.1 - 2026-10-18\n\n目标提交:'+('a'*40)+'\n\n### Fixed\n\n- wrong branch\n\n## 开发快照 snapshot/v0.1.1 - 2026-10-18\n\n目标提交:'+sha+'\n\n### Fixed\n\n- exact branch'
|
||||
assert 'exact branch' in notes(duplicate,'0.1.1',sha) and 'wrong branch' not in notes(duplicate,'0.1.1',sha)
|
||||
assert before==git(r,'tag'),'planning wrote a tag'
|
||||
try:plan(r,'a'*7)
|
||||
except ValueError:pass
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
"""Hash-bound historical import into the local governance master, never the source DB.
|
||||
|
||||
Requires an approved row decision ledger and a genuinely restored native backup.
|
||||
All employee/answer-bearing subprocess I/O is private; stdout contains counts only.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse
|
||||
import collections
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import posixpath
|
||||
import re
|
||||
import subprocess
|
||||
import uuid
|
||||
import xml.etree.ElementTree as ET
|
||||
import zipfile
|
||||
|
||||
PG = "knowledge-governance-p1-postgres-1"
|
||||
TZ = dt.timezone(dt.timedelta(hours=8))
|
||||
NS = {"s": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"}
|
||||
STATUSES = {"new_import_candidate", "existing_2_0_duplicate", "missing_key_review"}
|
||||
|
||||
def sha(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
def text(value: str) -> str:
|
||||
return value.replace("\r\n", "\n").replace("\r", "\n").strip()
|
||||
|
||||
def literal(value: str) -> str:
|
||||
return "'" + value.replace("'", "''") + "'"
|
||||
|
||||
def read_rows(path: Path, expected_sha: str) -> tuple[dict[str,str],list[tuple[int,dict[str,str]]]]:
|
||||
content=path.read_bytes()
|
||||
if sha(content)!=expected_sha:
|
||||
raise ValueError("workbook changed before snapshot parsing")
|
||||
with zipfile.ZipFile(io.BytesIO(content)) as z:
|
||||
if z.testzip() is not None:
|
||||
raise ValueError("workbook ZIP integrity failed")
|
||||
workbook = ET.fromstring(z.read("xl/workbook.xml"))
|
||||
sheets = workbook.find("s:sheets", NS)
|
||||
if sheets is None or len(sheets)==0:
|
||||
raise ValueError("workbook contains no worksheets")
|
||||
sheet = sheets[0]
|
||||
if sheet.attrib["name"] != "问题流水表":
|
||||
raise ValueError("approved first worksheet not found")
|
||||
rid = sheet.attrib["{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"]
|
||||
relationships = ET.fromstring(z.read("xl/_rels/workbook.xml.rels"))
|
||||
target = next(r.attrib["Target"] for r in relationships if r.attrib["Id"] == rid)
|
||||
target = target.lstrip("/") if target.startswith("/") else posixpath.normpath("xl/"+target)
|
||||
shared = []
|
||||
if "xl/sharedStrings.xml" in z.namelist():
|
||||
for _, item in ET.iterparse(z.open("xl/sharedStrings.xml"),events=("end",)):
|
||||
if item.tag.endswith("}si"):
|
||||
shared.append("".join(n.text or "" for n in item.iter() if n.tag.endswith("}t")))
|
||||
item.clear()
|
||||
def value(cell):
|
||||
v=cell.find("s:v",NS)
|
||||
if cell.attrib.get("t")=="s" and v is not None:
|
||||
return shared[int(v.text)]
|
||||
if cell.attrib.get("t")=="inlineStr":
|
||||
return "".join(n.text or "" for n in cell.iter() if n.tag.endswith("}t"))
|
||||
return (v.text or "") if v is not None else ""
|
||||
headers={}; rows=[]
|
||||
for _, item in ET.iterparse(z.open(target),events=("end",)):
|
||||
if not item.tag.endswith("}row"):
|
||||
continue
|
||||
rowno=int(item.attrib["r"])
|
||||
cells={re.sub(r"\d","",c.attrib["r"]):value(c) for c in item}
|
||||
if rowno==1:
|
||||
headers=cells;item.clear();continue
|
||||
raw={c:cells.get(c,"") for c in "ABCDEFGHIJKLMNO"}
|
||||
if any(text(v) for v in raw.values()):
|
||||
if any("\x00" in v for v in raw.values()):
|
||||
raise ValueError("NUL in workbook; no lossy conversion allowed")
|
||||
rows.append((rowno,raw))
|
||||
item.clear()
|
||||
if any(headers.get(c)!=h for c,h in {"H":"提问时间","I":"提问人","J":"原始问题"}.items()):
|
||||
raise ValueError("approved event columns changed")
|
||||
return headers,rows
|
||||
|
||||
def prepare(args,plan,decisions):
|
||||
_,rows=read_rows(args.workbook,plan["source_sha256"])
|
||||
by_row={r["excel_row"]:r for r in decisions}
|
||||
if len(by_row)!=len(decisions) or len(rows)!=plan["data_rows"] or set(by_row)!={r for r,_ in rows}:
|
||||
raise ValueError("approved decisions do not cover exactly the input rows")
|
||||
observed=dt.datetime.now(TZ).isoformat()
|
||||
for number,raw in rows:
|
||||
decision=by_row[number]
|
||||
if decision["status"] not in STATUSES:
|
||||
raise ValueError("unapproved or ambiguous row disposition")
|
||||
asked=None
|
||||
if text(raw["H"]):
|
||||
asked=dt.datetime.fromisoformat(text(raw["H"]).replace("/","-").replace("Z","+00:00"))
|
||||
asked=asked.replace(tzinfo=TZ) if asked.tzinfo is None else asked.astimezone(TZ)
|
||||
if asked.microsecond:
|
||||
raise ValueError("timestamp precision differs from the approved seconds-only input")
|
||||
key=[asked.strftime("%Y-%m-%d %H:%M:%S") if asked else "",text(raw["I"]),text(raw["J"])]
|
||||
key_hash=sha(json.dumps(key,ensure_ascii=False).encode())
|
||||
if key_hash!=decision["key_sha256"]:
|
||||
raise ValueError("approved event key changed")
|
||||
record_id="legacy_"+plan["source_sha256"]+"_"+str(number)
|
||||
fields={k:raw[c] for k,c in {"question_chinese":"A","coverage":"C","is_correct":"D","product_category":"E","problem_type":"F","root_cause":"G","language":"K"}.items()}
|
||||
payload={"id":record_id,"status":"historical_import","question":raw["J"],"answer":raw["B"],"asked_at":asked.isoformat() if asked else None,"time_source":"historical_excel","asker":raw["I"],"trigger_person":raw["L"],"department":raw["M"],"region":raw["N"],"references":[],"media":[],"source_coverage":{"verdict":"","reason_code":"","evaluator_version":""},"feedback":{"asker_value":"","up":0,"down":0},"master_fields":fields,"_identity":{},"_quality_observed_at":observed}
|
||||
payload["_quality_hash"]=sha(json.dumps({"id":record_id,"question":raw["J"],"answer":raw["B"],"status":payload["status"],"references":[],"media":[]},ensure_ascii=False,sort_keys=True).encode())
|
||||
yield {"row_number":number,"status":decision["status"],"event_key":key_hash,"expected_matches":decision["matched_record_sha256"],"asked_at":payload["asked_at"],"raw":raw,"payload":payload}
|
||||
|
||||
def build_sql(args,plan,stage,batch):
|
||||
tenant=literal(args.tenant);digest=literal(plan["source_sha256"]);sheet=literal(plan["sheet"]);batchsql=literal(batch)
|
||||
counts=(plan["data_rows"],plan["new_import_candidate_rows"],plan["existing_2_0_duplicate_rows"],plan["missing_key_review_rows"])
|
||||
sql="BEGIN ISOLATION LEVEL SERIALIZABLE; SET LOCAL statement_timeout='120s'; SET LOCAL lock_timeout='15s';\n"
|
||||
sql+="SELECT pg_advisory_xact_lock(hashtextextended("+tenant+"||':qa-history-import',0));\n"
|
||||
sql+="LOCK TABLE qa_ops_master_records IN SHARE ROW EXCLUSIVE MODE;\n"
|
||||
sql+="CREATE TEMP TABLE incoming_json(raw jsonb) ON COMMIT DROP;\nCOPY incoming_json(raw) FROM STDIN;\n"
|
||||
for item in stage:
|
||||
line=json.dumps(item,ensure_ascii=False,separators=(",",":"))
|
||||
sql+=line.replace("\\","\\\\").replace("\n","\\n").replace("\r","\\r").replace("\t","\\t")+"\n"
|
||||
sql+="\\.\nCREATE TEMP TABLE incoming ON COMMIT DROP AS SELECT (raw->>'row_number')::int row_number,raw->>'status' status,raw->>'event_key' event_key,raw->'expected_matches' expected_matches,(raw->>'asked_at')::timestamptz asked_at,raw->'raw' original_fields,raw->'payload' payload FROM incoming_json; CREATE INDEX ON incoming(event_key); ANALYZE incoming; ANALYZE qa_ops_master_records;\nCREATE TEMP TABLE admission_status(replayed boolean NOT NULL,inserted integer NOT NULL) ON COMMIT DROP;\n"
|
||||
sql+="DO $import$ DECLARE replay boolean; bad bigint; BEGIN\n"
|
||||
sql+="IF (SELECT max(version) FROM schema_migrations)<>53 THEN RAISE EXCEPTION 'unverified governance schema'; END IF;\n"
|
||||
sql+="IF EXISTS(SELECT 1 FROM incoming WHERE status<>'missing_key_review' AND event_key<>qa_ops_master_event_key((asked_at)::timestamptz,original_fields->>'I',original_fields->>'J')) THEN RAISE EXCEPTION 'SQL and approved Python event identities differ'; END IF;\n"
|
||||
sql+="SELECT EXISTS(SELECT 1 FROM qa_ops_master_import_batches WHERE tenant_key="+tenant+" AND source_sha256="+digest+" AND sheet_name="+sheet+") INTO replay;\nIF replay THEN\n"
|
||||
sql+="IF NOT EXISTS(SELECT 1 FROM qa_ops_master_import_batches WHERE tenant_key="+tenant+" AND id="+batchsql+" AND ROW(total_rows,imported_rows,skipped_rows,held_rows)=ROW("+",".join(str(n)for n in counts)+")) THEN RAISE EXCEPTION 'existing import manifest differs'; END IF;\n"
|
||||
sql+="IF (SELECT count(*) FROM qa_ops_master_import_rows WHERE tenant_key="+tenant+" AND batch_id="+batchsql+")<>"+str(counts[0])+" OR EXISTS(SELECT 1 FROM incoming i LEFT JOIN qa_ops_master_import_rows r ON r.tenant_key="+tenant+" AND r.batch_id="+batchsql+" AND r.row_number=(i.row_number)::int WHERE r.original_fields IS DISTINCT FROM i.original_fields OR r.disposition IS DISTINCT FROM CASE i.status WHEN 'new_import_candidate' THEN 'imported' WHEN 'existing_2_0_duplicate' THEN 'skipped_duplicate' ELSE 'held_missing_key' END) THEN RAISE EXCEPTION 'existing row audit differs'; END IF;\n"
|
||||
sql+="INSERT INTO admission_status VALUES(true,0);\nELSE\n"
|
||||
sql+="CREATE TEMP TABLE master_before ON COMMIT DROP AS SELECT id,row_to_json(m)::text AS contents FROM qa_ops_master_records m WHERE tenant_key="+tenant+";\n"
|
||||
sql+="CREATE TEMP TABLE source_quality_before ON COMMIT DROP AS SELECT 'records' AS kind,to_jsonb(q) AS value FROM qa_ops_quality_records q WHERE tenant_key="+tenant+" UNION ALL SELECT 'inputs',to_jsonb(q) FROM qa_ops_quality_inputs q WHERE tenant_key="+tenant+" UNION ALL SELECT 'checks',to_jsonb(q) FROM qa_ops_quality_checks q WHERE tenant_key="+tenant+" UNION ALL SELECT 'reviews',to_jsonb(q) FROM qa_ops_quality_reviews q WHERE tenant_key="+tenant+";\n"
|
||||
sql+="IF EXISTS(SELECT 1 FROM incoming i WHERE i.status='new_import_candidate' AND EXISTS(SELECT 1 FROM qa_ops_master_records m WHERE m.tenant_key="+tenant+" AND m.event_key=i.event_key)) OR EXISTS(SELECT 1 FROM incoming i WHERE i.status='existing_2_0_duplicate' AND (SELECT COALESCE(jsonb_agg(encode(sha256(convert_to(m.id,'UTF8')),'hex') ORDER BY m.id),'[]'::jsonb) FROM qa_ops_master_records m WHERE m.tenant_key="+tenant+" AND m.event_key=i.event_key) IS DISTINCT FROM i.expected_matches) THEN RAISE EXCEPTION 'comparison changed; refresh the preview before writing'; END IF;\n"
|
||||
sql+="INSERT INTO qa_ops_master_import_batches(tenant_key,id,source_sha256,source_name,sheet_name,total_rows,imported_rows,skipped_rows,held_rows) VALUES("+tenant+","+batchsql+","+digest+","+literal(args.workbook.name)+","+sheet+","+",".join(str(n)for n in counts)+");\n"
|
||||
sql+="INSERT INTO qa_ops_master_records(tenant_key,id,event_key,origin,asked_at,question,status,identity,quality_hash,payload,original_fields,batch_id,source_row) SELECT "+tenant+",payload->>'id',event_key,'historical_excel',(asked_at)::timestamptz,original_fields->>'J','historical_import','{}'::jsonb,payload->>'_quality_hash',payload,original_fields,"+batchsql+",(row_number)::int FROM incoming WHERE status='new_import_candidate';\n"
|
||||
sql+="GET DIAGNOSTICS bad=ROW_COUNT; IF bad<>"+str(counts[1])+" THEN RAISE EXCEPTION 'imported row count differs'; END IF;\n"
|
||||
sql+="INSERT INTO qa_ops_master_import_rows(tenant_key,batch_id,row_number,disposition,original_fields,master_id) SELECT "+tenant+","+batchsql+",(i.row_number)::int,CASE i.status WHEN 'new_import_candidate' THEN 'imported' WHEN 'existing_2_0_duplicate' THEN 'skipped_duplicate' ELSE 'held_missing_key' END,i.original_fields,CASE WHEN i.status='missing_key_review' THEN NULL ELSE m.id END FROM incoming i LEFT JOIN qa_ops_master_records m ON m.tenant_key="+tenant+" AND m.event_key=i.event_key AND i.status<>'missing_key_review';\n"
|
||||
sql+="INSERT INTO qa_ops_master_source_links(tenant_key,source_kind,source_id,master_id) SELECT "+tenant+",'historical_excel',"+digest+"||':'||"+sheet+"||':'||row_number,master_id FROM qa_ops_master_import_rows WHERE tenant_key="+tenant+" AND batch_id="+batchsql+" AND master_id IS NOT NULL;\n"
|
||||
sql+="IF EXISTS(SELECT 1 FROM master_before b LEFT JOIN qa_ops_master_records m ON m.tenant_key="+tenant+" AND m.id=b.id WHERE row_to_json(m)::text IS DISTINCT FROM b.contents) THEN RAISE EXCEPTION 'existing master record changed'; END IF;\n"
|
||||
sql+="IF EXISTS((SELECT kind,value FROM source_quality_before EXCEPT SELECT kind,value FROM (SELECT 'records' kind,to_jsonb(q) value FROM qa_ops_quality_records q WHERE tenant_key="+tenant+" UNION ALL SELECT 'inputs',to_jsonb(q) FROM qa_ops_quality_inputs q WHERE tenant_key="+tenant+" UNION ALL SELECT 'checks',to_jsonb(q) FROM qa_ops_quality_checks q WHERE tenant_key="+tenant+" UNION ALL SELECT 'reviews',to_jsonb(q) FROM qa_ops_quality_reviews q WHERE tenant_key="+tenant+") current_source)) THEN RAISE EXCEPTION 'original source evaluation changed'; END IF;\n"
|
||||
sql+="INSERT INTO admission_status VALUES(false,"+str(counts[1])+");\nEND IF;\nEND $import$;\n"
|
||||
sql+="SELECT jsonb_build_object('state','IMPORT_TRANSACTION_VERIFIED','batch_id',"+batchsql+",'inserted_rows',inserted,'skipped_rows',"+str(counts[2])+",'held_rows',"+str(counts[3])+",'replayed',replayed,'master_total',(SELECT count(*) FROM qa_ops_master_records WHERE tenant_key="+tenant+"),'production_source_connected',false) FROM admission_status;\nCOMMIT;\n"
|
||||
return sql
|
||||
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
for name in ["workbook","decisions","plan","backup-verification","evidence-directory"]:
|
||||
parser.add_argument("--"+name,type=Path,required=True)
|
||||
parser.add_argument("--tenant",required=True)
|
||||
parser.add_argument("--database",required=True)
|
||||
parser.add_argument("--apply",action="store_true",required=True)
|
||||
parser.add_argument("--live-apply",action="store_true")
|
||||
args=parser.parse_args()
|
||||
if not (re.fullmatch(r"kg_history_import_test_[a-f0-9]{12}",args.database) or (args.database=="governance" and args.live_apply)):
|
||||
raise ValueError("only an isolated history test DB or explicitly approved local governance DB is permitted")
|
||||
if not args.tenant or len(args.tenant)>128 or any(ord(c)<32 for c in args.tenant):
|
||||
raise ValueError("invalid fixed governance tenant")
|
||||
plan=json.loads(args.plan.read_text());decisions=json.loads(args.decisions.read_text())
|
||||
expected=plan["source_sha256"]
|
||||
if not re.fullmatch(r"[a-f0-9]{64}",expected) or sha(args.workbook.read_bytes())!=expected:
|
||||
raise ValueError("approved input SHA differs")
|
||||
if plan["sheet"]!="问题流水表" or plan["dedup_key"]!=["提问时间","提问人","原始问题"] or plan["within_excel_same_key_extra_rows"] or plan["ambiguous_existing_key_rows"]:
|
||||
raise ValueError("unapproved matching contract")
|
||||
approved=collections.Counter(d["status"] for d in decisions)
|
||||
if approved!={"new_import_candidate":plan["new_import_candidate_rows"],"existing_2_0_duplicate":plan["existing_2_0_duplicate_rows"],"missing_key_review":plan["missing_key_review_rows"]}:
|
||||
raise ValueError("approved row counts differ")
|
||||
backup=json.loads(args.backup_verification.read_text());dump=args.backup_verification.parent/backup["backup_file"]
|
||||
if backup["state"]!="BACKUP_RESTORE_VERIFIED" or not backup["real_restore_completed"] or not backup["all_table_row_counts_equal"] or not backup["all_qa_quality_org_frozen_content_hashes_equal"] or backup["source_workbook_sha256"]!=expected or dump.stat().st_size!=backup["backup_bytes"] or sha(dump.read_bytes())!=backup["backup_sha256"]:
|
||||
raise ValueError("verified native backup gate failed")
|
||||
args.evidence_directory.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||
stage=list(prepare(args,plan,decisions));batch="xlsx_"+expected+"_"+sha(plan["sheet"].encode())[:12]
|
||||
sql=build_sql(args,plan,stage,batch)
|
||||
private=args.evidence_directory/("import-"+uuid.uuid4().hex[:12]+"-private.log")
|
||||
result=subprocess.run(["docker","exec","-i",PG,"psql","-X","-qAt","-v","ON_ERROR_STOP=1","-U","governance","-d",args.database],input=sql,text=True,capture_output=True,timeout=150)
|
||||
private.write_text(result.stderr)
|
||||
if result.returncode:
|
||||
raise RuntimeError("governance import has no verified commit receipt; read the batch before retrying; the transaction is all-or-nothing; inspect the restricted evidence log")
|
||||
reports=[json.loads(line) for line in result.stdout.splitlines() if line.startswith('{')]
|
||||
if len(reports)!=1:
|
||||
raise RuntimeError("import receipt unavailable; inspect batch read-back before any retry")
|
||||
report=reports[0]
|
||||
# A committed receipt is checked by an independent connection, not just COMMIT's exit code.
|
||||
query="BEGIN READ ONLY; SELECT jsonb_build_object('total',count(*),'imported',count(*)FILTER(WHERE disposition='imported'),'skipped',count(*)FILTER(WHERE disposition='skipped_duplicate'),'held',count(*)FILTER(WHERE disposition='held_missing_key')) FROM qa_ops_master_import_rows WHERE tenant_key="+literal(args.tenant)+" AND batch_id="+literal(batch)+"; COMMIT;"
|
||||
check=subprocess.run(["docker","exec",PG,"psql","-X","-qAt","-v","ON_ERROR_STOP=1","-U","governance","-d",args.database,"-c",query],capture_output=True,text=True,timeout=30)
|
||||
if check.returncode:
|
||||
raise RuntimeError("import committed but independent audit read-back failed; do not claim complete")
|
||||
actual=json.loads(check.stdout.strip())
|
||||
if actual!={"total":plan["data_rows"],"imported":plan["new_import_candidate_rows"],"skipped":plan["existing_2_0_duplicate_rows"],"held":plan["missing_key_review_rows"]}:
|
||||
raise RuntimeError("committed audit row counts differ")
|
||||
if sha(args.workbook.read_bytes())!=expected:
|
||||
raise RuntimeError("input changed during import")
|
||||
report.update(independent_read_back_verified=True,source_unchanged=True)
|
||||
evidence=args.evidence_directory/("import-"+uuid.uuid4().hex[:12]+"-verification.json")
|
||||
evidence.write_text(json.dumps(report,ensure_ascii=False,indent=2))
|
||||
print(json.dumps(report,ensure_ascii=False))
|
||||
|
||||
if __name__=="__main__":
|
||||
main()
|
||||
+41
-3
@@ -9,9 +9,22 @@
|
||||
"⚠️ 文件缺失或解析不了 ⇒ 门禁红:范围声明不出来时,不许默认放行。"
|
||||
],
|
||||
"optional": [
|
||||
{"package":"knowledge-governance/internal/qaopsquality","test":"TestQualityStoreImmutableHistoryReplayConcurrencyAndStaleness","reason":"仅在显式一次性 loopback kg_qaops_quality_test_ 库执行;默认 CI 不连接共享/生产库,隔离 PG 另行实跑"},
|
||||
{"package": "knowledge-governance/internal/dobotaiops", "test": "TestQARecordInternalIdentityAndWholeFilterKeys", "reason": "必须显式一次性隔离PG;验证真实只读SQL身份关联/计数及隐私,不连接生产;默认无库时明确跳过,另行本地补验"},
|
||||
{"package": "knowledge-governance/internal/dobotaiops", "test": "TestQAUsageGroupsCountEventsOnceOverTheFullFilter", "reason": "必须显式一次性隔离PG;验证真实只读SQL身份关联/计数及隐私,不连接生产;默认无库时明确跳过,另行本地补验"},
|
||||
{"package":"knowledge-governance/internal/qaopsmirror","reason":"本包所有集成用例只在显式一次性 loopback kg_qaops_mirror_test_ 库运行;默认 CI 不连共享或生产库;隔离 PG -race 另行实跑"},
|
||||
{
|
||||
"package": "knowledge-governance/internal/qaopsquality",
|
||||
"test": "TestQualityStoreImmutableHistoryReplayConcurrencyAndStaleness",
|
||||
"reason": "仅在显式一次性 loopback kg_qaops_quality_test_ 库执行;默认 CI 不连接共享/生产库,隔离 PG 另行实跑"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/dobotaiops",
|
||||
"test": "TestQARecordInternalIdentityAndWholeFilterKeys",
|
||||
"reason": "必须显式一次性隔离PG;验证真实只读SQL身份关联/计数及隐私,不连接生产;默认无库时明确跳过,另行本地补验"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/dobotaiops",
|
||||
"test": "TestQAUsageGroupsCountEventsOnceOverTheFullFilter",
|
||||
"reason": "必须显式一次性隔离PG;验证真实只读SQL身份关联/计数及隐私,不连接生产;默认无库时明确跳过,另行本地补验"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/qaopsorg",
|
||||
"test": "TestDirectorySyncQueueDurableReplayAndLeaseFencing",
|
||||
@@ -111,6 +124,31 @@
|
||||
"package": "knowledge-governance/internal/versionhistory",
|
||||
"test": "TestLiveSyncAgainstRealRepository",
|
||||
"reason": "真实仓库的只读同步用例需要内部可达的 Gitea(**匿名**,不读凭据);无环境即跳过(补验路径:设 VERSION_HISTORY_LIVE_BASE_URL 后单跑这条)"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/qaopsmirror",
|
||||
"test": "TestLocalMirrorQueriesNeverRequireSource",
|
||||
"reason": "仅显式一次性隔离PG验证本地副本/持久同步或专门只读源夹具;默认CI不连接共享与生产库,另行实际执行隔离验收"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/qaopsmirror",
|
||||
"test": "TestLocalMirrorDurableQueueCoalescesAndAudits",
|
||||
"reason": "仅显式一次性隔离PG验证本地副本/持久同步或专门只读源夹具;默认CI不连接共享与生产库,另行实际执行隔离验收"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/qaopsmirror",
|
||||
"test": "TestLocalMirrorSyncActivatesAndCheckpoints",
|
||||
"reason": "仅显式一次性隔离PG验证本地副本/持久同步或专门只读源夹具;默认CI不连接共享与生产库,另行实际执行隔离验收"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/qaopsmirror",
|
||||
"test": "TestLocalMirrorPeriodicSyncIsDurableAndDueOnly",
|
||||
"reason": "仅显式一次性隔离PG验证本地副本/持久同步或专门只读源夹具;默认CI不连接共享与生产库,另行实际执行隔离验收"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/dobotaiops",
|
||||
"test": "TestMirrorSourceManifestDetectsUpdatesWithoutVolatileTimes",
|
||||
"reason": "仅显式一次性隔离PG验证本地副本/持久同步或专门只读源夹具;默认CI不连接共享与生产库,另行实际执行隔离验收"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Generated
+1493
-6
File diff suppressed because it is too large
Load Diff
+3
-1
@@ -13,7 +13,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "19.1.1",
|
||||
"react-dom": "19.1.1"
|
||||
"react-dom": "19.1.1",
|
||||
"react-markdown": "10.1.0",
|
||||
"remark-gfm": "4.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "19.1.10",
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { QAAnswerMarkdown } from './QAAnswerMarkdown'
|
||||
describe('AI answer Markdown preview', () => {
|
||||
it('renders headings, tables, code, links and keeps original source', () => {
|
||||
const answer =
|
||||
'# 安装步骤\n\n- **先断电**\n- 检查接线\n\n| 参数 | 值 |\n| --- | --- |\n| 速度 | 50 |\n\n```python\nprint("ready")\n```\n\n[说明](https://example.invalid/guide)'
|
||||
const html = renderToStaticMarkup(<QAAnswerMarkdown answer={answer} />)
|
||||
expect(html).toContain('<h1>安装步骤</h1>')
|
||||
expect(html).toContain('<strong>先断电</strong>')
|
||||
expect(html).toContain('<table>')
|
||||
expect(html).toContain('language-python')
|
||||
expect(html).toContain('href="https://example.invalid/guide"')
|
||||
expect(html).toContain('noopener noreferrer')
|
||||
expect(html).toContain('查看 Markdown 原文')
|
||||
})
|
||||
it('never executes raw HTML, unsafe URL schemes or automatically loads external images', () => {
|
||||
const answer =
|
||||
'<script>globalThis.PWNED=true</script>\n\n<img src="x" onerror="alert(1)">\n\n[unsafe](javascript:alert%281%29)\n\n'
|
||||
const html = renderToStaticMarkup(<QAAnswerMarkdown answer={answer} />)
|
||||
expect(html).not.toContain('<script>')
|
||||
expect(html).not.toContain('<img ')
|
||||
expect(html).not.toContain('href="javascript:')
|
||||
expect(html.split('<details')[0]).not.toContain('onerror=')
|
||||
expect(html).toContain('查看图片')
|
||||
})
|
||||
it('does not confuse an empty answer with a positive assessment', () => {
|
||||
expect(renderToStaticMarkup(<QAAnswerMarkdown answer="" />)).toContain('暂无答案')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useState } from 'react'
|
||||
import Markdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import './qaAnswer.css'
|
||||
|
||||
export function safeAnswerURL(value: string): string {
|
||||
if (!value || /[\u0000-\u0020\u007f\\]/.test(value) || value.startsWith('//')) return ''
|
||||
if (!/^[a-z][a-z0-9+.-]*:/i.test(value)) return value
|
||||
try {
|
||||
const url = new URL(value)
|
||||
return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password ? value : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export function QAAnswerMarkdown({ answer }: { answer: string }) {
|
||||
const [showImages, setShowImages] = useState(false)
|
||||
if (!answer) return <p>暂无答案</p>
|
||||
return (
|
||||
<div className="qa-answer">
|
||||
<div className="qa-answer-tools">
|
||||
<span>Markdown 预览</span>
|
||||
{/!\[/.test(answer) ? (
|
||||
<button type="button" onClick={() => setShowImages(!showImages)} aria-pressed={showImages}>
|
||||
{showImages ? '隐藏图片' : '显示答案图片'}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="qa-answer-markdown">
|
||||
<Markdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
skipHtml
|
||||
urlTransform={safeAnswerURL}
|
||||
components={{
|
||||
a: ({ href, children }) =>
|
||||
href ? (
|
||||
<a href={href} target="_blank" rel="noopener noreferrer" referrerPolicy="no-referrer">
|
||||
{children}
|
||||
</a>
|
||||
) : (
|
||||
<span>{children}</span>
|
||||
),
|
||||
img: ({ src, alt }) =>
|
||||
src ? (
|
||||
showImages ? (
|
||||
<img src={src} alt={alt ?? ''} loading="lazy" referrerPolicy="no-referrer" />
|
||||
) : (
|
||||
<a href={src} target="_blank" rel="noopener noreferrer" referrerPolicy="no-referrer">
|
||||
查看图片{alt ? `:${alt}` : ''}
|
||||
</a>
|
||||
)
|
||||
) : (
|
||||
<span>{alt || '图片地址不可用'}</span>
|
||||
),
|
||||
}}
|
||||
>
|
||||
{answer}
|
||||
</Markdown>
|
||||
</div>
|
||||
<details className="qa-answer-source">
|
||||
<summary>查看 Markdown 原文</summary>
|
||||
<pre>{answer}</pre>
|
||||
</details>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { qaDailySeries, qaCategorySeries } from './qaDashboard'
|
||||
import { QADashboardView } from './QADashboard'
|
||||
import { parseQADashboard } from './qaDashboardData'
|
||||
import { dashboardFixture } from './qaDashboard.fixture'
|
||||
import type { QARecord, QAQuery } from './qaOps'
|
||||
const query: QAQuery = { start: '2026-10-11T16:00:00Z', end: '2026-10-13T16:00:00Z', keyword: '', cursor: '' }
|
||||
const records = [
|
||||
{ id: 'a', asked_at: '2026-10-11T16:30:00Z', product_category: '<img src=x onerror=alert(1)>', problem_type: '通信' },
|
||||
{ id: 'b', asked_at: '2026-10-12T16:01:00Z' },
|
||||
] as QARecord[]
|
||||
describe('question dashboard projections', () => {
|
||||
it('groups by Beijing day and keeps zero days instead of using the browser timezone', () => {
|
||||
expect(qaDailySeries(records, query)).toEqual([
|
||||
{ label: '2026-10-12', count: 1 },
|
||||
{ label: '2026-10-13', count: 1 },
|
||||
])
|
||||
expect(qaDailySeries([], query).map((p) => p.count)).toEqual([0, 0])
|
||||
})
|
||||
it('keeps unclassified records distinct without inventing a category', () => {
|
||||
expect(qaCategorySeries(records, 'problem_type')).toEqual([
|
||||
{ label: '通信', count: 1 },
|
||||
{ label: '未分类', count: 1 },
|
||||
])
|
||||
})
|
||||
it('renders the real dashboard panels and escaped category text', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<QADashboardView data={parseQADashboard(dashboardFixture)} loading={false} error="" onRetry={vi.fn()} />
|
||||
)
|
||||
for (const title of ['问题总数', '本周新增', '覆盖率趋势', '正确率趋势', '产品问题排行', '导出看板图片'])
|
||||
expect(html).toContain(title)
|
||||
expect(html).not.toContain('<img src=x')
|
||||
expect((html.match(/data-panel=/g) || []).length).toBe(11)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,125 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { QAQuery } from './qaOps'
|
||||
import { fetchQADashboard } from './qaDashboardData'
|
||||
import type { QADashboardData } from './qaDashboardData'
|
||||
import { QADashboardDrawing } from './QADashboardDrawing'
|
||||
import { createDashboardPNG } from './qaDashboardExport'
|
||||
import { currentQAWeek } from './qaWeeks'
|
||||
import { QAMonthly } from './QAMonthly'
|
||||
import './qaDashboard.css'
|
||||
export interface QADashboardProps {
|
||||
data: QADashboardData | null
|
||||
loading: boolean
|
||||
error: string
|
||||
onRetry: () => void
|
||||
}
|
||||
export function QADashboardView({ data, loading, error, onRetry }: QADashboardProps) {
|
||||
const host = useRef<HTMLDivElement>(null),
|
||||
svg = useRef<SVGSVGElement>(null)
|
||||
const [width, setWidth] = useState(1280),
|
||||
[exporting, setExporting] = useState(false),
|
||||
[exportError, setExportError] = useState('')
|
||||
useEffect(() => {
|
||||
const element = host.current
|
||||
if (!element) return
|
||||
const update = () => setWidth(Math.max(240, Math.floor(element.clientWidth)))
|
||||
update()
|
||||
const observer = new ResizeObserver(update)
|
||||
observer.observe(element)
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
useEffect(() => setExportError(''), [data])
|
||||
async function download() {
|
||||
if (!svg.current || !data || loading || error || exporting) return
|
||||
setExporting(true)
|
||||
setExportError('')
|
||||
try {
|
||||
const blob = await createDashboardPNG(svg.current),
|
||||
url = URL.createObjectURL(blob),
|
||||
link = document.createElement('a'),
|
||||
week = currentQAWeek(new Date(data.week_start))
|
||||
link.href = url
|
||||
link.download = `DobotAI_QA_Dashboard_${week.year}_W${String(week.week).padStart(2, '0')}.png`
|
||||
document.body.append(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
} catch (e) {
|
||||
setExportError(e instanceof Error ? e.message : '看板图片生成失败')
|
||||
} finally {
|
||||
setExporting(false)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section className="qa-dashboard" aria-label="问题统计看板">
|
||||
<div className="qa-dashboard-toolbar">
|
||||
<button type="button" disabled={!data || loading || !!error || exporting} onClick={() => void download()}>
|
||||
{exporting ? '正在生成图片…' : '导出看板图片'}
|
||||
</button>
|
||||
</div>
|
||||
{error ? (
|
||||
<div role="alert" className="error-banner">
|
||||
{error}{' '}
|
||||
<button type="button" onClick={onRetry}>
|
||||
重新读取
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
{exportError ? (
|
||||
<div role="alert" className="error-banner">
|
||||
{exportError}
|
||||
</div>
|
||||
) : null}
|
||||
{loading ? <p role="status">正在读取完整统计范围…</p> : null}
|
||||
<div className="qa-dashboard-canvas" ref={host}>
|
||||
{!loading && !error && data ? <QADashboardDrawing data={data} width={width} svgRef={svg} /> : null}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
export function QADashboard({
|
||||
query,
|
||||
error,
|
||||
revision,
|
||||
onRetry,
|
||||
}: {
|
||||
query: QAQuery | null
|
||||
error: string | null
|
||||
revision: number
|
||||
onRetry: () => void
|
||||
}) {
|
||||
const [data, setData] = useState<QADashboardData | null>(null),
|
||||
[failure, setFailure] = useState(''),
|
||||
[loading, setLoading] = useState(false),
|
||||
[monthly, setMonthly] = useState(false)
|
||||
useEffect(() => {
|
||||
setData(null)
|
||||
setFailure('')
|
||||
if (!query) {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
const abort = new AbortController()
|
||||
setLoading(true)
|
||||
void fetchQADashboard(query, abort.signal)
|
||||
.then((v) => {
|
||||
if (!abort.signal.aborted) setData(v)
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!abort.signal.aborted) setFailure(e instanceof Error ? e.message : '统计看板读取失败')
|
||||
})
|
||||
.finally(() => {
|
||||
if (!abort.signal.aborted) setLoading(false)
|
||||
})
|
||||
return () => abort.abort()
|
||||
}, [query, revision])
|
||||
return (
|
||||
<div className="qa-dashboard-scroll">
|
||||
<QADashboardView data={data} loading={loading} error={error || failure} onRetry={onRetry} />
|
||||
<details className="qa-monthly-disclosure" onToggle={(e) => setMonthly(e.currentTarget.open)}>
|
||||
<summary>个人月明细</summary>
|
||||
{monthly ? <QAMonthly /> : null}
|
||||
</details>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { it, expect } from 'vitest'
|
||||
import { QADashboardDrawing } from './QADashboardDrawing'
|
||||
import { dashboardFixture } from './qaDashboard.fixture'
|
||||
import { parseQADashboard } from './qaDashboardData'
|
||||
it('draws all eleven panels as a self-contained exportable SVG without HTML execution', () => {
|
||||
const html = renderToStaticMarkup(<QADashboardDrawing data={parseQADashboard(dashboardFixture)} width={1280} />)
|
||||
expect((html.match(/data-panel=/g) || []).length).toBe(11)
|
||||
for (const title of [
|
||||
'问题总数',
|
||||
'本周新增',
|
||||
'覆盖率',
|
||||
'正确率',
|
||||
'问题类型分布',
|
||||
'产品问题排行',
|
||||
'问题趋势',
|
||||
'区域平均使用频率',
|
||||
'区域使用覆盖率',
|
||||
'覆盖率趋势',
|
||||
'正确率趋势',
|
||||
])
|
||||
expect(html).toContain(title)
|
||||
expect(html).toContain('<img src=x')
|
||||
expect(html).not.toContain('<foreignObject')
|
||||
expect(html).not.toContain('<img src=x')
|
||||
expect(html).toContain('data-frozen="missing"')
|
||||
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)
|
||||
expect(html).toContain('viewBox="0 0 350 ')
|
||||
})
|
||||
@@ -0,0 +1,589 @@
|
||||
import type { ReactNode, Ref } from 'react'
|
||||
import type { QADashboardData, DashboardCount, DashboardRegion } from './qaDashboardData'
|
||||
import type { QualityRate } from './qaQuality'
|
||||
import { currentQAWeek } from './qaWeeks'
|
||||
interface Box {
|
||||
x: number
|
||||
y: number
|
||||
w: number
|
||||
h: number
|
||||
}
|
||||
const blue = '#3274e6',
|
||||
ink = '#23344d',
|
||||
muted = '#7a8799',
|
||||
line = '#eaf0f7'
|
||||
const colors = [blue, '#59a9f3', '#69c6bc', '#f3c25a', '#f39b6c', '#9b8ade', '#86b8a1', '#d6a3cf', '#8aacc9', '#c4cb76']
|
||||
const number = (n: number) => new Intl.NumberFormat('zh-CN').format(n)
|
||||
const pct = (n: number | null) => (n === null ? '—' : `${n.toFixed(1)}%`)
|
||||
function wrap(value: string, width: number, size = 12): string[] {
|
||||
const max = Math.max(2, width / size),
|
||||
out: string[] = []
|
||||
let row = '',
|
||||
units = 0
|
||||
for (const c of Array.from(value)) {
|
||||
const next = c.charCodeAt(0) < 128 ? 0.57 : 1
|
||||
if (row && units + next > max) {
|
||||
out.push(row)
|
||||
row = ''
|
||||
units = 0
|
||||
}
|
||||
row += c
|
||||
units += next
|
||||
}
|
||||
if (row || !out.length) out.push(row)
|
||||
return out
|
||||
}
|
||||
function Text({
|
||||
value,
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
size = 12,
|
||||
fill = ink,
|
||||
weight = 400,
|
||||
anchor = 'start',
|
||||
}: {
|
||||
value: string
|
||||
x: number
|
||||
y: number
|
||||
width: number
|
||||
size?: number
|
||||
fill?: string
|
||||
weight?: number
|
||||
anchor?: 'start' | 'middle' | 'end'
|
||||
}) {
|
||||
return (
|
||||
<text x={x} y={y} fontSize={size} fill={fill} fontWeight={weight} textAnchor={anchor}>
|
||||
{wrap(value, width, size).map((row, i) => (
|
||||
<tspan key={i} x={x} dy={i ? size * 1.35 : 0}>
|
||||
{row}
|
||||
</tspan>
|
||||
))}
|
||||
</text>
|
||||
)
|
||||
}
|
||||
function Panel({
|
||||
box,
|
||||
title,
|
||||
en,
|
||||
id,
|
||||
children,
|
||||
tint = '#fff',
|
||||
}: {
|
||||
box: Box
|
||||
title: string
|
||||
en: string
|
||||
id: string
|
||||
children: ReactNode
|
||||
tint?: string
|
||||
}) {
|
||||
return (
|
||||
<g data-panel={id} transform={`translate(${box.x} ${box.y})`}>
|
||||
<rect width={box.w} height={box.h} rx={7} fill={tint} />
|
||||
<text x={16} y={25} fontSize={14} fontWeight={650} fill={ink}>
|
||||
{title}
|
||||
</text>
|
||||
<text x={16} y={43} fontSize={10.5} fill={muted}>
|
||||
{en}
|
||||
</text>
|
||||
{children}
|
||||
</g>
|
||||
)
|
||||
}
|
||||
function Metric({
|
||||
box,
|
||||
value,
|
||||
title,
|
||||
en,
|
||||
id,
|
||||
tint,
|
||||
color,
|
||||
subtitle,
|
||||
}: {
|
||||
box: Box
|
||||
value: number
|
||||
title: string
|
||||
en: string
|
||||
id: string
|
||||
tint: string
|
||||
color: string
|
||||
subtitle: string
|
||||
}) {
|
||||
const text = number(value),
|
||||
size = Math.min(box.w < 220 ? 40 : 54, (box.w - 32) / (text.length * 0.62))
|
||||
return (
|
||||
<Panel box={box} title={title} en={en} id={id} tint={tint}>
|
||||
<text x={16} y={box.h - 43} fontSize={size} fill={color} fontWeight={700} data-value={value}>
|
||||
{text}
|
||||
</text>
|
||||
<text x={16} y={box.h - 17} fill={muted} fontSize={11}>
|
||||
{subtitle}
|
||||
</text>
|
||||
</Panel>
|
||||
)
|
||||
}
|
||||
function polar(cx: number, cy: number, r: number, degrees: number) {
|
||||
const a = (degrees * Math.PI) / 180
|
||||
return { x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) }
|
||||
}
|
||||
function arc(cx: number, cy: number, r: number, start: number, end: number) {
|
||||
const a = polar(cx, cy, r, start),
|
||||
b = polar(cx, cy, r, end)
|
||||
return `M ${a.x} ${a.y} A ${r} ${r} 0 ${end - start > 180 ? 1 : 0} 1 ${b.x} ${b.y}`
|
||||
}
|
||||
function Gauge({ box, rate, title, en, id }: { box: Box; rate: QualityRate; title: string; en: string; id: string }) {
|
||||
const r = Math.min(42, box.w * 0.27),
|
||||
cx = box.w / 2,
|
||||
cy = 94,
|
||||
d = arc(cx, cy, r, 135, 405)
|
||||
return (
|
||||
<Panel box={box} title={title} en={en} id={id}>
|
||||
<title>{`${title}:${rate.numerator} / ${rate.denominator};分母为有效已评估记录`}</title>
|
||||
<path d={d} fill="none" stroke="#e8ecf2" strokeWidth={8} strokeLinecap="round" />
|
||||
{rate.percent !== null && rate.percent > 0 ? (
|
||||
<path
|
||||
d={d}
|
||||
fill="none"
|
||||
stroke={blue}
|
||||
strokeWidth={8}
|
||||
strokeLinecap="round"
|
||||
pathLength={100}
|
||||
strokeDasharray={`${rate.percent} 100`}
|
||||
/>
|
||||
) : null}
|
||||
<text
|
||||
x={cx}
|
||||
y={cy + 6}
|
||||
textAnchor="middle"
|
||||
fontSize={box.w < 220 ? 22 : 27}
|
||||
fontWeight={650}
|
||||
fill={ink}
|
||||
data-value={rate.percent ?? 'unknown'}
|
||||
>
|
||||
{pct(rate.percent)}
|
||||
</text>
|
||||
<text x={cx} y={box.h - 14} fontSize={11} fill={muted} textAnchor="middle">
|
||||
{rate.denominator ? `${number(rate.numerator)} / ${number(rate.denominator)}` : '暂无有效分母'}
|
||||
</text>
|
||||
</Panel>
|
||||
)
|
||||
}
|
||||
function pieHeight(points: DashboardCount[], w: number) {
|
||||
const mobile = w < 500,
|
||||
legendW = mobile ? w - 60 : w * 0.45
|
||||
return Math.max(
|
||||
mobile ? 270 : 300,
|
||||
(mobile ? 225 : 65) + points.reduce((n, p) => n + Math.max(24, wrap(p.label, legendW - 85).length * 16 + 9), 0)
|
||||
)
|
||||
}
|
||||
function Pie({ box, points }: { box: Box; points: DashboardCount[] }) {
|
||||
const mobile = box.w < 500,
|
||||
total = points.reduce((n, p) => n + p.count, 0),
|
||||
legendW = mobile ? box.w - 32 : box.w * 0.47,
|
||||
cx = mobile ? box.w / 2 : box.w * 0.76,
|
||||
cy = mobile ? 135 : Math.max(155, box.h / 2),
|
||||
radius = Math.min(mobile ? 73 : 112, box.w * (mobile ? 0.25 : 0.21))
|
||||
let angle = -90,
|
||||
legendY = mobile ? 236 : 76
|
||||
return (
|
||||
<Panel box={box} title="问题类型分布" en="Issue Type Distribution" id="issue-types">
|
||||
{!total ? (
|
||||
<text x={box.w / 2} y={box.h / 2} textAnchor="middle" fill={muted} fontSize={13}>
|
||||
暂无分类记录
|
||||
</text>
|
||||
) : null}
|
||||
{points.map((point, i) => {
|
||||
const start = angle
|
||||
angle += (point.count / total) * 360
|
||||
const a = polar(cx, cy, radius, start),
|
||||
b = polar(cx, cy, radius, angle)
|
||||
const y = legendY
|
||||
legendY += Math.max(24, wrap(point.label, legendW - 85).length * 16 + 9)
|
||||
return (
|
||||
<g key={point.label}>
|
||||
{points.length === 1 ? (
|
||||
<circle cx={cx} cy={cy} r={radius} fill={colors[i % colors.length]} />
|
||||
) : (
|
||||
<path
|
||||
d={`M ${cx} ${cy} L ${a.x} ${a.y} A ${radius} ${radius} 0 ${angle - start > 180 ? 1 : 0} 1 ${b.x} ${b.y} Z`}
|
||||
fill={colors[i % colors.length]}
|
||||
stroke="#fff"
|
||||
strokeWidth={1}
|
||||
/>
|
||||
)}
|
||||
<title>{`${point.label}:${point.count}(${((point.count / total) * 100).toFixed(1)}%)`}</title>
|
||||
<circle cx={22} cy={y - 4} r={4} fill={colors[i % colors.length]} />
|
||||
<Text x={34} y={y} width={legendW - 91} value={point.label} size={11.5} />
|
||||
<text x={legendW + 8} y={y} textAnchor="end" fill={ink} fontSize={11.5}>
|
||||
{number(point.count)}
|
||||
</text>
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
</Panel>
|
||||
)
|
||||
}
|
||||
function productRows(points: DashboardCount[], w: number) {
|
||||
return points.map((p) => ({ point: p, lines: wrap(p.label, Math.max(70, w * 0.3), 11) }))
|
||||
}
|
||||
function productHeight(points: DashboardCount[], w: number) {
|
||||
return Math.max(300, 75 + productRows(points, w).reduce((n, r) => n + Math.max(30, r.lines.length * 15 + 10), 0))
|
||||
}
|
||||
function Products({ box, points }: { box: Box; points: DashboardCount[] }) {
|
||||
const left = Math.max(85, box.w * 0.32),
|
||||
right = box.w - 58,
|
||||
max = Math.max(1, ...points.map((p) => p.count))
|
||||
let y = 78
|
||||
return (
|
||||
<Panel box={box} title="产品问题排行" en="Product Issue Ranking" id="products">
|
||||
{points.length ? (
|
||||
productRows(points, box.w).map(({ point, lines }) => {
|
||||
const at = y
|
||||
y += Math.max(30, lines.length * 15 + 10)
|
||||
return (
|
||||
<g key={point.label}>
|
||||
<title>{`${point.label}:${point.count}`}</title>
|
||||
<Text x={16} y={at + 2} width={left - 26} value={point.label} size={11} />
|
||||
<rect
|
||||
x={left}
|
||||
y={at - 11}
|
||||
width={Math.max(1, (point.count / max) * (right - left))}
|
||||
height={15}
|
||||
rx={2}
|
||||
fill={blue}
|
||||
/>
|
||||
<text x={left + (point.count / max) * (right - left) + 5} y={at + 1} fontSize={11} fill={ink}>
|
||||
{number(point.count)}
|
||||
</text>
|
||||
</g>
|
||||
)
|
||||
})
|
||||
) : (
|
||||
<text x={16} y={100} fill={muted} fontSize={13}>
|
||||
暂无分类记录
|
||||
</text>
|
||||
)}
|
||||
</Panel>
|
||||
)
|
||||
}
|
||||
interface PlotPoint {
|
||||
label: string
|
||||
value: number | null
|
||||
hint: string
|
||||
frozen?: boolean
|
||||
}
|
||||
function Plot({
|
||||
box,
|
||||
title,
|
||||
en,
|
||||
id,
|
||||
points,
|
||||
percent = false,
|
||||
}: {
|
||||
box: Box
|
||||
title: string
|
||||
en: string
|
||||
id: string
|
||||
points: PlotPoint[]
|
||||
percent?: boolean
|
||||
}) {
|
||||
const left = 44,
|
||||
right = box.w - 22,
|
||||
top = 74,
|
||||
bottom = box.h - 47,
|
||||
max = percent ? 100 : Math.max(4, Math.ceil(Math.max(0, ...points.map((p) => p.value ?? 0)) / 4) * 4),
|
||||
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) {
|
||||
open = false
|
||||
continue
|
||||
}
|
||||
path += `${open ? 'L' : 'M'} ${x(i)} ${y(value)} `
|
||||
open = true
|
||||
}
|
||||
const every = Math.max(1, Math.ceil(points.length / (box.w < 420 ? 5 : 8)))
|
||||
return (
|
||||
<Panel box={box} title={title} en={en} id={id}>
|
||||
{Array.from({ length: 5 }, (_, i) => (
|
||||
<g key={i}>
|
||||
<line x1={left} x2={right} y1={y((max * i) / 4)} y2={y((max * i) / 4)} stroke={line} />
|
||||
<text x={left - 9} y={y((max * i) / 4) + 4} textAnchor="end" fill={muted} fontSize={10}>
|
||||
{(max * i) / 4}
|
||||
{percent ? '%' : ''}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
{path ? <path d={path} fill="none" stroke={blue} strokeWidth={2} data-series={id} /> : null}
|
||||
{points.map((point, i) => (
|
||||
<g
|
||||
key={point.label}
|
||||
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)}
|
||||
</text>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
{i % every === 0 || i === points.length - 1 ? (
|
||||
<text x={x(i)} y={bottom + 22} textAnchor="middle" fill={muted} fontSize={10}>
|
||||
{point.label}
|
||||
</text>
|
||||
) : null}
|
||||
</g>
|
||||
))}
|
||||
{!points.some((p) => p.value !== null) ? (
|
||||
<text x={(left + right) / 2} y={(top + bottom) / 2} fill={muted} textAnchor="middle" fontSize={12}>
|
||||
{percent ? '暂无冻结快照' : '暂无数据'}
|
||||
</text>
|
||||
) : null}
|
||||
</Panel>
|
||||
)
|
||||
}
|
||||
function regionalHeight(regions: DashboardRegion[], w: number) {
|
||||
return Math.max(
|
||||
290,
|
||||
130 + regions.reduce((n, r) => n + Math.max(34, wrap(r.name, Math.max(70, w - 125), 11.5).length * 16 + 12), 0)
|
||||
)
|
||||
}
|
||||
function RegionTable({
|
||||
box,
|
||||
regions,
|
||||
frequency,
|
||||
month,
|
||||
}: {
|
||||
box: Box
|
||||
regions: DashboardRegion[]
|
||||
frequency: boolean
|
||||
month: string
|
||||
}) {
|
||||
const rows = [...regions].sort((a, b) => {
|
||||
const av = frequency ? a.frequency : a.usage_coverage.percent,
|
||||
bv = frequency ? b.frequency : b.usage_coverage.percent
|
||||
return (bv ?? -1) - (av ?? -1) || a.name.localeCompare(b.name, 'zh-CN')
|
||||
})
|
||||
let y = 104
|
||||
return (
|
||||
<Panel
|
||||
box={box}
|
||||
title={frequency ? '区域平均使用频率' : '区域使用覆盖率'}
|
||||
en={frequency ? 'Average usage frequency' : 'Usage coverage'}
|
||||
id={frequency ? 'frequency' : 'usage-coverage'}
|
||||
>
|
||||
<rect x={10} y={57} width={box.w - 20} height={box.h - 68} rx={5} fill="#fff" stroke="#e4eaf2" />
|
||||
<text x={19} y={77} fontSize={10.5} fill={muted}>
|
||||
排名
|
||||
</text>
|
||||
<text x={58} y={77} fontSize={10.5} fill={muted}>
|
||||
区域
|
||||
</text>
|
||||
<text x={box.w - 19} y={77} textAnchor="end" fontSize={10.5} fill={muted}>
|
||||
{frequency ? '人均次数' : '使用覆盖率'}
|
||||
</text>
|
||||
<line x1={15} x2={box.w - 15} y1={85} y2={85} stroke={line} />
|
||||
{rows.map((r, i) => {
|
||||
const at = y,
|
||||
value = frequency ? r.frequency : r.usage_coverage.percent
|
||||
const h = Math.max(34, wrap(r.name, Math.max(70, box.w - 125), 11.5).length * 16 + 12)
|
||||
y += h
|
||||
return (
|
||||
<g key={r.id}>
|
||||
<title>{`${r.name};${month}月内提问 ${r.questions} 次;去重使用 ${r.users ?? '未知'} 人 / 通讯录归属 ${r.roster_people ?? '未知'} 人`}</title>
|
||||
{i % 2 === 0 ? <rect x={11} y={at - 15} width={box.w - 22} height={h} fill="#f7faff" /> : null}
|
||||
{value !== null && i < 3 ? (
|
||||
<circle cx={30} cy={at - 4} r={9} fill={['#e9bd54', '#a8b6c9', '#dc9c73'][i]} />
|
||||
) : null}
|
||||
<text x={30} y={at} textAnchor="middle" fontSize={10.5} fill={value !== null && i < 3 ? '#fff' : muted}>
|
||||
{value === null ? '—' : i + 1}
|
||||
</text>
|
||||
<Text x={53} y={at} width={Math.max(70, box.w - 125)} value={r.name} size={11.5} />
|
||||
<text x={box.w - 19} y={at} textAnchor="end" fontSize={12} fill={ink}>
|
||||
{value === null ? '—' : frequency ? value.toFixed(2) : `${value.toFixed(1)}%`}
|
||||
</text>
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
<text x={box.w - 17} y={box.h - 17} textAnchor="end" fontSize={9.5} fill={muted}>
|
||||
{month}月累计
|
||||
</text>
|
||||
</Panel>
|
||||
)
|
||||
}
|
||||
export function QADashboardDrawing({
|
||||
data,
|
||||
width,
|
||||
svgRef,
|
||||
}: {
|
||||
data: QADashboardData
|
||||
width: number
|
||||
svgRef?: Ref<SVGSVGElement>
|
||||
}) {
|
||||
const w = Math.max(240, Math.round(width)),
|
||||
pad = w < 700 ? 10 : 16,
|
||||
gap = w < 700 ? 12 : 18,
|
||||
inner = w - pad * 2,
|
||||
mobile = w < 700,
|
||||
unit = (inner - gap * 3) / 4,
|
||||
week = currentQAWeek(new Date(data.week_start)),
|
||||
filterLines = wrap(data.keyword ? `关键词:${data.keyword}` : '', inner - 16, 11),
|
||||
header = 62 + (data.keyword ? filterLines.length * 15 : 0),
|
||||
metricH = mobile ? 154 : 166
|
||||
const metrics: Box[] = Array.from({ length: 4 }, (_, i) =>
|
||||
mobile
|
||||
? {
|
||||
x: pad + ((i % 2) * (inner + gap)) / 2,
|
||||
y: header + Math.floor(i / 2) * (metricH + gap),
|
||||
w: (inner - gap) / 2,
|
||||
h: metricH,
|
||||
}
|
||||
: { x: pad + i * (unit + gap), y: header, w: unit, h: metricH }
|
||||
)
|
||||
let cursor = header + (mobile ? 2 * metricH + gap : metricH) + gap
|
||||
const pieW = mobile ? inner : (inner - gap) * 0.54,
|
||||
productW = mobile ? inner : inner - gap - pieW,
|
||||
pieH = pieHeight(data.issue_types, pieW),
|
||||
productsH = productHeight(data.products, productW),
|
||||
row2H = Math.max(pieH, productsH)
|
||||
const pie: Box = { x: pad, y: cursor, w: pieW, h: mobile ? pieH : row2H },
|
||||
products: Box = {
|
||||
x: mobile ? pad : pad + pieW + gap,
|
||||
y: mobile ? cursor + pieH + gap : cursor,
|
||||
w: productW,
|
||||
h: mobile ? productsH : row2H,
|
||||
}
|
||||
cursor += mobile ? pieH + productsH + gap * 2 : row2H + gap
|
||||
const trendW = mobile ? inner : unit * 2 + gap,
|
||||
regionW = mobile ? inner : unit,
|
||||
regionH = regionalHeight(data.regions, regionW),
|
||||
row3H = Math.max(290, regionH)
|
||||
const trend: Box = { x: pad, y: cursor, w: trendW, h: mobile ? 270 : row3H },
|
||||
freq: Box = {
|
||||
x: mobile ? pad : pad + trendW + gap,
|
||||
y: mobile ? cursor + trend.h + gap : cursor,
|
||||
w: regionW,
|
||||
h: mobile ? regionH : row3H,
|
||||
},
|
||||
usage: Box = {
|
||||
x: mobile ? pad : pad + trendW + regionW + gap * 2,
|
||||
y: mobile ? cursor + trend.h + regionH + gap * 2 : cursor,
|
||||
w: regionW,
|
||||
h: mobile ? regionH : row3H,
|
||||
}
|
||||
cursor += mobile ? trend.h + regionH * 2 + gap * 3 : row3H + gap
|
||||
const historyW = mobile ? inner : (inner - gap) / 2,
|
||||
coverage: Box = { x: pad, y: cursor, w: historyW, h: 270 },
|
||||
accuracy: Box = {
|
||||
x: mobile ? pad : pad + historyW + gap,
|
||||
y: mobile ? cursor + 270 + gap : cursor,
|
||||
w: historyW,
|
||||
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 month = new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7)
|
||||
return (
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="qa-dashboard-svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="100%"
|
||||
viewBox={`0 0 ${w} ${height}`}
|
||||
role="img"
|
||||
aria-label="完整十一项问题统计看板"
|
||||
style={{
|
||||
display: 'block',
|
||||
fontFamily: 'Arial, "Noto Sans CJK SC", "Microsoft YaHei", sans-serif',
|
||||
fontVariantNumeric: 'tabular-nums',
|
||||
background: '#fff',
|
||||
}}
|
||||
>
|
||||
<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}>
|
||||
问题统计看板
|
||||
</text>
|
||||
<text x={w - pad - 6} y={27} textAnchor="end" fontSize={12} fill={muted}>
|
||||
{week.year} · W{String(week.week).padStart(2, '0')}
|
||||
</text>
|
||||
<text x={pad + 6} y={46} fontSize={10.5} fill={muted}>
|
||||
{data.week_start.slice(0, 10)} 起的自然周 · 区域统计 {month} 月累计
|
||||
</text>
|
||||
{data.keyword ? (
|
||||
<Text x={pad + 6} y={62} width={inner - 16} value={`关键词:${data.keyword}`} size={11} fill={muted} />
|
||||
) : null}
|
||||
<Metric
|
||||
box={metrics[0]}
|
||||
title="问题总数"
|
||||
en="Total Issues"
|
||||
id="total"
|
||||
value={data.total_issues}
|
||||
tint="#fff4e2"
|
||||
color="#c69b00"
|
||||
subtitle="所选周截止前累计"
|
||||
/>
|
||||
<Metric
|
||||
box={metrics[1]}
|
||||
title="本周新增"
|
||||
en="New This week"
|
||||
id="new-week"
|
||||
value={data.new_this_week}
|
||||
tint="#ececff"
|
||||
color="#4056d6"
|
||||
subtitle="所选自然周"
|
||||
/>
|
||||
<Gauge box={metrics[2]} title="覆盖率" en="Coverage Rate" id="coverage" rate={data.quality.rates.coverage} />
|
||||
<Gauge box={metrics[3]} title="正确率" en="Accuracy Rate" id="accuracy" rate={data.quality.rates.correctness} />
|
||||
<Pie box={pie} points={data.issue_types} />
|
||||
<Products box={products} points={data.products} />
|
||||
<Plot
|
||||
box={trend}
|
||||
title="问题趋势"
|
||||
en="Issue Trend"
|
||||
id="issue-trend"
|
||||
points={data.daily.map((p) => ({ label: p.date.slice(5), value: p.count, hint: `${p.date}:${p.count} 条` }))}
|
||||
/>
|
||||
<RegionTable box={freq} regions={data.regions} frequency month={month} />
|
||||
<RegionTable box={usage} regions={data.regions} frequency={false} month={month} />
|
||||
<Plot
|
||||
box={coverage}
|
||||
title="覆盖率趋势"
|
||||
en="Coverage Rate Trend"
|
||||
id="coverage-trend"
|
||||
points={frozen(false)}
|
||||
percent
|
||||
/>
|
||||
<Plot
|
||||
box={accuracy}
|
||||
title="正确率趋势"
|
||||
en="Accuracy Rate Trend"
|
||||
id="accuracy-trend"
|
||||
points={frozen(true)}
|
||||
percent
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { QAMirrorSyncView } from './QAMirrorSync'
|
||||
import type { QAMirrorStatus } from './qaMirror'
|
||||
const base: QAMirrorStatus = {
|
||||
mode: 'local',
|
||||
ready: false,
|
||||
blocked: false,
|
||||
revision: 0,
|
||||
records: 0,
|
||||
source_observed_at: null,
|
||||
last_success_at: null,
|
||||
next_sync_at: null,
|
||||
error_code: 'initial_sync_pending',
|
||||
interval_seconds: 300,
|
||||
worker_ready: true,
|
||||
job: null,
|
||||
}
|
||||
describe('local Q&A synchronization strip', () => {
|
||||
it('shows pending first import rather than a successfully empty dataset', () => {
|
||||
const html = renderToStaticMarkup(<QAMirrorSyncView status={base} error="" submitting={false} onSync={vi.fn()} />)
|
||||
expect(html).toContain('本地数据库')
|
||||
expect(html).toContain('首次同步尚未完成')
|
||||
expect(html).toContain('立即同步')
|
||||
expect(html).not.toContain('每 5 分钟后台同步 · 查询不请求远端')
|
||||
})
|
||||
it('keeps the last-good dataset visibly stale after a failed sync', () => {
|
||||
const status = {
|
||||
...base,
|
||||
ready: true,
|
||||
revision: 1,
|
||||
records: 639,
|
||||
last_success_at: '2026-10-18T00:00:00Z',
|
||||
source_observed_at: '2026-10-18T00:00:00Z',
|
||||
next_sync_at: '2026-10-18T00:05:00Z',
|
||||
error_code: 'mirror_source_unavailable',
|
||||
}
|
||||
const html = renderToStaticMarkup(<QAMirrorSyncView status={status} error="" submitting={false} onSync={vi.fn()} />)
|
||||
expect(html).toContain('639')
|
||||
expect(html).toContain('保留上次成功数据')
|
||||
expect(html).not.toContain('不承诺实时源快照')
|
||||
})
|
||||
it('distinguishes authorization blocking from an ordinary network failure', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<QAMirrorSyncView
|
||||
status={{ ...base, blocked: true, error_code: 'mirror_source_authorization_failed' }}
|
||||
error=""
|
||||
submitting={false}
|
||||
onSync={vi.fn()}
|
||||
/>
|
||||
)
|
||||
expect(html).toContain('权限校验未通过')
|
||||
expect(html).toContain('本地读取已阻断')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,123 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { fetchQAMirrorStatus, mirrorSyncActive, mirrorStateChanged, startQAMirrorSync } from './qaMirror'
|
||||
import type { QAMirrorStatus } from './qaMirror'
|
||||
import { newOperationID } from './operationKey'
|
||||
import './qaMirror.css'
|
||||
interface ViewProps {
|
||||
status: QAMirrorStatus | null
|
||||
error: string
|
||||
submitting: boolean
|
||||
onSync: () => void
|
||||
}
|
||||
export function QAMirrorSyncView(p: ViewProps) {
|
||||
const s = p.status
|
||||
const active = mirrorSyncActive(s)
|
||||
return (
|
||||
<section className="qa-mirror-sync" aria-label="问答本地数据库与同步状态">
|
||||
<div className="qa-mirror-sync-line">
|
||||
<strong>本地数据库</strong>
|
||||
|
||||
{s?.ready ? <span>已同步 {s.records} 条</span> : null}
|
||||
<button type="button" onClick={p.onSync} disabled={p.submitting || !s?.worker_ready || active}>
|
||||
{p.submitting ? '正在入队…' : active ? '后台同步中…' : '立即同步'}
|
||||
</button>
|
||||
</div>
|
||||
<div role="status" className="qa-ops-muted">
|
||||
{!s
|
||||
? '正在读取同步状态…'
|
||||
: s.blocked
|
||||
? '源端权限校验未通过,本地读取已阻断;修复授权后可重新同步。'
|
||||
: !s.ready
|
||||
? '首次同步尚未完成,暂不把未同步数据视为空结果。'
|
||||
: ''}
|
||||
{s?.job && active ? (
|
||||
<span>
|
||||
{' '}
|
||||
{s.job.expected > 0
|
||||
? `已检查 ${s.job.loaded} / ${s.job.expected} 条,取回变化 ${s.job.changed} 条。`
|
||||
: '正在检查源端变化。'}
|
||||
</span>
|
||||
) : null}
|
||||
{s?.error_code && s.error_code !== 'initial_sync_pending' && !s.blocked ? (
|
||||
<span className="qa-ops-warning"> 最近同步失败,保留上次成功数据;请检查源端连接后重试。</span>
|
||||
) : null}
|
||||
{s && !s.worker_ready ? <span className="qa-ops-warning"> 同步执行器未在线。</span> : null}
|
||||
</div>
|
||||
{p.error ? (
|
||||
<p className="error-banner" role="alert">
|
||||
{p.error}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
export function QAMirrorSync({ onChanged }: { onChanged: () => void }) {
|
||||
const [status, setStatus] = useState<QAMirrorStatus | null>(null),
|
||||
[error, setError] = useState(''),
|
||||
[submitting, setSubmitting] = useState(false)
|
||||
const key = useRef('')
|
||||
const acceptedJob = useRef('')
|
||||
const changed = useRef(onChanged)
|
||||
changed.current = onChanged
|
||||
const observed = useRef<{ revision: number; blocked: boolean; ready: boolean } | undefined>(undefined)
|
||||
const kick = useRef<() => void>(() => {})
|
||||
useEffect(() => {
|
||||
let disposed = false,
|
||||
timer: ReturnType<typeof setTimeout> | undefined
|
||||
const controller = new AbortController()
|
||||
let inFlight = false
|
||||
const read = async () => {
|
||||
if (disposed || inFlight) return
|
||||
inFlight = true
|
||||
let next = 15000
|
||||
try {
|
||||
const fresh = await fetchQAMirrorStatus(controller.signal)
|
||||
if (disposed) return
|
||||
const previous = observed.current
|
||||
observed.current = { revision: fresh.revision, blocked: fresh.blocked, ready: fresh.ready }
|
||||
setStatus(fresh)
|
||||
setError('')
|
||||
if (mirrorStateChanged(previous, fresh)) changed.current()
|
||||
if (!mirrorSyncActive(fresh) && fresh.job?.id === acceptedJob.current) {
|
||||
key.current = ''
|
||||
acceptedJob.current = ''
|
||||
}
|
||||
if (mirrorSyncActive(fresh) || !fresh.ready) next = 2500
|
||||
} catch (e) {
|
||||
if (!disposed) setError(e instanceof Error ? e.message : '本地同步状态读取失败')
|
||||
} finally {
|
||||
inFlight = false
|
||||
if (!disposed) {
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(() => void read(), next)
|
||||
}
|
||||
}
|
||||
}
|
||||
kick.current = () => {
|
||||
clearTimeout(timer)
|
||||
void read()
|
||||
}
|
||||
void read()
|
||||
return () => {
|
||||
disposed = true
|
||||
controller.abort()
|
||||
clearTimeout(timer)
|
||||
kick.current = () => {}
|
||||
}
|
||||
}, [])
|
||||
const synchronize = async () => {
|
||||
if (submitting || mirrorSyncActive(status)) return
|
||||
setSubmitting(true)
|
||||
setError('')
|
||||
if (!key.current) key.current = newOperationID()
|
||||
try {
|
||||
acceptedJob.current = await startQAMirrorSync(key.current)
|
||||
kick.current()
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : '同步请求未确认,请重试,已有本地数据不变')
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
return <QAMirrorSyncView status={status} error={error} submitting={submitting} onSync={() => void synchronize()} />
|
||||
}
|
||||
@@ -14,9 +14,17 @@ describe('personal monthly view', () => {
|
||||
onPage={() => {}}
|
||||
/>
|
||||
)
|
||||
for (const text of ['本源零记录', '当月进度', '姓名未同步', '不是考核名单', '当前通讯录', '未关联'])
|
||||
expect(html).toContain(text)
|
||||
for (const text of ['本源零记录', '当月进度', '姓名未同步', '当前通讯录', '未关联']) expect(html).toContain(text)
|
||||
expect(html).not.toContain('<script>')
|
||||
for (const text of [
|
||||
'不是考核名单',
|
||||
'本次读取:',
|
||||
'0 仅表示本源未关联到提问',
|
||||
'成功/失败不是答案正确性结论',
|
||||
'上方全名册指标不随人员筛选变化',
|
||||
])
|
||||
expect(html).not.toContain(text)
|
||||
expect(html).toContain('qa-ops-page-bar')
|
||||
expect(html).not.toContain('达标率')
|
||||
expect(html).not.toContain('绩效合格')
|
||||
})
|
||||
|
||||
+10
-14
@@ -36,24 +36,20 @@ export function QAMonthlyView({ data, loading, error, onRetry, onPage }: ViewPro
|
||||
<span>仅 DobotAI 2.0 · 北京时间</span>
|
||||
</div>
|
||||
<p className="qa-ops-muted">
|
||||
全名册:{data.roster_people} 人 · 已关联提问 {data.used_people} 人 · 本源零记录 {data.zero_people}{' '}
|
||||
人。名册来自当前通讯录,不是在职证明,也不是考核名单。
|
||||
当前通讯录:{data.roster_people} 人 · 已关联提问 {data.used_people} 人 · 本源零记录 {data.zero_people} 人
|
||||
</p>
|
||||
<p className="qa-ops-muted">
|
||||
本月范围内 {data.questions} 条问答,已关联 {data.linked_questions} 条,未关联 {data.unresolved_questions}{' '}
|
||||
条。0 仅表示本源未关联到提问,不等于实际未使用;成功/失败不是答案正确性结论。
|
||||
本月问答 {data.questions} 条 · 已关联 {data.linked_questions} 条 · 未关联 {data.unresolved_questions} 条
|
||||
</p>
|
||||
{data.missing_names > 0 ? (
|
||||
<p className="qa-ops-warning">
|
||||
{data.missing_names} 人姓名未同步,请重新同步通讯录;不根据姓名猜身份,不用原始标识代替姓名。
|
||||
</p>
|
||||
<p className="qa-ops-warning">{data.missing_names} 人姓名未同步,请重新同步通讯录。</p>
|
||||
) : null}
|
||||
<details className="qa-ops-organization">
|
||||
<summary>统计范围与组织版本</summary>
|
||||
<p>
|
||||
范围:{stamp(data.start)} 至 {stamp(data.end)}(不含结束)。当前通讯录同步于{' '}
|
||||
{stamp(data.organization.synced_at!)}
|
||||
;不代表提问时部门或正式绩效分母。自然月时间范围完整不代表已归档全部历史。目录:
|
||||
;目录:
|
||||
{data.organization.directory_id};区域:{data.organization.revision_id || '未保存'}。
|
||||
</p>
|
||||
</details>
|
||||
@@ -61,7 +57,6 @@ export function QAMonthlyView({ data, loading, error, onRetry, onPage }: ViewPro
|
||||
<span>
|
||||
符合人员筛选 {data.total} 人 · 第 {data.page} 页
|
||||
</span>
|
||||
<span>上方全名册指标不随人员筛选变化</span>
|
||||
</div>
|
||||
{data.rows.length ? (
|
||||
<div className="qa-ops-table-scroll" aria-label="个人月明细表格滚动区" tabIndex={0}>
|
||||
@@ -78,7 +73,7 @@ export function QAMonthlyView({ data, loading, error, onRetry, onPage }: ViewPro
|
||||
<tr key={row.key}>
|
||||
<td>{row.name || '姓名未同步'}</td>
|
||||
<td>{row.departments.join(';') || '无部门记录'}</td>
|
||||
<td>{usageLabels[row.region || row.state]}</td>
|
||||
<td>{usageLabels[row.region || row.state] ?? (row.region || row.state)}</td>
|
||||
<td>{row.questions}</td>
|
||||
<td>{row.succeeded}</td>
|
||||
<td>{row.failed}</td>
|
||||
@@ -89,10 +84,9 @@ export function QAMonthlyView({ data, loading, error, onRetry, onPage }: ViewPro
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<p className="qa-ops-empty">没有符合人员筛选的记录,请调整条件;这不是通讯录为空。</p>
|
||||
<p className="qa-ops-empty">没有符合人员筛选的记录,请调整条件。</p>
|
||||
)}
|
||||
<footer className="qa-ops-page-bar">
|
||||
<span>本次读取:{stamp(data.as_of)}</span>
|
||||
<div>
|
||||
{data.page > 1 ? (
|
||||
<button type="button" onClick={() => onPage(data.page - 1)}>
|
||||
@@ -123,6 +117,7 @@ export function QAMonthly() {
|
||||
const [request, setRequest] = useState<MonthlyQuery>({ month: draft.month })
|
||||
const [data, setData] = useState<MonthlyPeople | null>(null),
|
||||
[options, setOptions] = useState<MonthlyPeople['department_options']>([]),
|
||||
[regionOptions, setRegionOptions] = useState<string[]>([]),
|
||||
[loading, setLoading] = useState(false),
|
||||
[error, setError] = useState('')
|
||||
useEffect(() => {
|
||||
@@ -135,6 +130,7 @@ export function QAMonthly() {
|
||||
if (!controller.signal.aborted) {
|
||||
setData(next)
|
||||
setOptions(next.department_options)
|
||||
setRegionOptions(next.organization.region_names ?? [])
|
||||
}
|
||||
})
|
||||
.catch((reason) => {
|
||||
@@ -202,9 +198,9 @@ export function QAMonthly() {
|
||||
区域 / 状态
|
||||
<select value={draft.region} disabled={loading} onChange={(e) => change('region', e.target.value)}>
|
||||
<option value="">全部区域 / 状态</option>
|
||||
{['国内工业', 'APAC', 'EMEA', 'America', 'unassigned', 'cross_region'].map((key) => (
|
||||
{[...regionOptions, 'unassigned', 'cross_region'].map((key) => (
|
||||
<option key={key} value={key}>
|
||||
{usageLabels[key]}
|
||||
{usageLabels[key] ?? key}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { QAOperationsView } from './QAOperations'
|
||||
import { QAOperationsTabs, QAOperationsView } from './QAOperations'
|
||||
import type { QARecord, QARecordPage } from './qaOps'
|
||||
import { restoreWorkspace } from './workspace'
|
||||
|
||||
@@ -50,6 +50,19 @@ const props = {
|
||||
}
|
||||
|
||||
describe('QA operations workbench', () => {
|
||||
it('uses the four requested destinations in their fixed order', () => {
|
||||
const html = renderToStaticMarkup(<QAOperationsTabs view="records" onChange={vi.fn()} />)
|
||||
const labels = ['问题流水', '问题统计看板', '区域配置', '周报生成']
|
||||
for (const label of labels) expect(html).toContain(label)
|
||||
for (let i = 1; i < labels.length; i++) expect(html.indexOf(labels[i - 1])).toBeLessThan(html.indexOf(labels[i]))
|
||||
expect(html).not.toContain('部门/区域保留源快照')
|
||||
})
|
||||
it('removes explanatory banners without hiding errors or any required column', () => {
|
||||
const html = renderToStaticMarkup(<QAOperationsView {...props} />)
|
||||
expect(html).not.toContain('本次读取')
|
||||
expect(html).not.toContain('固定显示完整字段')
|
||||
expect(html).not.toContain('DobotAI 2.0 / 钉钉')
|
||||
})
|
||||
it('shows all required columns even when empty and keeps false/downvotes visible', () => {
|
||||
const html = renderToStaticMarkup(<QAOperationsView {...props} />)
|
||||
expect(html).toContain('原始问题')
|
||||
|
||||
+127
-126
@@ -5,14 +5,35 @@ import { fetchQARecord, fetchAllQARecords, fetchQAStatus, qaCellValue, qaColumns
|
||||
import type { QAQuery, QARecord, QARecordPage, QAStatus } from './qaOps'
|
||||
import './qaOps.css'
|
||||
import { QARegions } from './QARegions'
|
||||
import { QAUsage } from './QAUsage'
|
||||
import { QAMonthly } from './QAMonthly'
|
||||
import { QAQualityEditor, QAQualityCounts } from './QAQuality'
|
||||
import { QADashboard } from './QADashboard'
|
||||
import { QAWeekly } from './QAWeekly'
|
||||
import { QAQualityEditor } from './QAQuality'
|
||||
import { qualityLabels } from './qaQuality'
|
||||
import { usageLabels } from './qaUsage'
|
||||
import { QAWeekPicker } from './QAWeekPicker'
|
||||
import { QAAnswerMarkdown } from './QAAnswerMarkdown'
|
||||
import { QAMirrorSync } from './QAMirrorSync'
|
||||
import { currentQAWeek, qaDateTimeToISO, qaWeekQueryRange } from './qaWeeks'
|
||||
|
||||
export type QAOpsView = 'records' | 'dashboard' | 'regions' | 'weekly'
|
||||
export function QAOperationsTabs({ view, onChange }: { view: QAOpsView; onChange: (view: QAOpsView) => void }) {
|
||||
return (
|
||||
<nav className="qa-region-tabs" aria-label="问答运营视图">
|
||||
{(
|
||||
[
|
||||
['records', '问题流水'],
|
||||
['dashboard', '问题统计看板'],
|
||||
['regions', '区域配置'],
|
||||
['weekly', '周报生成'],
|
||||
] as const
|
||||
).map(([id, label]) => (
|
||||
<button key={id} type="button" aria-pressed={view === id} onClick={() => onChange(id)}>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
interface ViewProps {
|
||||
onQualitySaved?: (record: QARecord) => void
|
||||
onReloadDetail?: () => void
|
||||
@@ -28,7 +49,6 @@ interface ViewProps {
|
||||
progress?: { loaded: number; total: number }
|
||||
onRetry: () => void
|
||||
}
|
||||
const stateLabels = { disabled: '未配置', unavailable: '连接不可用', blocked: '接入被阻断', connected: '已连接' }
|
||||
const warningLabels: Record<string, string> = {
|
||||
database_temp_enabled: '数据库仍允许临时对象:未视为完全只读验收通过',
|
||||
database_transport_unencrypted: '数据库连接未启用 TLS:上线前须完成传输安全审核',
|
||||
@@ -57,17 +77,8 @@ export function QAOperationsView(props: ViewProps) {
|
||||
? `共 ${page.total} 条 · 已展示 ${page.items.length} 条`
|
||||
: '尚未读取问答'}
|
||||
</span>
|
||||
<span className="qa-ops-source">
|
||||
DobotAI 2.0 / 钉钉 · 独立只读连接{props.status ? ` · ${stateLabels[props.status.state]}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
{page?.organization ? (
|
||||
<p className="qa-ops-muted qa-ops-organization">
|
||||
{page.organization.state === 'ready'
|
||||
? `缺失组织信息按当前通讯录补全(${stamp(page.organization.synced_at!)}),不代表提问时归属。目录:${page.organization.directory_id};区域版本:${page.organization.revision_id || '未保存'}`
|
||||
: '尚无完整通讯录,仅展示源端已有组织快照,不根据姓名推断。'}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{props.status?.warnings.map((warning) => (
|
||||
<p className="qa-ops-warning" key={warning}>
|
||||
{warningLabels[warning] ?? '数据源有待审核的安全告警'}
|
||||
@@ -136,12 +147,7 @@ export function QAOperationsView(props: ViewProps) {
|
||||
) : page && !props.loading && !props.error ? (
|
||||
<p className="qa-ops-empty">没有符合条件的问答,请调整时间范围或关键词。</p>
|
||||
) : null}
|
||||
{page ? (
|
||||
<footer className="qa-ops-page-bar">
|
||||
<span>本次读取:{stamp(page.as_of)} · 固定显示完整字段,左右滚动查看;— 表示暂无数据</span>
|
||||
<span>{page.items.length === page.total ? '已全部展示' : '全量读取尚未完成'}</span>
|
||||
</footer>
|
||||
) : null}
|
||||
|
||||
{showDrawer ? (
|
||||
<>
|
||||
<button
|
||||
@@ -232,6 +238,17 @@ export function QAOperationsView(props: ViewProps) {
|
||||
</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>
|
||||
@@ -240,7 +257,7 @@ export function QAOperationsView(props: ViewProps) {
|
||||
<h4>原始问题</h4>
|
||||
<div className="qa-ops-full-text">{detail.question || '无文本问题'}</div>
|
||||
<h4>AI答案</h4>
|
||||
<div className="qa-ops-full-text">{detail.answer || '尚无答案;不默认判覆盖或正确'}</div>
|
||||
<QAAnswerMarkdown key={detail.id} answer={detail.answer} />
|
||||
<h4>治理侧覆盖复检</h4>
|
||||
<p>
|
||||
{detail.coverage.verdict === 'uncovered'
|
||||
@@ -258,6 +275,7 @@ export function QAOperationsView(props: ViewProps) {
|
||||
<QAQualityEditor
|
||||
key={detail.id}
|
||||
recordId={detail.id}
|
||||
dataset={detail.record_origin ? 'master' : undefined}
|
||||
quality={detail.quality}
|
||||
onSaved={props.onQualitySaved ?? (() => {})}
|
||||
onReload={props.onReloadDetail ?? (() => {})}
|
||||
@@ -297,8 +315,7 @@ function initialDraft() {
|
||||
}
|
||||
|
||||
export function QAOperations() {
|
||||
const [view, setView] = useState<'records' | 'regions' | 'usage'>('records')
|
||||
const [usageMode, setUsageMode] = useState<'regions' | 'monthly'>('regions')
|
||||
const [view, setView] = useState<QAOpsView>('records')
|
||||
const auth = useOptionalAuth()
|
||||
const canRead = auth?.identity?.role === 'admin'
|
||||
const [draft, setDraft] = useState(initialDraft)
|
||||
@@ -309,6 +326,7 @@ export function QAOperations() {
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [revision, setRevision] = useState(0)
|
||||
const [qualityRevision, setQualityRevision] = useState(0)
|
||||
const [mirrorChanged, setMirrorChanged] = useState(false)
|
||||
const [detail, setDetail] = useState<QARecord | null>(null)
|
||||
const [detailLoading, setDetailLoading] = useState(false)
|
||||
const [detailError, setDetailError] = useState<string | null>(null)
|
||||
@@ -330,6 +348,7 @@ export function QAOperations() {
|
||||
if (!query || !canRead) return
|
||||
if (view !== 'records') {
|
||||
setLoading(false)
|
||||
setError(null)
|
||||
detailRequest.current?.abort()
|
||||
setDetail(null)
|
||||
return
|
||||
@@ -348,7 +367,7 @@ export function QAOperations() {
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted) setStatus(null)
|
||||
})
|
||||
void fetchAllQARecords(query, controller.signal, (loaded, total) => {
|
||||
void fetchAllQARecords({ ...query, dataset: 'master' }, controller.signal, (loaded, total) => {
|
||||
if (!controller.signal.aborted) setProgress({ loaded, total })
|
||||
})
|
||||
.then((result) => {
|
||||
@@ -391,7 +410,7 @@ export function QAOperations() {
|
||||
setDetailError(null)
|
||||
setDetailLoading(true)
|
||||
try {
|
||||
const result = await fetchQARecord(id, controller.signal)
|
||||
const result = await fetchQARecord(id, controller.signal, 'master')
|
||||
if (!controller.signal.aborted) setDetail(result)
|
||||
} catch (reason) {
|
||||
if (!controller.signal.aborted) setDetailError(reason instanceof Error ? reason.message : '详情读取失败')
|
||||
@@ -400,19 +419,22 @@ export function QAOperations() {
|
||||
}
|
||||
}
|
||||
const close = () => {
|
||||
if (mirrorChanged) {
|
||||
setMirrorChanged(false)
|
||||
setRevision((v) => v + 1)
|
||||
setQualityRevision((v) => v + 1)
|
||||
}
|
||||
detailRequest.current?.abort()
|
||||
setDetail(null)
|
||||
setDetailError(null)
|
||||
setDetailLoading(false)
|
||||
returnFocus.current?.focus()
|
||||
}
|
||||
const queryView = view === 'records' || view === 'dashboard'
|
||||
return (
|
||||
<section className="qa-ops" aria-label="问答运营">
|
||||
<header className="qa-ops-header">
|
||||
<h2>
|
||||
问答运营 <span>/ {view === 'regions' ? '区域归属' : view === 'usage' ? '使用统计' : '问答记录'}</span>
|
||||
</h2>
|
||||
<p>真实问答只读查询;原始记录、源端判断与治理复检分开保留。</p>
|
||||
<h2>问答运营</h2>
|
||||
</header>
|
||||
{!canRead ? (
|
||||
<p className="error-banner" role="alert">
|
||||
@@ -420,64 +442,48 @@ export function QAOperations() {
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
<nav className="qa-region-tabs" aria-label="问答运营视图">
|
||||
<button type="button" aria-pressed={view === 'records'} onClick={() => setView('records')}>
|
||||
问答记录
|
||||
</button>
|
||||
<button type="button" aria-pressed={view === 'usage'} onClick={() => setView('usage')}>
|
||||
使用统计
|
||||
</button>
|
||||
<button type="button" aria-pressed={view === 'regions'} onClick={() => setView('regions')}>
|
||||
区域使用
|
||||
</button>
|
||||
</nav>
|
||||
{view === 'usage' ? (
|
||||
<nav className="qa-region-tabs" aria-label="使用统计视图">
|
||||
<button type="button" aria-pressed={usageMode === 'regions'} onClick={() => setUsageMode('regions')}>
|
||||
区域汇总
|
||||
</button>
|
||||
<button type="button" aria-pressed={usageMode === 'monthly'} onClick={() => setUsageMode('monthly')}>
|
||||
个人月明细
|
||||
</button>
|
||||
</nav>
|
||||
) : null}
|
||||
{view === 'usage' && usageMode === 'monthly' ? (
|
||||
<QAMonthly />
|
||||
) : view === 'regions' ? (
|
||||
<QARegions />
|
||||
) : (
|
||||
<QAOperationsTabs view={view} onChange={setView} />
|
||||
{queryView ? (
|
||||
<>
|
||||
<QAMirrorSync
|
||||
onChanged={() => {
|
||||
if (detail || detailLoading) {
|
||||
setMirrorChanged(true)
|
||||
return
|
||||
}
|
||||
setQuery((q) => (q ? { ...q } : q))
|
||||
setRevision((v) => v + 1)
|
||||
setQualityRevision((v) => v + 1)
|
||||
}}
|
||||
/>
|
||||
{mirrorChanged ? <p className="qa-ops-warning">数据已更新,关闭详情后刷新。</p> : null}
|
||||
<form className="qa-ops-query" onSubmit={submit}>
|
||||
{view === 'records' ? (
|
||||
<QAWeekPicker
|
||||
year={draft.year}
|
||||
week={draft.week}
|
||||
onCurrentWeek={() => {
|
||||
const current = initialDraft()
|
||||
setDraft({ ...current, keyword: draft.keyword })
|
||||
setQuery({
|
||||
start: qaDateTimeToISO(current.start),
|
||||
end: qaDateTimeToISO(current.end),
|
||||
keyword: draft.keyword,
|
||||
cursor: '',
|
||||
})
|
||||
}}
|
||||
onChange={(year, week) => {
|
||||
setDraft((old) => {
|
||||
if (week === null) return { ...old, year, week }
|
||||
const { start, end } = qaWeekQueryRange(year, week)
|
||||
return { ...old, year, week, start, end }
|
||||
})
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<QAWeekPicker
|
||||
year={draft.year}
|
||||
week={draft.week}
|
||||
onCurrentWeek={() => {
|
||||
const current = initialDraft()
|
||||
setDraft({ ...current, keyword: draft.keyword })
|
||||
setQuery({
|
||||
start: qaDateTimeToISO(current.start),
|
||||
end: qaDateTimeToISO(current.end),
|
||||
keyword: draft.keyword,
|
||||
cursor: '',
|
||||
})
|
||||
}}
|
||||
onChange={(year, week) =>
|
||||
setDraft((old) =>
|
||||
week === null ? { ...old, year, week } : { ...old, ...qaWeekQueryRange(year, week) }
|
||||
)
|
||||
}
|
||||
/>
|
||||
<label>
|
||||
开始时间(北京时间)
|
||||
<input
|
||||
type="datetime-local"
|
||||
required
|
||||
value={draft.start}
|
||||
onChange={(event) => setDraft({ ...draft, start: event.target.value, week: null })}
|
||||
onChange={(e) => setDraft({ ...draft, start: e.target.value, week: null })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
@@ -486,7 +492,7 @@ export function QAOperations() {
|
||||
type="datetime-local"
|
||||
required
|
||||
value={draft.end}
|
||||
onChange={(event) => setDraft({ ...draft, end: event.target.value, week: null })}
|
||||
onChange={(e) => setDraft({ ...draft, end: e.target.value, week: null })}
|
||||
/>
|
||||
</label>
|
||||
<label className="qa-ops-keyword">
|
||||
@@ -496,59 +502,54 @@ export function QAOperations() {
|
||||
maxLength={200}
|
||||
placeholder="检索原始问题"
|
||||
value={draft.keyword}
|
||||
onChange={(event) => setDraft({ ...draft, keyword: event.target.value })}
|
||||
onChange={(e) => setDraft({ ...draft, keyword: e.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" disabled={loading}>
|
||||
查询
|
||||
</button>
|
||||
</form>
|
||||
<p className="qa-ops-slice-note">
|
||||
部门/区域保留源快照,缺失时按当前通讯录补全;使用统计不是绩效结论。外语翻译与AI评估仍暂缓,空值不默认填“否”。
|
||||
</p>
|
||||
{view === 'records' ? <QAQualityCounts query={query} revision={qualityRevision} /> : null}
|
||||
{view === 'usage' ? (
|
||||
<QAUsage query={query} />
|
||||
) : (
|
||||
<QAOperationsView
|
||||
page={page}
|
||||
status={status}
|
||||
error={error}
|
||||
loading={loading}
|
||||
detail={detail}
|
||||
detailLoading={detailLoading}
|
||||
detailError={detailError}
|
||||
onReloadDetail={() => {
|
||||
if (detail) void select(detail.id)
|
||||
}}
|
||||
onQualitySaved={(fresh) => {
|
||||
if (fresh.id !== detail?.id) return
|
||||
setDetail(fresh)
|
||||
setPage((old) => {
|
||||
if (!old) return old
|
||||
const all = new Set(old.columns)
|
||||
const f = fresh.quality?.effective
|
||||
if (f) {
|
||||
if (f.coverage) all.add('coverage')
|
||||
if (f.correctness) all.add('is_correct')
|
||||
for (const key of ['product_category', 'problem_type', 'root_cause'] as const)
|
||||
if (f[key]) all.add(key)
|
||||
}
|
||||
return {
|
||||
...old,
|
||||
items: old.items.map((item) => (item.id === fresh.id ? fresh : item)),
|
||||
columns: qaColumns.filter((c) => all.has(c.key)).map((c) => c.key),
|
||||
}
|
||||
})
|
||||
setQualityRevision((v) => v + 1)
|
||||
}}
|
||||
onSelect={(id) => void select(id)}
|
||||
onCloseDetail={close}
|
||||
progress={progress}
|
||||
onRetry={() => setRevision((value) => value + 1)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
{view === 'regions' ? (
|
||||
<QARegions />
|
||||
) : view === 'weekly' ? (
|
||||
<QAWeekly query={query} />
|
||||
) : view === 'dashboard' ? (
|
||||
<QADashboard
|
||||
query={query}
|
||||
error={error}
|
||||
revision={qualityRevision}
|
||||
onRetry={() => {
|
||||
setRevision((v) => v + 1)
|
||||
setQualityRevision((v) => v + 1)
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<QAOperationsView
|
||||
page={page}
|
||||
status={status}
|
||||
error={error}
|
||||
loading={loading}
|
||||
detail={detail}
|
||||
detailLoading={detailLoading}
|
||||
detailError={detailError}
|
||||
onReloadDetail={() => {
|
||||
if (detail) void select(detail.id)
|
||||
}}
|
||||
onQualitySaved={(fresh) => {
|
||||
if (fresh.id !== detail?.id) return
|
||||
setDetail(fresh)
|
||||
setPage((old) =>
|
||||
old ? { ...old, items: old.items.map((item) => (item.id === fresh.id ? fresh : item)) } : old
|
||||
)
|
||||
setQualityRevision((v) => v + 1)
|
||||
}}
|
||||
onSelect={(id) => void select(id)}
|
||||
onCloseDetail={close}
|
||||
progress={progress}
|
||||
onRetry={() => setRevision((v) => v + 1)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -38,7 +38,13 @@ describe('manual quality operations', () => {
|
||||
<QAQualitySummaryView data={parseQualitySummary(summaryFixture)} error="" loading={false} onRefresh={() => {}} />
|
||||
)
|
||||
expect(ok).toContain('完整筛选范围')
|
||||
expect(ok).toContain('AI 评估未接入')
|
||||
expect(ok).not.toContain('AI 评估未接入')
|
||||
expect(ok).not.toContain('读取:')
|
||||
expect(ok).toContain('质量统计')
|
||||
const empty = renderToStaticMarkup(
|
||||
<QAQualitySummaryView data={null} error="" loading={false} onRefresh={() => {}} />
|
||||
)
|
||||
expect(empty).not.toContain('按当前完整时间/关键词范围留档,不按当前页估算。')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
+14
-21
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { FormEvent } from 'react'
|
||||
import { getPayload, fetchQARecord } from './qaOps'
|
||||
import { getPayload, fetchQARecord, qaDatasetPrefix } from './qaOps'
|
||||
import type { QAQuery, QARecord } from './qaOps'
|
||||
import { newOperationID } from './operationKey'
|
||||
import {
|
||||
@@ -15,12 +15,14 @@ import type { QAQuality, QualityFields, QualityHistory, QualitySnapshot, Quality
|
||||
const stamp = (v: string) => new Date(v).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })
|
||||
const message = (e: unknown) => (e instanceof Error ? e.message : '质量操作失败,请重试')
|
||||
interface EditorProps {
|
||||
dataset?: 'master'
|
||||
recordId: string
|
||||
quality: QAQuality
|
||||
onSaved: (record: QARecord) => void
|
||||
onReload: () => void
|
||||
}
|
||||
export function QAQualityEditor({ recordId, quality, onSaved, onReload }: EditorProps) {
|
||||
export function QAQualityEditor({ recordId, quality, onSaved, onReload, dataset }: EditorProps) {
|
||||
const apiPrefix = qaDatasetPrefix(dataset)
|
||||
const initial = quality.state === 'reviewed' ? quality.effective : emptyQualityFields
|
||||
const [fields, setFields] = useState<QualityFields>({ ...initial }),
|
||||
[reason, setReason] = useState(quality.state === 'reviewed' ? quality.latest_review?.reason || '' : ''),
|
||||
@@ -85,15 +87,11 @@ export function QAQualityEditor({ recordId, quality, onSaved, onReload }: Editor
|
||||
const signature = JSON.stringify(body)
|
||||
try {
|
||||
if (nonce.current.signature !== signature) nonce.current = { signature, value: newOperationID() }
|
||||
const raw = await getPayload(
|
||||
`/api/v1/qa-ops/records/${encodeURIComponent(recordId)}/reviews`,
|
||||
controller.signal,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-quality' },
|
||||
body: JSON.stringify({ ...body, nonce: nonce.current.value }),
|
||||
}
|
||||
)
|
||||
const raw = await getPayload(`${apiPrefix}/records/${encodeURIComponent(recordId)}/reviews`, controller.signal, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'qa-quality' },
|
||||
body: JSON.stringify({ ...body, nonce: nonce.current.value }),
|
||||
})
|
||||
if (!raw || typeof raw !== 'object') throw Error('复核回执无效')
|
||||
const receipt = raw as Record<string, unknown>
|
||||
parseQAQuality(receipt.view)
|
||||
@@ -102,7 +100,7 @@ export function QAQualityEditor({ recordId, quality, onSaved, onReload }: Editor
|
||||
const savedRevision = Number(receipt.saved_revision)
|
||||
const audit = parseQualityHistory(
|
||||
await getPayload(
|
||||
`/api/v1/qa-ops/records/${encodeURIComponent(recordId)}/quality/history?review_before=${savedRevision + 1}`,
|
||||
`${apiPrefix}/records/${encodeURIComponent(recordId)}/quality/history?review_before=${savedRevision + 1}`,
|
||||
controller.signal
|
||||
)
|
||||
)
|
||||
@@ -117,7 +115,7 @@ export function QAQualityEditor({ recordId, quality, onSaved, onReload }: Editor
|
||||
)
|
||||
)
|
||||
throw Error('保存后的精确复核记录尚未读回,请用原表单重试,重复请求不会重复留档')
|
||||
const fresh = await fetchQARecord(recordId, controller.signal)
|
||||
const fresh = await fetchQARecord(recordId, controller.signal, dataset)
|
||||
if (!fresh.quality || fresh.quality.revision < savedRevision)
|
||||
throw Error('复核已留档但当前问答尚未读回,请重新读取')
|
||||
if (!controller.signal.aborted) {
|
||||
@@ -144,7 +142,7 @@ export function QAQualityEditor({ recordId, quality, onSaved, onReload }: Editor
|
||||
try {
|
||||
const next = parseQualityHistory(
|
||||
await getPayload(
|
||||
`/api/v1/qa-ops/records/${encodeURIComponent(recordId)}/quality/history${params.size ? '?' + params : ''}`,
|
||||
`${apiPrefix}/records/${encodeURIComponent(recordId)}/quality/history${params.size ? '?' + params : ''}`,
|
||||
controller.signal
|
||||
)
|
||||
)
|
||||
@@ -171,7 +169,7 @@ export function QAQualityEditor({ recordId, quality, onSaved, onReload }: Editor
|
||||
try {
|
||||
const next = parseQualitySnapshot(
|
||||
await getPayload(
|
||||
`/api/v1/qa-ops/records/${encodeURIComponent(recordId)}/quality/inputs/${epoch}`,
|
||||
`${apiPrefix}/records/${encodeURIComponent(recordId)}/quality/inputs/${epoch}`,
|
||||
controller.signal
|
||||
)
|
||||
)
|
||||
@@ -407,7 +405,7 @@ export function QAQualitySummaryView({ data, loading, error, onRefresh }: Summar
|
||||
return (
|
||||
<section className="qa-quality-summary" aria-label="质量数量">
|
||||
<button type="button" disabled={loading} onClick={onRefresh}>
|
||||
{loading ? '正在复检留档…' : '复检留档与质量数量'}
|
||||
{loading ? '正在统计…' : '质量统计'}
|
||||
</button>
|
||||
{error ? (
|
||||
<p role="alert" className="error-banner">
|
||||
@@ -460,12 +458,7 @@ export function QAQualitySummaryView({ data, loading, error, onRefresh }: Summar
|
||||
</p>
|
||||
<p className="qa-ops-muted">统计规则:{data.summary.rates.policy_version}</p>
|
||||
</details>
|
||||
<p className="qa-ops-muted">
|
||||
AI 评估未接入;人工待确认是已复核中的子集,规则命中可与人工结论不同。读取:{stamp(data.as_of)}
|
||||
</p>
|
||||
</>
|
||||
) : !error && !loading ? (
|
||||
<span className="qa-ops-muted">按当前完整时间/关键词范围留档,不按当前页估算。</span>
|
||||
) : null}
|
||||
</section>
|
||||
)
|
||||
|
||||
@@ -51,6 +51,30 @@ const props = {
|
||||
onRemoveMissing: vi.fn(),
|
||||
}
|
||||
describe('region mapping workbench', () => {
|
||||
it('separates multiselect from bulk application and renders hierarchy and editable region names', () => {
|
||||
const custom = {
|
||||
...state,
|
||||
regions: [{ id: 'APAC', name: '国外工业Amercia' }],
|
||||
view: { ...state.view, regions: { APAC: 1 } },
|
||||
}
|
||||
const html = renderToStaticMarkup(<RegionMappingView {...props} state={custom} />)
|
||||
for (const label of [
|
||||
'区域设置',
|
||||
'添加区域',
|
||||
'一级部门',
|
||||
'二级部门',
|
||||
'三级部门',
|
||||
'四级及更深',
|
||||
'批量归属',
|
||||
'全选当前列表',
|
||||
'取消本次勾选',
|
||||
'国外工业Amercia',
|
||||
])
|
||||
expect(html).toContain(label)
|
||||
expect(html).toMatch(/disabled=""[^>]*>批量归属/)
|
||||
expect(html).not.toContain('将 示例公司/')
|
||||
})
|
||||
|
||||
it('shows real synchronization stages without inventing progress and protects dirty drafts', () => {
|
||||
const syncStatus = {
|
||||
configured: true,
|
||||
@@ -80,14 +104,14 @@ describe('region mapping workbench', () => {
|
||||
const bodyRule = css.match(/\.qa-region-table td\s*\{([^}]+)\}/)?.[1] ?? ''
|
||||
expect(bodyRule).toMatch(/white-space:\s*normal/)
|
||||
expect(bodyRule).toMatch(/overflow-wrap:\s*anywhere/)
|
||||
const statusRule = css.match(/\.qa-region-table td:nth-child\(4\)\s*\{([^}]+)\}/)?.[1] ?? ''
|
||||
const statusRule = css.match(/\.qa-region-table td\.qa-region-basis\s*\{([^}]+)\}/)?.[1] ?? ''
|
||||
expect(statusRule).toMatch(/white-space:\s*nowrap/)
|
||||
})
|
||||
it('shows a dated historical roster, conflicts and no invented performance verdict', () => {
|
||||
const html = renderToStaticMarkup(<RegionMappingView {...props} />)
|
||||
expect(html).toContain('历史快照')
|
||||
expect(html).toContain('跨区域待核对:1')
|
||||
expect(html).toContain('配置区域归属不等于纳入绩效考核')
|
||||
expect(html).not.toContain('配置区域归属不等于纳入绩效考核')
|
||||
expect(html).not.toContain('<script>test</script>')
|
||||
expect(html).not.toContain('达标率')
|
||||
expect(html).toMatch(/disabled=""[^>]*>保存归属/)
|
||||
|
||||
+217
-45
@@ -1,11 +1,24 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { changeRegionRule, fetchOrganization, previewOrganization, regionNames, saveOrganization } from './qaOrg'
|
||||
import type { Organization, RegionRule } from './qaOrg'
|
||||
import {
|
||||
changeRegionRule,
|
||||
fetchOrganization,
|
||||
previewOrganization,
|
||||
organizationRegions,
|
||||
parseRegionDefinitions,
|
||||
saveOrganization,
|
||||
} from './qaOrg'
|
||||
import type { Organization, RegionRule, RegionDefinition } from './qaOrg'
|
||||
import './qaRegions.css'
|
||||
import { applyBulkRegionRules, departmentLevels } from './qaRegionSelection'
|
||||
import { completedSyncAction, directorySyncActive, fetchDirectorySync, startDirectorySync } from './qaOrgSync'
|
||||
import type { DirectorySyncStatus } from './qaOrgSync'
|
||||
import { newOperationID } from './operationKey'
|
||||
interface Props {
|
||||
regions?: RegionDefinition[]
|
||||
selectedIDs?: string[]
|
||||
onCatalog?: (regions: RegionDefinition[]) => void
|
||||
onSelect?: (ids: string[]) => void
|
||||
onApply?: () => void
|
||||
syncStatus?: DirectorySyncStatus | null
|
||||
syncError?: string
|
||||
syncSubmitting?: boolean
|
||||
@@ -28,10 +41,35 @@ interface Props {
|
||||
onReload: () => void
|
||||
}
|
||||
export function RegionMappingView(p: Props) {
|
||||
const display = p.preview ?? p.state
|
||||
const available = p.state?.state === 'ready'
|
||||
const departments =
|
||||
display?.view.departments.filter((d) => d.path.toLowerCase().includes(p.search.toLowerCase())) ?? []
|
||||
const [newName, setNewName] = useState(''),
|
||||
[level, setLevel] = useState(''),
|
||||
[catalogError, setCatalogError] = useState('')
|
||||
const display = p.preview ?? p.state,
|
||||
available = p.state?.state === 'ready'
|
||||
const regions = p.regions ?? organizationRegions(p.state),
|
||||
selected = p.selectedIDs ?? []
|
||||
const all = display?.view.departments ?? [],
|
||||
nodes = new Map(all.map((d) => [d.id, d]))
|
||||
const rows = all.map((d) => ({ department: d, levels: departmentLevels(all, d.id, nodes) }))
|
||||
const departments = rows.filter(
|
||||
({ department: d, levels }) =>
|
||||
d.path.toLowerCase().includes(p.search.toLowerCase()) && (!level || levels.length === Number(level))
|
||||
)
|
||||
const maximum = rows.reduce((n, r) => Math.max(n, r.levels.length), 0)
|
||||
const label = (id: string, catalog = regions) => catalog.find((r) => r.id === id)?.name ?? id
|
||||
const choose = (id: string, checked: boolean) =>
|
||||
p.onSelect?.(checked ? [...new Set([...selected, id])] : selected.filter((x) => x !== id))
|
||||
const add = () => {
|
||||
if (!newName.trim()) return
|
||||
const next = [...regions, { id: 'region-' + newOperationID(), name: newName.trim() }]
|
||||
try {
|
||||
p.onCatalog?.(parseRegionDefinitions(next))
|
||||
setNewName('')
|
||||
setCatalogError('')
|
||||
} catch {
|
||||
setCatalogError('区域名称无效,请核对长度、重名或保留名称')
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section className="qa-regions" aria-label="区域归属配置">
|
||||
<div className="qa-region-heading">
|
||||
@@ -85,9 +123,6 @@ export function RegionMappingView(p: Props) {
|
||||
{p.state.revision_id || '尚未保存'}
|
||||
</p>
|
||||
) : null}
|
||||
<p className="qa-ops-muted">
|
||||
父部门包含子部门,子部门单独配置优先。配置区域归属不等于纳入绩效考核;跨区域多部门人员先待核对。
|
||||
</p>
|
||||
{p.error ? (
|
||||
<p role="alert" className="error-banner">
|
||||
{p.error}
|
||||
@@ -97,16 +132,69 @@ export function RegionMappingView(p: Props) {
|
||||
{!p.state ? (
|
||||
<p role="status">{p.busy ? '正在读取通讯录…' : '尚未读取通讯录'}</p>
|
||||
) : !available ? (
|
||||
<p className="qa-ops-empty">尚无完整通讯录快照。先接入已验证的全量同步结果,不能使用按需人员缓存或编造部门。</p>
|
||||
<p className="qa-ops-empty">暂无通讯录,请先同步。</p>
|
||||
) : (
|
||||
<>
|
||||
<section className="qa-region-catalog" aria-label="区域设置">
|
||||
<h4>区域设置</h4>
|
||||
{catalogError ? (
|
||||
<p role="alert" className="error-banner">
|
||||
{catalogError}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="qa-region-names">
|
||||
{regions.map((r) => (
|
||||
<label key={r.id}>
|
||||
区域名称
|
||||
<input
|
||||
aria-label={`区域名称 ${r.id}`}
|
||||
value={r.name}
|
||||
maxLength={100}
|
||||
disabled={p.busy}
|
||||
onChange={(e) =>
|
||||
p.onCatalog?.(regions.map((x) => (x.id === r.id ? { ...x, name: e.target.value } : x)))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
add()
|
||||
}}
|
||||
className="qa-region-add"
|
||||
>
|
||||
<input
|
||||
aria-label="新区域名称"
|
||||
value={newName}
|
||||
maxLength={100}
|
||||
disabled={p.busy}
|
||||
placeholder="输入业务区域名称"
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
/>
|
||||
<button
|
||||
disabled={
|
||||
p.busy || !newName.trim() || regions.length >= 100 || regions.some((r) => r.name === newName.trim())
|
||||
}
|
||||
>
|
||||
添加区域
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
<div className="qa-region-filters">
|
||||
<label>
|
||||
选择区域
|
||||
<select value={p.selectedRegion} disabled={p.busy} onChange={(e) => p.onRegion(e.target.value)}>
|
||||
{regionNames.map((r) => (
|
||||
<option key={r}>{r}</option>
|
||||
))}
|
||||
{regions.length ? (
|
||||
regions.map((r) => (
|
||||
<option key={r.id} value={r.id}>
|
||||
{r.name}
|
||||
</option>
|
||||
))
|
||||
) : (
|
||||
<option value="">请先添加区域</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
@@ -118,6 +206,47 @@ export function RegionMappingView(p: Props) {
|
||||
placeholder="输入部门名称或完整路径"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
部门层级
|
||||
<select aria-label="部门层级" value={level} onChange={(e) => setLevel(e.target.value)}>
|
||||
<option value="">全部层级</option>
|
||||
{Array.from({ length: maximum }, (_, i) => (
|
||||
<option key={i} value={i + 1}>
|
||||
第 {i + 1} 级
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div className="qa-region-bulk">
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label="全选当前列表"
|
||||
disabled={p.busy || !departments.length}
|
||||
checked={departments.length > 0 && departments.every((r) => selected.includes(r.department.id))}
|
||||
onChange={(e) => {
|
||||
const visible = new Set(departments.map((r) => r.department.id))
|
||||
p.onSelect?.(
|
||||
e.target.checked
|
||||
? [...new Set([...selected, ...visible])]
|
||||
: selected.filter((id) => !visible.has(id))
|
||||
)
|
||||
}}
|
||||
/>
|
||||
全选当前列表
|
||||
</label>
|
||||
<span>已勾选 {selected.length} 个部门</span>
|
||||
<button
|
||||
type="button"
|
||||
disabled={p.busy || !selected.length || !regions.some((r) => r.id === p.selectedRegion)}
|
||||
onClick={p.onApply}
|
||||
>
|
||||
批量归属
|
||||
</button>
|
||||
<button type="button" disabled={p.busy || !selected.length} onClick={() => p.onSelect?.([])}>
|
||||
取消本次勾选
|
||||
</button>
|
||||
<button type="button" disabled={p.busy || !p.dirty} onClick={p.onPreview}>
|
||||
预览影响
|
||||
</button>
|
||||
@@ -129,18 +258,16 @@ export function RegionMappingView(p: Props) {
|
||||
<div className="qa-region-preview" aria-label="归属人数预览">
|
||||
<strong>{p.preview ? '预览结果(未保存)' : '已保存归属'}</strong>
|
||||
<span>通讯录人数:{display.view.total_people}</span>
|
||||
{regionNames.map((r) => (
|
||||
<span key={r}>
|
||||
{r}:{display.view.regions[r]}
|
||||
{organizationRegions(display).map((r) => (
|
||||
<span key={r.id}>
|
||||
{r.name}:{display.view.regions[r.id]}
|
||||
</span>
|
||||
))}
|
||||
<span>未归属:{display.view.unassigned_people}</span>
|
||||
<span>跨区域待核对:{display.view.conflicting_people}</span>
|
||||
</div>
|
||||
) : null}
|
||||
{p.dirty && !p.preview ? (
|
||||
<p className="qa-ops-muted">勾选已修改,人数仍为已保存结果;请预览后保存。</p>
|
||||
) : null}
|
||||
{p.dirty && !p.preview ? <p className="qa-ops-muted">人数仍为已保存结果;请预览后保存。</p> : null}
|
||||
{display?.view.missing_departments.length ? (
|
||||
<div role="alert" className="qa-ops-warning">
|
||||
部分已配置部门不在当前通讯录中,原规则保留,需核对:
|
||||
@@ -158,43 +285,71 @@ export function RegionMappingView(p: Props) {
|
||||
<table className="qa-region-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>直接配置</th>
|
||||
<th>选择</th>
|
||||
<th>一级部门</th>
|
||||
<th>二级部门</th>
|
||||
<th>三级部门</th>
|
||||
<th>四级及更深</th>
|
||||
<th>完整部门路径</th>
|
||||
<th>直接配置</th>
|
||||
<th>{p.dirty && !p.preview ? '已保存归属' : '生效归属'}</th>
|
||||
<th>依据</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{departments.map((d) => (
|
||||
<tr key={d.id}>
|
||||
<td>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={`将 ${d.path} 直接归入 ${p.selectedRegion}`}
|
||||
checked={p.rules.some((r) => r.department_id === d.id && r.region === p.selectedRegion)}
|
||||
disabled={p.busy}
|
||||
onChange={(e) => p.onToggle(d.id, e.target.checked)}
|
||||
/>
|
||||
</td>
|
||||
<td>{d.path}</td>
|
||||
<td>{d.region || '未归属'}</td>
|
||||
<td>{d.explicit ? '直接配置' : d.inherited_from ? '继承上级' : '未配置'}</td>
|
||||
</tr>
|
||||
))}
|
||||
{departments.map(({ department: d, levels }) => {
|
||||
const direct = p.rules.find((r) => r.department_id === d.id)
|
||||
return (
|
||||
<tr key={d.id} data-department-id={d.id}>
|
||||
<td>
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={`选择部门 ${d.path}`}
|
||||
checked={selected.includes(d.id)}
|
||||
disabled={p.busy}
|
||||
onChange={(e) => choose(d.id, e.target.checked)}
|
||||
/>
|
||||
</td>
|
||||
<td>{levels[0] || '—'}</td>
|
||||
<td>{levels[1] || '—'}</td>
|
||||
<td>{levels[2] || '—'}</td>
|
||||
<td>{levels.slice(3).join(' / ') || '—'}</td>
|
||||
<td>{d.path}</td>
|
||||
<td>
|
||||
{direct ? (
|
||||
<>
|
||||
<span>{label(direct.region)}</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`清除直接配置 ${d.path}`}
|
||||
disabled={p.busy}
|
||||
onClick={() => p.onToggle(d.id, false)}
|
||||
>
|
||||
清除
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
'—'
|
||||
)}
|
||||
</td>
|
||||
<td>{d.region ? label(d.region, organizationRegions(display)) : '未归属'}</td>
|
||||
<td className="qa-region-basis">
|
||||
{d.explicit ? '直接配置' : d.inherited_from ? '继承上级' : '未配置'}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
{!departments.length ? <p>没有匹配的部门路径</p> : null}
|
||||
</div>
|
||||
<p className="qa-ops-muted">
|
||||
此处仅预览通讯录归属人数;2.0 使用次数、考核名单与绩效统计尚未接入。不会将未知在职状态当作已确认在职人数。
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
function signature(rules: RegionRule[]) {
|
||||
return JSON.stringify([...rules].sort((a, b) => a.department_id.localeCompare(b.department_id)))
|
||||
function signature(rules: RegionRule[], regions: RegionDefinition[]) {
|
||||
return JSON.stringify({ rules: [...rules].sort((a, b) => a.department_id.localeCompare(b.department_id)), regions })
|
||||
}
|
||||
export function QARegions() {
|
||||
const [syncStatus, setSyncStatus] = useState<DirectorySyncStatus | null>(null),
|
||||
@@ -208,7 +363,9 @@ export function QARegions() {
|
||||
const [state, setState] = useState<Organization | null>(null),
|
||||
[preview, setPreview] = useState<Organization | null>(null),
|
||||
[rules, setRules] = useState<RegionRule[]>([])
|
||||
const [region, setRegion] = useState<string>(regionNames[0]),
|
||||
const [regions, setRegions] = useState<RegionDefinition[]>([]),
|
||||
[selected, setSelected] = useState<string[]>([])
|
||||
const [region, setRegion] = useState<string>(''),
|
||||
[search, setSearch] = useState(''),
|
||||
[busy, setBusy] = useState(false),
|
||||
[error, setError] = useState(''),
|
||||
@@ -217,6 +374,11 @@ export function QARegions() {
|
||||
const accept = (value: Organization) => {
|
||||
setState(value)
|
||||
setRules(value.rules)
|
||||
setRegions(organizationRegions(value))
|
||||
setRegion((current) =>
|
||||
organizationRegions(value).some((r) => r.id === current) ? current : (organizationRegions(value)[0]?.id ?? '')
|
||||
)
|
||||
setSelected([])
|
||||
setPreview(null)
|
||||
}
|
||||
const load = async () => {
|
||||
@@ -243,7 +405,7 @@ export function QARegions() {
|
||||
void load()
|
||||
return () => request.current?.abort()
|
||||
}, [])
|
||||
const dirty = Boolean(state && signature(rules) !== signature(state.rules))
|
||||
const dirty = Boolean(state && signature(rules, regions) !== signature(state.rules, organizationRegions(state)))
|
||||
dirtyRef.current = dirty
|
||||
const loadRef = useRef(load)
|
||||
loadRef.current = load
|
||||
@@ -325,8 +487,8 @@ export function QARegions() {
|
||||
setNotice('')
|
||||
try {
|
||||
const value = await (save
|
||||
? saveOrganization(state, rules, controller.signal)
|
||||
: previewOrganization(state, rules, controller.signal))
|
||||
? saveOrganization({ ...state, regions: parseRegionDefinitions(regions) }, rules, controller.signal)
|
||||
: previewOrganization({ ...state, regions: parseRegionDefinitions(regions) }, rules, controller.signal))
|
||||
if (!controller.signal.aborted) {
|
||||
if (save) {
|
||||
const readback = await fetchOrganization(controller.signal)
|
||||
@@ -347,6 +509,16 @@ export function QARegions() {
|
||||
}
|
||||
return (
|
||||
<RegionMappingView
|
||||
regions={regions}
|
||||
selectedIDs={selected}
|
||||
onCatalog={(next) => {
|
||||
setRegions(next)
|
||||
setPreview(null)
|
||||
setNotice('')
|
||||
setError('')
|
||||
}}
|
||||
onSelect={setSelected}
|
||||
onApply={() => edit(applyBulkRegionRules(rules, selected, region))}
|
||||
syncStatus={syncStatus}
|
||||
syncError={syncError}
|
||||
syncSubmitting={syncSubmitting}
|
||||
|
||||
@@ -20,6 +20,16 @@ const usage = parseQAUsage({
|
||||
rows: [{ key: 'unmatched', questions: 2, succeeded: 1, failed: 1, other: 0, users: null, roster_people: null }],
|
||||
})
|
||||
describe('usage statistics evidence', () => {
|
||||
it('renders a custom label without inheriting Object prototype properties', () => {
|
||||
const custom = {
|
||||
...usage,
|
||||
organization: { ...usage.organization, region_names: ['toString'] },
|
||||
rows: usage.rows.map((r) => ({ ...r, key: 'toString' })),
|
||||
}
|
||||
const html = renderToStaticMarkup(<QAUsageView data={custom} loading={false} error="" onRetry={() => {}} />)
|
||||
expect(html).toContain('toString')
|
||||
})
|
||||
|
||||
it('shows a current-roster basis and unknown counts without performance claims', () => {
|
||||
const html = renderToStaticMarkup(<QAUsageView data={usage} loading={false} error="" onRetry={() => {}} />)
|
||||
expect(html).toContain('按当前通讯录回看')
|
||||
|
||||
+1
-1
@@ -57,7 +57,7 @@ export function QAUsageView({ data, loading, error, onRetry }: Props) {
|
||||
<tbody>
|
||||
{data.rows.map((row) => (
|
||||
<tr key={row.key}>
|
||||
<td>{usageLabels[row.key]}</td>
|
||||
<td>{usageLabels[row.key] ?? row.key}</td>
|
||||
<td>{row.questions}</td>
|
||||
<td>{row.succeeded}</td>
|
||||
<td>{row.failed}</td>
|
||||
|
||||
@@ -15,8 +15,7 @@ describe('QA week picker', () => {
|
||||
expect(html).toContain('value="40" selected=""')
|
||||
expect(html).toContain('第40周(09-28 到 10-04)')
|
||||
expect(html).toContain('第53周(2026-12-28 到 2027-01-03)')
|
||||
expect(html).toContain('北京时间')
|
||||
expect(html).toContain('周一至周日')
|
||||
expect(html).not.toContain('北京时间 · 周一至周日 · 本周截至当前')
|
||||
})
|
||||
it('preserves custom range mode and does not offer invalid week 53', () => {
|
||||
const html = renderToStaticMarkup(<QAWeekPicker year={2027} week={null} onChange={vi.fn()} />)
|
||||
|
||||
@@ -50,7 +50,6 @@ export function QAWeekPicker({ year, week, onChange, onCurrentWeek }: Props) {
|
||||
<button className="qa-week-current" type="button" onClick={onCurrentWeek}>
|
||||
本周
|
||||
</button>
|
||||
<span className="qa-ops-muted">北京时间 · 周一至周日 · 本周截至当前</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { QAQuery } from './qaOps'
|
||||
import { fetchAllQARecords } from './qaOps'
|
||||
import { fetchQADashboardQuality } from './qaDashboard'
|
||||
import { fetchQAMirrorStatus } from './qaMirror'
|
||||
import { buildQAWeeklyDraft, downloadQAWeekly } from './qaWeekly'
|
||||
import type { QAWeeklyDraft } from './qaWeekly'
|
||||
import { QAAnswerMarkdown } from './QAAnswerMarkdown'
|
||||
export function QAWeekly({ query }: { query: QAQuery | null }) {
|
||||
const [draft, setDraft] = useState<QAWeeklyDraft | null>(null),
|
||||
[loading, setLoading] = useState(false),
|
||||
[error, setError] = useState('')
|
||||
const request = useRef<AbortController | null>(null)
|
||||
useEffect(() => {
|
||||
request.current?.abort()
|
||||
setDraft(null)
|
||||
setError('')
|
||||
setLoading(false)
|
||||
return () => request.current?.abort()
|
||||
}, [query])
|
||||
const generate = async () => {
|
||||
if (!query || loading) return
|
||||
request.current?.abort()
|
||||
const controller = new AbortController()
|
||||
request.current = controller
|
||||
setLoading(true)
|
||||
setDraft(null)
|
||||
setError('')
|
||||
try {
|
||||
const before = await fetchQAMirrorStatus(controller.signal)
|
||||
if (!before.ready || before.blocked) throw Error('本地同步未就绪,暂不能生成周报')
|
||||
const [page, quality] = await Promise.all([
|
||||
fetchAllQARecords(query, controller.signal),
|
||||
fetchQADashboardQuality(query, controller.signal),
|
||||
])
|
||||
const after = await fetchQAMirrorStatus(controller.signal)
|
||||
if (!after.ready || after.blocked || before.revision !== after.revision || page.local_revision !== after.revision)
|
||||
throw Error('本地副本在生成期间已更新,请重新生成')
|
||||
const result = buildQAWeeklyDraft(page, query, quality, new Date().toISOString())
|
||||
if (!controller.signal.aborted) setDraft(result)
|
||||
} catch (e) {
|
||||
if (!controller.signal.aborted) setError(e instanceof Error ? e.message : '周报生成失败')
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
}
|
||||
}
|
||||
const suffix = query ? new Date(Date.parse(query.start) + 8 * 60 * 60 * 1000).toISOString().slice(0, 10) : 'draft'
|
||||
return (
|
||||
<section className="qa-weekly" aria-label="周报生成">
|
||||
<header className="qa-weekly-toolbar">
|
||||
<div>
|
||||
<h3>周报生成</h3>
|
||||
{query ? (
|
||||
<span>
|
||||
{new Date(query.start).toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' })} 至{' '}
|
||||
{new Date(Date.parse(query.end) - 1).toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' })}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<button type="button" onClick={() => void generate()} disabled={loading || !query}>
|
||||
{loading ? '正在生成…' : '生成周报草稿'}
|
||||
</button>
|
||||
{draft ? (
|
||||
<>
|
||||
<span className="qa-weekly-badge">草稿 · {draft.questions} 条</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
downloadQAWeekly(draft.markdown, `DobotAI-问答周报-${suffix}.md`, 'text/markdown;charset=utf-8')
|
||||
}
|
||||
>
|
||||
下载 MD
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => downloadQAWeekly(draft.csv, `DobotAI-问题明细-${suffix}.csv`, 'text/csv;charset=utf-8')}
|
||||
>
|
||||
下载明细 CSV
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
</header>
|
||||
{error ? (
|
||||
<p role="alert" className="error-banner">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
{draft ? (
|
||||
<article className="qa-weekly-preview">
|
||||
<QAAnswerMarkdown answer={draft.markdown} />
|
||||
</article>
|
||||
) : (
|
||||
<div className="qa-weekly-empty">{loading ? '正在汇总本地问答…' : '尚未生成周报。'}</div>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user