Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52d92c95d8 | ||
|
|
7ffb5cdb9c | ||
|
|
a84ee85a84 | ||
|
|
b03715cb76 | ||
|
|
1b0274974c | ||
|
|
903fa94c00 | ||
|
|
cf8e25a30d | ||
|
|
b711327c8e | ||
|
|
b73240b2db | ||
|
|
8b8f9b7728 | ||
|
|
5bcf1dee4f | ||
|
|
db5349dbde | ||
|
|
f8f289395e | ||
|
|
46b920f28a | ||
|
|
d0fee1544a | ||
|
|
5c37b39858 | ||
|
|
fb245f7d2e | ||
|
|
e6ceae12f0 | ||
|
|
19bd9b0122 | ||
|
|
d89bd2e451 | ||
|
|
2230500a96 |
@@ -1,6 +1,17 @@
|
||||
# 质量数据分析平台设计规范
|
||||
|
||||
更新:2026-10-30
|
||||
更新:2026-11-02
|
||||
|
||||
- 月度趋势数据表提供“关键指标 / 完整指标”切换,完整列与主汇总表共用字段口径与顺序。黑片、亮片页面首次默认完整指标,其余四类查询首次默认关键指标;各缓存页保留用户选择,查询和重置不改写选择,不增加数据请求。
|
||||
|
||||
## 智能分析正文与运行反馈(2026-11-02)
|
||||
|
||||
- 历史正文与会话列表分别读取,指定会话链接不等待列表;只有从查询条件创建会话时才加载选项。加载提示放在对应面板内部,首次读取不得显示欢迎空状态,也不得用通用大高度加载块推移会话框和输入区;列表失败不阻止已授权正文读取。
|
||||
|
||||
- 原生 AI 会话及报告以模型完整原文为正文,保留段落、表格和顺序,正式查询图表穿插在相关章节后;取消二次改写和统计兜底报告替换。历史兜底报告仅在保存的模型原文可恢复时恢复,原文缺失不伪造补齐。
|
||||
- 会话只显示一次最终回答,运行过程保留思考与工具步骤;运行中默认展开,可手动收起。发送立即显示等待状态和计时,收到服务器开始时间后显示运行计时和旋转图标。
|
||||
- 不在会话追加范围说明、进度句、错误或“部分完成”提示;真实失败、证据缺口和完成状态仍保存在后台,恢复及重试入口保留。
|
||||
- 合格率变化统一为本期减比较期:下降为负 pp,上升为正 pp。用于筛选和排序的降幅指标保持原有语义,转换仅作用于展示值;图表、数据表和导出一致。
|
||||
|
||||
## 已确认方向
|
||||
- 保持现有导航宽度、模块顺序、筛选承载、指标横条、表格及趋势位置。(用户确认)
|
||||
@@ -55,3 +66,72 @@
|
||||
- 后续本地调整:顶部指标卡片恢复随页面滚动,移除其标题下的“(去本部报废)”,保留表头口径提示及切换功能;口径切换与卡片共用一行,移除上方独占空行并压缩卡片内边距。顶部筛选栏及表格冻结列不变。实际滚动检查、类型检查及31项相关检查通过,2026-10-31 已发布。
|
||||
|
||||
- 原口径隐藏亮片与综合合格率的说明图标,去本部报废口径保留图标;黑片总重量规则图标始终保留。构建及32项检查通过,已实测线上切换,2026-10-31 已发布。
|
||||
|
||||
## 2026-11-01:趋势柱形 01 轻度加深(用户确认)
|
||||
|
||||
- 保留现有布局、堆叠、坐标轴、目标线及三条合格率折线的颜色和算法。
|
||||
- 浅蓝主题合格重量柱:默认 #99A8E3,选中 #7F92DA,悬停 #6078CE;报废重量柱:默认 #E49A70,选中 #DB8656,悬停 #CD7546。
|
||||
- 未选中月份保色 50%,替代原来的 28%;既有 340 毫秒过渡及再次点击取消选择保持。
|
||||
- 六主题共用 web/src/trendBarPalette.ts;其他浅色主题沿用各自蓝色方向,午夜黑同步增强对比度。
|
||||
- 方案已获用户明确发布授权。候选预览控制栏和其他深度候选不进入正式页面。
|
||||
|
||||
## 2026-11-01:查询结果连续更新与阅读顺序
|
||||
|
||||
- 按用户要求调整为:指标卡、趋势图、汇总表、不良具体构成;总体、产业部、业务分组、产品、黑片和亮片查询保持一致。
|
||||
- 查询期间保留最后一次成功的卡片数据和表格及其期间、视图信息;旧结果暂时禁止打开明细及导出,新响应到达后恢复操作。
|
||||
- 卡片和已存在的表格单元格数字、表格高度采用 520 毫秒连续过渡;减少动态效果设置下直接更新。
|
||||
- Excel 始终使用最终服务端数值,不导出动画中的中间值。六主题逐帧检查、黑片与亮片实际页面检查及 42 项相关检查通过;当前仅本地修改,待用户发布。
|
||||
|
||||
## 2026-11-01:默认可用月份与页面切换(本地)
|
||||
|
||||
- 无显式查询期间的新页面默认进入月度:优先上个月;上个月未出现在已发布月份列表时,仅回退到上上个月。重置和切回月度采用同一规则。
|
||||
- 复用 `/api/options` 的 `periods` / `latestDataPeriod`,不额外拉取完整报表判断。手动选择、分享链接、已缓存查询期间不被自动覆盖。
|
||||
- 不同页面之间采用 280ms 新旧内容交叉淡化,取消整页位移,顶部和侧栏保持稳定。目标页面先提交内容及滚动位置,再交接画面;首次加载等待最多 900ms,内容稳定 32ms 后提前开始。连续导航立即打断上一次切换,返回保留筛选及滚动位置。减少动态效果或浏览器不支持时直接切换。
|
||||
- 六个查询页默认月份、六主题切换、手动选择的慢加载保护、显式年月和返回时的筛选/滚动位置均已在本地验证。页面转场补充快速连续点击、取消等待及不可见控件保护验证,53 项相关检查通过,尚未发布。
|
||||
- 黑片与亮片页移除指标卡下方的来源统计与计算口径整行,回收空隙;计算说明仍可从指标卡或表头查看。趋势图关联已生效的月份/季度,默认月份及查询后同步选中加深,年度取消月份高亮。六主题选中效果已检查。
|
||||
- 2026-11-01 发布前生产构建与 57 项相关检查通过;此次仅更新前端,不修改计算逻辑或业务数据。
|
||||
|
||||
## 2026-11-01:取消内部缩放(本地)
|
||||
|
||||
- 保留侧栏、指标卡、趋势图、表格和不良构成的现有结构与顺序,移除整页 80% 缩放。字号采用原有真实尺寸,不再通过整体缩放压缩内容。
|
||||
- 图表移除反向缩放与字体补偿,趋势图和柏拉图使用正常坐标尺寸;页面高度直接对应浏览器视口。
|
||||
- 顶部栏、筛选栏及管理页签共享冻结起点,桌面 53px、手机 40px;管理页签每级追加 47px,保留表格左右冻结列。
|
||||
- 本地已检查 1920×1080、1536×864、1366×768、390×844 视口、六个查询页、六主题、图表点击和完整字段的冻结列。实际 Windows 硬件尚未验收,使用隔离演示数据预览,未发布。
|
||||
|
||||
## 2026-11-01:黑片与亮片更多筛选(本地)
|
||||
|
||||
- 黑片与亮片查询页将项目组、添加来源筛选字段及其条件行统一收入“更多筛选”,默认收起,主行保留期间、产业部、业务分组和产品。
|
||||
- 复用其他查询页的展开/收起样式、已选条件数量及清除入口;收起保留筛选,仍按原方式点击查询生效。
|
||||
- 本地实测两页展开收起、条件保留及实际查询参数、清除后查询;类型检查与阶段查询回归通过,未发布。
|
||||
|
||||
## 2026-11-01:侧栏内容字号(本地)
|
||||
|
||||
- 侧栏菜单从 13px 调到 14px,分组标题与账户主文字从 12px 调到 13px,菜单图标从 16px 调到 18px;侧栏宽度和主内容字号不变。
|
||||
- 已检查六种主题、长菜单名称和折叠状态,无文字换行或图标裁切,未发布。
|
||||
|
||||
## 2026-11-01:统一查询指标卡高度
|
||||
|
||||
- 六个查询页桌面端指标卡统一最小高度 96px,避免黑片与亮片页因没有辅助说明而矮一截;保留手机端原有 84px 最小高度。
|
||||
- 六个查询页和六种主题的卡片高度已实测一致;数据、字号、卡片排列与口径切换保持原有行为。
|
||||
|
||||
## 2026-11-01:筛选框统一与钻取趋势过渡(本地)
|
||||
|
||||
- 黑片、亮片取消独立的筛选框最小宽度与间距,年份、月份、季度复用其他查询页的尺寸规则;月份统一为两位显示,原查询方式保留。
|
||||
- 钻取时保留上次成功的趋势及目标线,新数据返回后使用同一图表实例进行 520ms 更新动画;减少动态效果时直接更新。
|
||||
- 旧范围图表在更新或失败时禁止交互;加载失败保留原图并允许重试。已取消的请求不能覆盖后续相同范围的新请求。
|
||||
- 本地复现原钻取存在 23 帧空白,修复后三级钻取与六主题均为零空白帧;快速返回重入、失败保留、实际筛选框尺寸及相关检查通过,未发布。
|
||||
|
||||
## 2026-11-01:查询操作强调与底部精简
|
||||
|
||||
- 各级返回按钮统一为带左箭头的“返回上一级”,沿用原有父级路径,使用主题色描边与浅底;Excel 导出使用实色主按钮,两者统一加粗。
|
||||
- 趋势数据表取消底部分页统计与月份汇总链接,直接展示已返回的期间;保留月份行的筛选操作。各查询页删除“点击期间筛选”类提示。
|
||||
- 本地实测三级返回、月份行筛选及六主题按钮效果;主汇总表分页和 Excel 导出行为保持原有方式。
|
||||
|
||||
## 2026-11-02:全系统统一加载(用户批准方案)
|
||||
|
||||
- 维持现有布局、主题及 280/520 毫秒过渡;150 毫秒后显示区域加载提示。首次失败、更新失败、成功空结果分别呈现,更新时保留已生效范围的结果。
|
||||
- 更新中的旧范围结果不能钻取、查看明细或导出;区域独立重试。任务使用真实阶段,写入即时忙碌并防重复,不显示虚构百分比或新增常驻说明。
|
||||
- 返回页面保留筛选、页码、滚动位置及表格高度;隐藏页面和未选管理页签不主动刷新。业务分页、全范围搜索排序和导出不变。
|
||||
- 实现与验证详见 docs/全系统统一加载实现与验收_20261102.md。
|
||||
|
||||
- 2026-11-02:趋势折线使用用户选定的 A 轻度平滑(0.15),沿横轴约束曲线;查询合格率、不良率、智能分析与导出统一。柏拉图累计线保持直线,数据点、缺失断点和计算口径不变。
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
|
||||
比例转百分数乘100;两比例之差乘100才是“百分点”。例如0.96→0.95是下降1个百分点,不能先对原始比例差保留两位再换算。保留原始精度到最后展示一步。空值表示缺失/不适用,不等于零;新增/退出对象允许描述重量变化,但不补造其缺失期合格率。
|
||||
|
||||
合格率变化统一为“本期-比较期”:下降显示 -X.XX pp,上升显示 +X.XX pp,持平为 0.00 pp;可另外标注方向。rateDrop/rate_drop 是比较期减本期的降幅排序量,不能直接当作有符号变化;展示其变化时取反并按正式单位换算,排序顺序不变。优先引用工具已提供的正式变化值,不能从舍入后的两期率重新计算。
|
||||
|
||||
重量统一以正式kg展示。仅正式schema/返回单位明确为kg的质量字段允许按精确Decimal固定1000识别吨展示,最终仍统一kg;未知来源单位、件数、率和百分点不能按重量换算。严格比较阈值保留原始精确边界,不能用舍入值改变“低于/超过”等关系。工具formalDisplay与原始值共同给出正式展示;OwnStageRateChangePp是阶段自身率变化,ContributionPp才是对综合率的贡献,不能因同阶段同为百分点互换,也不能用舍入相邻值修正错误贡献。
|
||||
|
||||
“汽车交通”是“新能源汽车磁钢”产业部的业务别名,统一用 filters.department=新能源汽车磁钢;不能用国内和海外的 group 多选集合替代产业部范围,两者原始记录覆盖未必相同。国内、海外是该产业部下的业务分组,查询子分组时保留 department 并添加明确 group;比较分组时用 changes+dimension=group,父筛选仍为 department。总体指全公司。规格对应 product。期间、范围、基期、发布版本要一致。默认比较上一个完整期间;如果用户未给年份和月份,从可用数据目录与上下文判断,首次使用在回答中简短说明,不把当前日历月当成已有数据月。
|
||||
|
||||
@@ -2,12 +2,16 @@
|
||||
|
||||
先读 /RULES.md 了解正式公式、单位、范围和来源语义;需要时读 /agent/mcps/quality/quality_data.json 一次了解工具。所有业务数据经原生 mcp_call 调用 quality 的 quality_data 取得。不调用数据库、execute_sql、display_chart 或 story;平台负责图表与报告。
|
||||
|
||||
本模式开放只读文件工具 read/list/grep/search 和 quality 的 mcp_call/mcp_connect。平台负责查询前的任务澄清、数据绑定和后续追问;不使用原生 clarification、数据库选择、凭据收集、建议追问或写入工具结束任务。证据足够时,在最后一次查询返回后直接输出最终正文,并正常结束;工具返回、图表安排或进度说明不等于最终回答。
|
||||
|
||||
本会话使用自主调查模式。遵守RULES中的正式公式、数据语义与证据边界,不设固定全维度覆盖、维度顺序或自动补查配方。以本轮 _agentTask 的明确目标和约束为准:必要基线→观察结果→选择下次查询或验证反例→判断是否已回答。不要为了覆盖目录而查询每个产业部、分组或规格,不固定只追一个产品或一个阶段。若多个线索同样重要,应比较后再判断。
|
||||
|
||||
正式数值直接来自工具,不能自行重算KPI或编造缺失值。你可以解释分子分母、规模、结构及阶段的关系,清楚区分已核实事实、统计线索与待验证生产假设;引用真实 evidenceRef。工具支持的正式差值和阶段拆解可以直接引用;缺少的数据不得补零。统计关联不能宣称已证实设备、工艺、供应商或人员根因。
|
||||
|
||||
优先使用工具formalDisplay的规范数值与单位,重量最终统一kg。阶段自身率变化与对综合率贡献按metricRole明确区分;不能把OwnStageRateChangePp当ContributionPp,也不能从舍入后的阶段变化凑总体等式。只有正式原单位明确kg的质量字段可按固定1000识别吨,数量和未知单位不换算,严格阈值不舍入。
|
||||
|
||||
合格率变化统一为“本期-比较期”:下降显示 -X.XX pp,上升显示 +X.XX pp,持平为 0.00 pp;可另外标注方向。rateDrop/rate_drop 是比较期减本期的降幅排序量,不能直接当作有符号变化;展示其变化时取反并按正式单位换算,排序顺序不变。优先引用工具已提供的正式变化值,不能从舍入后的两期率重新计算。
|
||||
|
||||
当前已确认 filters、period、comparisonPeriod 是唯一范围权威。历史问答只帮助理解指代,不能恢复已取消条件。每轮使用同一个内部releaseId但不向用户展示内部ID、版本锁定或执行协议。修改用户范围需要下一轮确认;调查内只允许保持父条件、沿授权目录缩小对象。
|
||||
|
||||
原因分析须先取得整个已确认范围的正式本期/比较期基线,再决定是否缩小范围;不能用某个子分组或单个规格的率代替整个问题范围。首次compare/query保持_agentTask.filters原样,不额外添加子对象。之后的方向和深度由真实返回的线索决定。
|
||||
|
||||
@@ -37,7 +37,7 @@ releaseId、发布版本号、候选发布状态、Story ID/slug/version 仅作
|
||||
整体变化先用简短摘要说清变化方向、主要阶段和优先核查线索,再展开各节。每节先写一到三句解释已确认的现象及实际含义,必要时附一张紧凑数据表,不只连续抄表、不在“重点关注”重复全部数字。阶段数学影响沿用 stageDecomposition 的服务端结果,不能把阶段自身率变化当作对综合率贡献,也不把数学拆解称现场生产根因。亮片报废下降而投入下降更多时,要明确解释合格率仍可能下降。
|
||||
|
||||
常规整体分析的重点规格优先结合报废增量、当前规模、率变化和分阶段有效投入确定核查优先级。单按合格率降幅返回的小批量、0率或阶段缺失规格,另列“极端率变化线索”,不能只因降幅大就称整体主要原因;两期分母未查清时不推断停产、退出或全批报废。用户明确只看降幅排名时保留真实排名与批量背景。不得自设未授权的最低批量阈值或忽略小批量的安全/质量异常。
|
||||
即使这些规格报废绝对重量较小,也不能据此断言其对总体综合率的影响“可忽略”或计算贡献;只能说明报废重量及投入规模,并把总体影响留待正式可加总口径核验。0率原因未核实前,不用“更可能是全批报废/覆盖问题”等概率判断,只写待核对的分母、批次和数据覆盖。没有已确认的批量阈值时,不给规格贴“批量有效/无代表性”的确定性标签,可具体写两期投入重量及其变化。合格率变化一律明确比较期→本期,并写“下降/上升X.XX个百分点”,避免只写带符号的pp。
|
||||
即使这些规格报废绝对重量较小,也不能据此断言其对总体综合率的影响“可忽略”或计算贡献;只能说明报废重量及投入规模,并把总体影响留待正式可加总口径核验。0率原因未核实前,不用“更可能是全批报废/覆盖问题”等概率判断,只写待核对的分母、批次和数据覆盖。没有已确认的批量阈值时,不给规格贴“批量有效/无代表性”的确定性标签,可具体写两期投入重量及其变化。合格率变化统一为“本期-比较期”:下降显示 -X.XX pp,上升显示 +X.XX pp,持平为 0.00 pp;可另外标注方向。rateDrop/rate_drop 是比较期减本期的降幅排序量,不能直接当作有符号变化;展示其变化时取反并按正式单位换算,排序顺序不变。优先引用工具已提供的正式变化值,不能从舍入后的两期率重新计算。
|
||||
|
||||
组织、规格和具体缺陷之间的关系只写实际交叉查询已经核对的联系;没有交叉证据时保持各自范围,不把两个独立排名拼成因果链。最后只列能执行的优先核查问题,分清已确认现象与待验证原因,不编造责任人、完成期限或闭环结果。所有图文继续复用同一轮证据;不要为了报告样式重复查询、重新计算核心指标或自动生成故事。
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package cn.yunsheng.quality.analysis;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** 模型选择的普通对话不产生业务事实;确认与发布使用同一份受限原文。 */
|
||||
final class AnalysisDirectConversation {
|
||||
private static final Pattern FORBIDDEN=Pattern.compile(
|
||||
"(?:\\d+(?:[.,]\\d+)*|[零〇一二两三四五六七八九十百千万点]+)\\s*(?:[%%]|kg\\b|公斤|千克|吨|个百分点|pp\\b)"
|
||||
+"|百分之|(?:合格率|投入|报废|总重|产量|重量|数量)(?:重量|数量|总数|率)?\\s*(?:为|是|有|达到|共|合计|总计|[::])?\\s*(?:\\d|[零〇一二两三四五六七八九十百千万点])"
|
||||
+"|(?:已|已经)(?:查到|查询|核实|统计|生成|保存|记住|修改|设置|完成分析)(?!的)"
|
||||
+"|https?://|Q[A-F0-9]{8}|<[^>]+>|Bearer\\s+|\\bsk-[A-Za-z0-9_-]+|(?:api[_-]?key|token|password)\\s*[:=]",
|
||||
Pattern.CASE_INSENSITIVE|Pattern.UNICODE_CASE);
|
||||
private static final Pattern BUSINESS=Pattern.compile("合格率|报废|投入|产量|重量|分组|规格|产业部|国内|海外|产品");
|
||||
private static final Pattern CLAIM=Pattern.compile("主要是.{0,40}所致|主要来自|主要原因是|所致|远高于|远低于|确实更(?:大|小|差|好)|基本持平|(?:下降|上升|增加|减少|恶化|改善)了|明显.{0,8}(?:下降|上升|增加|减少)|导致.{0,12}(?:下降|上升)");
|
||||
static boolean applies(Map<String,Object> task) {return task.get("directResponse") instanceof Map<?,?>;}
|
||||
static void validate(Map<String,Object> task) {
|
||||
Map<String,Object> reply=AnalysisProtocolService.map(task.get("directResponse"));
|
||||
if(!Set.of("explain","restate").contains(Objects.toString(task.get("kind"),""))
|
||||
||!reply.keySet().equals(Set.of("purpose","answer","requiresMemory"))
|
||||
||!Set.of("greeting","capabilities","acknowledgement").contains(Objects.toString(reply.get("purpose"),""))
|
||||
||!Boolean.FALSE.equals(reply.get("requiresMemory")))throw invalid();
|
||||
for(String key:List.of("freshQuery","comparisonRequired","trendRequired","verifySource","fullDetails","needsClarification"))
|
||||
if(!Boolean.FALSE.equals(task.get(key)))throw invalid();
|
||||
for(String key:List.of("dimensions","stages","fields"))if(!(task.get(key) instanceof List<?> values)||!values.isEmpty())throw invalid();
|
||||
if(task.get("memberFields")!=null&&!(task.get("memberFields") instanceof List<?> values&&values.isEmpty()))throw invalid();
|
||||
if(task.get("dimensionStages")!=null&&!(task.get("dimensionStages") instanceof Map<?,?> values&&values.isEmpty()))throw invalid();
|
||||
if(task.containsKey("queryPlan")||!"none".equals(task.get("visualPreference"))||task.get("visualType")!=null
|
||||
||!"none".equals(task.getOrDefault("historyMode","none"))||"native_agent".equals(task.get("executionMode")))throw invalid();
|
||||
if(!(reply.get("answer") instanceof String text)||text.isBlank()||text.length()>1200||FORBIDDEN.matcher(text).find()
|
||||
||BUSINESS.matcher(text).find()&&CLAIM.matcher(text).find())throw invalid();
|
||||
}
|
||||
static Map<String,Object> answer(Map<String,Object> task,String release,Map<String,Object> context) {
|
||||
validate(task);
|
||||
var answer=new LinkedHashMap<String,Object>();answer.put("answer",AnalysisProtocolService.map(task.get("directResponse")).get("answer"));
|
||||
answer.put("engine","NAO");answer.put("releaseId",release);answer.put("context",context);answer.put("task",task);
|
||||
answer.put("completionMethod","direct_conversation");answer.put("businessResultsSentToModel",false);answer.put("stopReason","direct_conversation");
|
||||
for(String key:List.of("results","visuals","queryEvidenceRefs","protocolQueryIds"))answer.put(key,List.of());
|
||||
answer.put("visualSchemaVersion",1);answer.put("visualState","not_requested");return answer;
|
||||
}
|
||||
private static IllegalArgumentException invalid(){return new IllegalArgumentException("普通对话只允许问候、能力介绍或致谢,不得替代业务查询、事实判断或记忆操作");}
|
||||
}
|
||||
@@ -86,8 +86,13 @@ public class AnalysisProtocolService {
|
||||
var state=store.state(sessionId);
|
||||
Long prior="CLARIFICATION".equals(state.status()) ? state.revision() : state.confirmedRevision();
|
||||
if (prior!=null) previous=read(store.revision(sessionId,prior).taskJson());
|
||||
if("report".equals(previous.get("kind"))&&!retry) {
|
||||
var resumed=jdbc.query("SELECT task_json FROM analysis_protocol_revision WHERE session_id=? AND disposition='CONFIRMED' AND JSON_UNQUOTE(JSON_EXTRACT(task_json,'$.kind'))<>'report' ORDER BY revision DESC LIMIT 1",
|
||||
if(AnalysisDirectConversation.applies(previous)&&!retry) {
|
||||
// 取该修订首次确认前冻结的业务前态,保留待澄清任务,且不复活已取消的目标。
|
||||
var frozen=jdbc.query("SELECT input_json FROM analysis_protocol_attempt WHERE session_id=? AND revision=? AND execution_id IS NOT NULL ORDER BY created_at,attempt_id LIMIT 1",
|
||||
(rs,n)->read(rs.getString(1)),sessionId,prior);
|
||||
previous=frozen.isEmpty()?Map.of():map(frozen.getFirst().get("previousTask"));
|
||||
} else if("report".equals(previous.get("kind"))&&!retry) {
|
||||
var resumed=jdbc.query("SELECT task_json FROM analysis_protocol_revision WHERE session_id=? AND disposition='CONFIRMED' AND JSON_UNQUOTE(JSON_EXTRACT(task_json,'$.kind'))<>'report' AND (JSON_EXTRACT(task_json,'$.directResponse') IS NULL OR JSON_TYPE(JSON_EXTRACT(task_json,'$.directResponse'))='NULL') ORDER BY revision DESC LIMIT 1",
|
||||
(rs,n)->read(rs.getString(1)),sessionId);
|
||||
previous=resumed.isEmpty()?Map.of():resumed.getFirst();
|
||||
}
|
||||
@@ -321,8 +326,16 @@ public class AnalysisProtocolService {
|
||||
metadata.put("sourceStatus",input.get("sourceStatus"));metadata.put("queryRefs",checked.get("queryRefs"));metadata.put("missingEvidence",checked.get("missingEvidence"));
|
||||
var overlay=new LinkedHashMap<String,Object>();for(String key:List.of("visualSchemaVersion","visualState","visuals"))overlay.put(key,checked.get(key));overlay.put("visualRecovery",metadata);
|
||||
boolean originalComplete="COMPLETED".equals(input.get("sourceStatus"));
|
||||
boolean factsComplete=Boolean.TRUE.equals(map(map(input.get("sourceAnswer")).get("factCoverage")).get("complete"))&&Boolean.TRUE.equals(input.get("factsStillCovered"));
|
||||
if(!originalComplete&&factsComplete&&Boolean.TRUE.equals(checked.get("chartsComplete"))) {
|
||||
var sourceAnswer=map(input.get("sourceAnswer"));var quality=new LinkedHashMap<>(map(sourceAnswer.get("answerQuality")));
|
||||
boolean chartsComplete=Boolean.TRUE.equals(checked.get("chartsComplete"));
|
||||
if(!quality.isEmpty()){quality.put("chartsComplete",chartsComplete);overlay.put("answerQuality",quality);}
|
||||
boolean factsComplete=Boolean.TRUE.equals(map(sourceAnswer.get("factCoverage")).get("complete"))&&Boolean.TRUE.equals(input.get("factsStillCovered"));
|
||||
boolean narrativeComplete=Boolean.TRUE.equals(quality.get("narrativeComplete"))&&Boolean.TRUE.equals(quality.get("dataComplete"))
|
||||
&&!Boolean.FALSE.equals(sourceAnswer.get("nativeStopSucceeded"))
|
||||
&&!Boolean.FALSE.equals(quality.get("citationComplete"))&&list(quality.get("unresolvedEvidenceRefs")).isEmpty()
|
||||
&&!Objects.toString(sourceAnswer.get("answer"),"").isBlank();
|
||||
if(!originalComplete&&"PARTIAL".equals(input.get("sourceStatus"))&&factsComplete&&narrativeComplete&&chartsComplete) {
|
||||
metadata.put("priorMissingEvidence",list(quality.get("missingEvidence")));quality.put("missingEvidence",List.of());
|
||||
overlay.put("status","COMPLETED");overlay.put("originalStatus",input.get("sourceStatus"));
|
||||
overlay.put("completion",Map.of("completed",true,"reason","visual_recovery_complete"));overlay.put("stopReason","visual_recovery_complete");
|
||||
}
|
||||
@@ -415,7 +428,8 @@ public class AnalysisProtocolService {
|
||||
jdbc.update("UPDATE analysis_protocol_execution SET status='FAILED' WHERE execution_id=? AND status='RUNNING'",a.executionId());
|
||||
jdbc.update("UPDATE analysis_protocol_session SET status='FAILED',version=version+1 WHERE session_id=?",a.sessionId());
|
||||
jdbc.update("UPDATE analysis_protocol_attempt SET status='FAILED' WHERE attempt_id=?",id);
|
||||
Map<String,Object> answer=Map.of("answer",reason,"results",List.of(),"releaseId",a.releaseId(),"engine",a.input().containsKey("controlledInspection")?"CONTROLLED_INSPECTION_PROTOCOL":"NAO","completion",Map.of("completed",false,"reason",reason));
|
||||
boolean nativeConversation=autonomousSession(a.sessionId())&&!a.input().containsKey("controlledInspection");
|
||||
Map<String,Object> answer=Map.of("answer",nativeConversation?"":reason,"results",List.of(),"releaseId",a.releaseId(),"engine",a.input().containsKey("controlledInspection")?"CONTROLLED_INSPECTION_PROTOCOL":"NAO","completion",Map.of("completed",false,"reason",reason));
|
||||
jdbc.update("UPDATE analysis_turn SET status='FAILED',answer_json=CAST(? AS JSON),stop_reason=?,finished_at=CURRENT_TIMESTAMP(6) WHERE id=?",write(answer),reason,a.turnId());
|
||||
inspection.updateAssociation(a,"FAILED");
|
||||
event(id,"failed",Map.of("turnId",a.turnId(),"status","FAILED","result",answer,"stopReason",reason));
|
||||
@@ -486,6 +500,7 @@ public class AnalysisProtocolService {
|
||||
if(!target.equals("POST /api/analysis/protocol/history")||!params.isEmpty()||nodeId!=null||scopeId!=null)throw denied("历史报告不能执行新的正式查询");
|
||||
return Map.of();
|
||||
}
|
||||
if(AnalysisDirectConversation.applies(task))throw denied("普通对话不能执行正式业务查询");
|
||||
if(target.equals("POST /api/analysis/protocol/queries")) {
|
||||
if(!task.containsKey("queryPlan")&&!AnalysisProtocolExploration.nativeAgent(task)||nodeId!=null||scopeId!=null)throw denied("当前任务未声明分步查询");
|
||||
return Map.of();
|
||||
@@ -625,15 +640,24 @@ public class AnalysisProtocolService {
|
||||
binding.current(a.sessionId(),a.turnId(),a.userId(),a.revision(),a.executionId());
|
||||
Map<String,Object> task=read(store.revision(a.sessionId(),a.revision()).taskJson());
|
||||
if(!Objects.equals(canonical(task),canonical(details.get("agentTask")))) throw denied("最终答复没有绑定当前任务");
|
||||
if(Set.of("COMPLETED","PARTIAL").contains(status)&&!"report".equals(task.get("kind"))
|
||||
if(Set.of("COMPLETED","PARTIAL").contains(status)&&AnalysisDirectConversation.applies(task)) {
|
||||
answer=AnalysisDirectConversation.answer(task,a.releaseId(),taskContext(a.releaseId(),task));
|
||||
status="COMPLETED";
|
||||
} else if(Set.of("COMPLETED","PARTIAL").contains(status)&&!"report".equals(task.get("kind"))
|
||||
&&!hasProtocolEvidence(details)) {
|
||||
status="FAILED";
|
||||
String original=AnalysisProtocolExploration.nativeAgent(task)?Objects.toString(answer.get("answer"),""):null;
|
||||
answer.clear();
|
||||
answer.put("answer",noProofFailureReason(details));
|
||||
answer.put("answer",original!=null?original:noProofFailureReason(details));
|
||||
answer.put("results",List.of());
|
||||
answer.put("releaseId",a.releaseId());
|
||||
answer.put("engine","NAO");
|
||||
answer.put("stopReason","formal_query_evidence_missing");
|
||||
if(original!=null) {
|
||||
answer.put("executionMode","native_agent");
|
||||
answer.put("answerQuality",Map.of("version",1,"dataComplete",false,"narrativeFactBinding","not_assessed",
|
||||
"missingEvidence",List.of(noProofFailureReason(details))));
|
||||
}
|
||||
} else if(Set.of("COMPLETED","PARTIAL").contains(status)) {
|
||||
governance.requireBoundAction("QUERY","query.aggregate");
|
||||
if(AnalysisProtocolInspection.KIND.equals(task.get("kind"))) {
|
||||
@@ -672,7 +696,7 @@ public class AnalysisProtocolService {
|
||||
answer.put("answerQuality",quality);
|
||||
}
|
||||
if(AnalysisProtocolExploration.nativeAgent(task)){for(String key:List.of("scopeCoverage","explorationWarnings","conclusionProtocolQueryIds","attemptProtocolQueryIds"))if(checked.containsKey(key))answer.put(key,checked.get(key));}
|
||||
if(Boolean.TRUE.equals(task.get("verifySource"))||Boolean.TRUE.equals(task.get("fullDetails"))) {
|
||||
if(!AnalysisProtocolExploration.nativeAgent(task)&&(Boolean.TRUE.equals(task.get("verifySource"))||Boolean.TRUE.equals(task.get("fullDetails")))) {
|
||||
for(String field:List.of("reportMarkdown","reportHtml","reportTitle"))answer.remove(field);
|
||||
String rawStatus=rawStatusText(checked,map(recordList));
|
||||
if(planResolution(a,task,actor).scopes().stream().allMatch(AnalysisProtocolService::rawScope))answer.put("answer",rawStatus);
|
||||
@@ -680,7 +704,7 @@ public class AnalysisProtocolService {
|
||||
}
|
||||
if(!Boolean.TRUE.equals(checked.get("complete"))) {
|
||||
status="PARTIAL";answer.put("stopReason","evidence_incomplete");
|
||||
if(AnalysisProtocolExploration.nativeAgent(task))appendCoverageNotices(answer,list(checked.get("missingEvidence")));
|
||||
if(AnalysisProtocolExploration.nativeAgent(task))appendNativeCoverageDiagnostics(answer,list(checked.get("missingEvidence")));
|
||||
}
|
||||
} else {
|
||||
validateMetricEvidence(a,task,details);
|
||||
@@ -801,6 +825,15 @@ public class AnalysisProtocolService {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
/** Native model prose is immutable; coverage gaps belong to the saved execution metadata. */
|
||||
static void appendNativeCoverageDiagnostics(Map<String,Object> answer,List<?> missing) {
|
||||
var gaps=new LinkedHashSet<String>();
|
||||
var quality=new LinkedHashMap<>(map(answer.get("answerQuality")));
|
||||
for(Object raw:list(quality.get("missingEvidence")))if(raw instanceof String gap&&!gap.isBlank())gaps.add(gap);
|
||||
for(Object raw:missing)if(raw instanceof String gap&&!gap.isBlank())gaps.add(gap);
|
||||
if(gaps.isEmpty())return;
|
||||
quality.putIfAbsent("version",1);quality.put("missingEvidence",List.copyOf(gaps));answer.put("answerQuality",quality);
|
||||
}
|
||||
/** A server downgrade must remain visible even when the model omitted its own limitations. */
|
||||
private void appendCoverageNotices(Map<String,Object> answer,List<?> missing) {
|
||||
var gaps=missing.stream().filter(String.class::isInstance).map(String.class::cast).filter(s->!s.isBlank()).distinct().toList();
|
||||
@@ -1668,6 +1701,12 @@ public class AnalysisProtocolService {
|
||||
}
|
||||
}
|
||||
}
|
||||
if(AnalysisDirectConversation.applies(t)) {
|
||||
try {AnalysisDirectConversation.validate(t);}catch(IllegalArgumentException invalid){throw conflict(invalid.getMessage());}
|
||||
if(t.get("period")!=null)period(map(t.get("period")));
|
||||
if(t.get("comparisonPeriod")!=null)period(map(t.get("comparisonPeriod")));
|
||||
return t;
|
||||
}
|
||||
period(map(t.get("period")));
|
||||
if(Boolean.TRUE.equals(t.get("needsClarification"))) {
|
||||
if(!(t.get("clarification") instanceof String s)||s.isBlank())throw conflict("澄清必须说明待确认对象");
|
||||
|
||||
@@ -1626,6 +1626,15 @@ public class AnalysisTurnService {
|
||||
if(quality.get(field) instanceof Boolean value)safe.put(field,value);
|
||||
if(quality.get("missingEvidence") instanceof List<?> gaps)safe.put("missingEvidence",gaps.stream()
|
||||
.filter(value->value instanceof String gap&&!gap.isBlank()&&gap.length()<=1000).distinct().limit(20).toList());
|
||||
if("not_assessed".equals(quality.get("narrativeFactBinding")))safe.put("narrativeFactBinding","not_assessed");
|
||||
for(String field:List.of("citedEvidenceRefs","unresolvedEvidenceRefs"))if(quality.get(field) instanceof List<?> refs) {
|
||||
var visible=refs.stream().filter(value->value instanceof String ref&&ref.matches("Q[A-F0-9]{8}")
|
||||
&&(!field.equals("citedEvidenceRefs")||(answer.get("queryEvidenceRefs") instanceof List<?> allowed?allowed:List.of()).contains(ref))).distinct().limit(100).toList();
|
||||
safe.put(field,visible);
|
||||
if(field.equals("unresolvedEvidenceRefs"))safe.put("citationComplete",visible.isEmpty());
|
||||
}
|
||||
if(quality.get("notices") instanceof List<?> notices)safe.put("notices",notices.stream()
|
||||
.filter(value->value instanceof String notice&&!notice.isBlank()&¬ice.length()<=1000).distinct().limit(20).toList());
|
||||
answer.put("answerQuality",safe);
|
||||
}
|
||||
Object count = details.get("toolCount");
|
||||
|
||||
@@ -13,6 +13,7 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -429,6 +430,26 @@ public class NaoAnalysisRunner {
|
||||
status = "FAILED";
|
||||
if (reason.isBlank()) reason = "原装 NAO 返回了无效结束状态";
|
||||
}
|
||||
boolean conflictingExit=Boolean.FALSE.equals(message.get("nativeStopSucceeded"))
|
||||
|| message.get("finishReason") instanceof String finish&&!finish.isBlank()&&!"stop".equalsIgnoreCase(finish)
|
||||
|| message.get("toolCalls") instanceof List<?> calls&&calls.stream().anyMatch(raw->raw instanceof Map<?,?> call&&"started".equals(call.get("status")))
|
||||
|| message.get("answerQuality") instanceof Map<?,?> quality&&Boolean.FALSE.equals(quality.get("narrativeComplete"));
|
||||
if(Set.of("COMPLETED","PARTIAL").contains(status)&&conflictingExit) {
|
||||
if("COMPLETED".equals(status)){status="PARTIAL";reason="incomplete_finish";}
|
||||
var quality=new LinkedHashMap<String,Object>();
|
||||
if(message.get("answerQuality") instanceof Map<?,?> prior)prior.forEach((k,v)->quality.put(String.valueOf(k),v));
|
||||
quality.put("version",1);quality.put("narrativeComplete",false);details.put("answerQuality",quality);
|
||||
}
|
||||
boolean visibleBody=!answer.isBlank()
|
||||
|| message.get("reportMarkdown") instanceof String markdown&&!markdown.isBlank()
|
||||
|| message.get("reportHtml") instanceof String html&&!html.isBlank()
|
||||
|| message.get("memberList") instanceof Map<?,?> || message.get("recordList") instanceof Map<?,?>;
|
||||
if("COMPLETED".equals(status)&&!visibleBody) {
|
||||
status="PARTIAL";reason="answer_missing";
|
||||
var quality=new LinkedHashMap<String,Object>();
|
||||
if(message.get("answerQuality") instanceof Map<?,?> prior)prior.forEach((k,v)->quality.put(String.valueOf(k),v));
|
||||
quality.put("version",1);quality.put("narrativeComplete",false);details.put("answerQuality",quality);
|
||||
}
|
||||
if ("FAILED".equals(status) && safeMessage != null) {
|
||||
details.put("message", safeMessage);
|
||||
if (answer.isBlank()) answer = safeMessage;
|
||||
@@ -437,6 +458,7 @@ public class NaoAnalysisRunner {
|
||||
details.remove("message");
|
||||
}
|
||||
details.put("status", status);
|
||||
details.put("stopReason", reason);
|
||||
details.put("answer", answer);
|
||||
details.put("engine", "NAO");
|
||||
return new Result(status, answer, details, reason);
|
||||
|
||||
@@ -5,6 +5,7 @@ import cn.yunsheng.quality.identity.AppUserPrincipal;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
@@ -26,14 +27,25 @@ public class WorkspaceStateController {
|
||||
var policy = jdbc.queryForList("SELECT detail_allowed,evidence_allowed,original_download_allowed,CAST(allowed_fields AS CHAR) AS allowed_fields,valid_until,inherit_department_children,row_version FROM user_access_policy WHERE user_id=?", actor.getId().toString());
|
||||
String auth = digest(List.of(actor.getId(), actor.getRoleCodes().stream().sorted().toList(),
|
||||
actor.getDepartments().stream().sorted().toList(), actor.getGroups().stream().sorted().toList(), policy));
|
||||
var currentRelease = jdbc.queryForList("SELECT * FROM current_release ORDER BY dataset_id");
|
||||
String currentReleaseId = currentRelease.stream()
|
||||
.filter(row -> "quality".equals(String.valueOf(row.get("dataset_id"))))
|
||||
.map(row -> row.get("release_id"))
|
||||
.filter(java.util.Objects::nonNull)
|
||||
.map(String::valueOf)
|
||||
.findFirst().orElse(null);
|
||||
String data = digest(List.of(
|
||||
jdbc.queryForList("SELECT * FROM current_release ORDER BY dataset_id"),
|
||||
currentRelease,
|
||||
jdbc.queryForList("SELECT * FROM platform_metadata ORDER BY metadata_key"),
|
||||
jdbc.queryForList("SELECT id,row_version FROM target_version WHERE status='ACTIVE' ORDER BY id"),
|
||||
jdbc.queryForList("SELECT * FROM query_filter_field ORDER BY field_key"),
|
||||
jdbc.queryForList("SELECT id,row_version FROM service_identity ORDER BY id"),
|
||||
jdbc.queryForList("SELECT * FROM service_binding ORDER BY service_type")));
|
||||
return Map.of("authRevision", auth, "dataRevision", data);
|
||||
Map<String, String> result = new LinkedHashMap<>();
|
||||
result.put("authRevision", auth);
|
||||
result.put("dataRevision", data);
|
||||
result.put("currentReleaseId", currentReleaseId);
|
||||
return result;
|
||||
}
|
||||
private static String digest(Object value) {
|
||||
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.toString().getBytes(StandardCharsets.UTF_8))); }
|
||||
|
||||
@@ -76,6 +76,37 @@ public class MetricsController {
|
||||
extraFilters, exclusions, columnFilters, stage, actor);
|
||||
}
|
||||
|
||||
/** 轻量趋势接口:查询参数与正式指标接口一致,但只返回版本、上下文、趋势和覆盖信息。 */
|
||||
@GetMapping("/trend")
|
||||
@PreAuthorize("hasAnyRole('SYSTEM_ADMIN','QUALITY_VIEWER','BUSINESS_ANALYST')")
|
||||
public MetricsService.MetricTrendSnapshot trendHttp(@RequestParam(required = false) Integer year,
|
||||
@RequestParam(required = false) Integer month,
|
||||
@RequestParam(required = false) Integer monthStart,
|
||||
@RequestParam(required = false) Integer monthEnd,
|
||||
@RequestParam(required = false) String quarter,
|
||||
@RequestParam(required = false) String department,
|
||||
@RequestParam(required = false) String group,
|
||||
@RequestParam(required = false) String product,
|
||||
@RequestParam(required = false) String productSearch,
|
||||
@RequestParam(required = false) String projectGroup,
|
||||
@RequestParam(defaultValue = "overall") String view,
|
||||
@RequestParam(defaultValue = "true") boolean includeUnassigned,
|
||||
@RequestParam(required = false) String releaseId,
|
||||
@RequestParam(defaultValue = "month") String trendGranularity,
|
||||
@RequestParam(required = false) String extraFilters,
|
||||
@RequestParam(required = false) String exclusions,
|
||||
@RequestParam(required = false) String columnFilters,
|
||||
@RequestParam(required = false) String stage,
|
||||
@AuthenticationPrincipal AppUserPrincipal actor) {
|
||||
Integer quarterNumber = parseQuarter(quarter);
|
||||
MetricsService.MetricsQuery query = new MetricsService.MetricsQuery(year, month, quarterNumber, department,
|
||||
group, product, projectGroup, view, includeUnassigned, releaseId, trendGranularity,
|
||||
parseExclusions(exclusions));
|
||||
query = query.withMonthRange(monthStart, monthEnd).withExtraFilters(extraFilters)
|
||||
.withProductSearch(productSearch).withColumnFilters(columnFilters).withStage(stage);
|
||||
return responseAccess.visibleTrend(metrics.calculateTrend(query, actor), actor);
|
||||
}
|
||||
|
||||
/** Existing direct callers retain the pre-range controller signature. */
|
||||
public MetricsService.MetricSnapshot calculate(Integer year, Integer month, String quarter,
|
||||
String department, String group, String product, String productSearch,
|
||||
|
||||
@@ -5,6 +5,7 @@ import cn.yunsheng.quality.identity.AppUserPrincipal;
|
||||
import cn.yunsheng.quality.metrics.MetricsService.DefectRow;
|
||||
import cn.yunsheng.quality.metrics.MetricsService.MetricRow;
|
||||
import cn.yunsheng.quality.metrics.MetricsService.MetricSnapshot;
|
||||
import cn.yunsheng.quality.metrics.MetricsService.MetricTrendSnapshot;
|
||||
import cn.yunsheng.quality.metrics.MetricsService.MetricStage;
|
||||
import cn.yunsheng.quality.metrics.MetricsService.TrendMetricRow;
|
||||
import java.util.List;
|
||||
@@ -30,6 +31,25 @@ public class MetricsResponseAccess {
|
||||
return new MetricSnapshot(filtered.release(), filtered.context(), hideDefects(filtered.summary()), List.of(), List.of(), defects, filtered.coverage());
|
||||
}
|
||||
|
||||
/** 趋势查询沿用明细授权和指标字段可见性边界。 */
|
||||
public MetricTrendSnapshot visibleTrend(MetricTrendSnapshot snapshot, AppUserPrincipal actor) {
|
||||
governance.requireUserActivePolicy(actor);
|
||||
if (!Boolean.TRUE.equals(governance.policy(actor.getId().toString()).get("detailAllowed")))
|
||||
return new MetricTrendSnapshot(snapshot.release(), snapshot.context(), List.of(), snapshot.coverage());
|
||||
governance.requireBoundAction("QUERY", "query.detail");
|
||||
Set<String> allowed = governance.allowedFields(actor);
|
||||
List<TrendMetricRow> trend = allowed.contains("*") ? snapshot.trend()
|
||||
: snapshot.trend().stream().map(row -> restrictTrend(row, allowed)).toList();
|
||||
return new MetricTrendSnapshot(snapshot.release(), snapshot.context(), trend, snapshot.coverage());
|
||||
}
|
||||
|
||||
private TrendMetricRow restrictTrend(TrendMetricRow row, Set<String> allowed) {
|
||||
return new TrendMetricRow(row.month(), row.key(), row.label(), row.department(), row.group(), row.product(),
|
||||
row.projectGroup(), row.compositeRate(), restrictDefects(row.black(), "black", allowed),
|
||||
restrictDefects(row.bright(), "bright", allowed), row.coverage(),
|
||||
row.compositeRateWithoutHeadquartersScrap(), row.period(), row.periodLabel(), row.granularity());
|
||||
}
|
||||
|
||||
private MetricRow hideDefects(MetricRow row) {
|
||||
return new MetricRow(row.key(), row.label(), row.department(), row.group(), row.product(), row.projectGroup(), row.compositeRate(),
|
||||
hideDefects(row.black()), hideDefects(row.bright()), row.coverage(), row.compositeRateWithoutHeadquartersScrap());
|
||||
|
||||
@@ -71,6 +71,113 @@ public class MetricsService {
|
||||
return calculateForRelease(query, actor, release);
|
||||
}
|
||||
|
||||
/** 只按时间桶生成趋势,不构造总体摘要或产品/分组维度行。 */
|
||||
public MetricTrendSnapshot calculateTrend(MetricsQuery query, AppUserPrincipal actor) {
|
||||
if (actor == null) throw new ResponseStatusException(HttpStatus.FORBIDDEN, "指标查询必须绑定当前有效用户");
|
||||
governance.requireUserActivePolicy(actor);
|
||||
governance.requireBoundAction("QUERY", "query.aggregate");
|
||||
validate(query);
|
||||
String releaseId = query.releaseId() == null || query.releaseId().isBlank()
|
||||
? currentReleaseId() : query.releaseId();
|
||||
if (releaseId == null) return emptyTrendSnapshot(query);
|
||||
ReleaseInfo release = release(releaseId, actor);
|
||||
return withConsistentSnapshot(() -> calculateTrendForReleaseSnapshot(query, actor, release));
|
||||
}
|
||||
|
||||
private MetricTrendSnapshot calculateTrendForReleaseSnapshot(MetricsQuery query, AppUserPrincipal actor,
|
||||
ReleaseInfo release) {
|
||||
boolean hasUnrolledBuilds = hasUnrolledBuilds(release.id());
|
||||
Map<String, AggregateStats> periods = queryTrendAggregates(release.id(), query, actor, hasUnrolledBuilds);
|
||||
String ruleVersion = jdbc.queryForObject("SELECT rule_version FROM data_release WHERE id=?", String.class, release.id());
|
||||
ConfigurableRuleEngine rules = rulesForVersion(ruleVersion);
|
||||
List<TrendMetricRow> trend = trendRows(periods, query.trendGranularity()).stream().map(row -> {
|
||||
MetricRow adjusted = rules.applyMetrics(new MetricRow(row.key(), row.label(), row.department(), row.group(),
|
||||
row.product(), row.projectGroup(), row.compositeRate(), row.black(), row.bright(), row.coverage(),
|
||||
row.compositeRateWithoutHeadquartersScrap()));
|
||||
return new TrendMetricRow(row.month(), adjusted.key(), adjusted.label(), adjusted.department(), adjusted.group(),
|
||||
adjusted.product(), adjusted.projectGroup(), adjusted.compositeRate(), adjusted.black(), adjusted.bright(),
|
||||
adjusted.coverage(), adjusted.compositeRateWithoutHeadquartersScrap(), row.period(), row.periodLabel(),
|
||||
row.granularity());
|
||||
}).toList();
|
||||
Map<String, Object> coverage = queryCoverage(release.id(), query, actor, hasUnrolledBuilds);
|
||||
Map<String, Object> context = context(query, query.includeUnassigned());
|
||||
context.put("ruleVersionId", ruleVersion == null ? BusinessRowMapper.RULE_VERSION : ruleVersion);
|
||||
context.put("calculationRules", rules.calculationRules());
|
||||
context.put("metricFormulaDescriptions", rules.formulaDescriptions());
|
||||
return new MetricTrendSnapshot(release.asMap(), context, trend, coverage);
|
||||
}
|
||||
|
||||
private Map<String, AggregateStats> queryTrendAggregates(String releaseId, MetricsQuery query,
|
||||
AppUserPrincipal actor, boolean hasUnrolledBuilds) {
|
||||
Map<String, AggregateStats> periods = new TreeMap<>();
|
||||
boolean hasSourceFilters = !query.extraFilters().isEmpty() || !query.columnFilters().isEmpty();
|
||||
if (!hasSourceFilters) {
|
||||
aggregateTrendStage(periods, "black", releaseId, query, actor, false);
|
||||
aggregateTrendStage(periods, "bright", releaseId, query, actor, false);
|
||||
}
|
||||
if (hasUnrolledBuilds || hasSourceFilters) {
|
||||
aggregateTrendStage(periods, "black", releaseId, query, actor, true);
|
||||
aggregateTrendStage(periods, "bright", releaseId, query, actor, true);
|
||||
}
|
||||
return periods;
|
||||
}
|
||||
|
||||
private void aggregateTrendStage(Map<String, AggregateStats> periods, String stage, String releaseId,
|
||||
MetricsQuery query, AppUserPrincipal actor, boolean factFallback) {
|
||||
if (query.stage() != null && !query.stage().equals(stage)) return;
|
||||
String table = factFallback ? (stage.equals("black") ? "fact_black" : "fact_bright") : "metric_rollup";
|
||||
StringBuilder where = new StringBuilder(" WHERE rm.release_id=?");
|
||||
List<Object> args = new ArrayList<>();
|
||||
args.add(releaseId);
|
||||
boolean hasSourceFilters = !query.extraFilters().isEmpty() || !query.columnFilters().isEmpty();
|
||||
if (factFallback && !hasSourceFilters)
|
||||
where.append(" AND NOT EXISTS (SELECT 1 FROM metric_rollup_build rb WHERE rb.build_id=f.build_id)");
|
||||
else if (!factFallback) { where.append(" AND f.stage=?"); args.add(stage); }
|
||||
appendTime(where, args, query);
|
||||
appendDimensions(where, args, query);
|
||||
appendExclusions(where, args, query);
|
||||
if (factFallback) {
|
||||
new QueryFilterFields(jdbc, governance).append(where, args, stage, query.extraFilters(), actor);
|
||||
if (!query.columnFilters().isEmpty())
|
||||
new SourceColumnQueries(jdbc, governance, JsonMapper.builder().build())
|
||||
.append(where, args, stage, query.columnFilters(), releaseId, actor);
|
||||
}
|
||||
DataScope.append(where, args, actor, "f.department COLLATE utf8mb4_0900_as_cs",
|
||||
"f.group_name COLLATE utf8mb4_0900_as_cs");
|
||||
if (!effectiveIncludeUnassigned(query)) where.append(" AND (f.group_name IS NOT NULL AND f.group_name<>'')");
|
||||
|
||||
String countExpression = factFallback ? "COUNT(*)" : "SUM(f.source_row_count)";
|
||||
String sql = """
|
||||
SELECT %s AS trend_period,
|
||||
SUM(f.qualified_weight) AS qualified_weight,
|
||||
SUM(f.scrap_weight) AS scrap_weight,
|
||||
SUM(f.total_weight) AS total_weight,
|
||||
%s AS black_responsibility_scrap,
|
||||
%s AS black_material_scrap,
|
||||
%s AS black_external_scrap,
|
||||
%s AS bright_headquarters_scrap,
|
||||
%s AS bright_plating_scrap,
|
||||
%s AS bright_material_scrap,
|
||||
%s AS bright_processing_scrap,
|
||||
%s AS bright_diffusion_scrap,
|
||||
%s AS row_count
|
||||
FROM release_member rm JOIN %s f ON f.build_id=rm.transform_build_id
|
||||
%s
|
||||
GROUP BY trend_period
|
||||
ORDER BY trend_period
|
||||
""".formatted(trendBucketExpression(query.trendGranularity()),
|
||||
componentSum("black_responsibility_scrap"), componentSum("black_material_scrap"),
|
||||
componentSum("black_external_scrap"), componentSum("bright_headquarters_scrap"),
|
||||
componentSum("bright_plating_scrap"), componentSum("bright_material_scrap"),
|
||||
componentSum("bright_processing_scrap"), componentSum("bright_diffusion_scrap"),
|
||||
countExpression, table, where);
|
||||
jdbc.query(sql, (RowCallbackHandler) rs -> {
|
||||
String period = rs.getString("trend_period");
|
||||
AggregateStats stats = new AggregateStats().read(rs, stage);
|
||||
periods.computeIfAbsent(period, ignored -> new AggregateStats()).merge(stage, stats);
|
||||
}, args.toArray());
|
||||
}
|
||||
|
||||
/** Candidate and historical release path reserved for the explicit governance reconciliation flow. */
|
||||
public MetricSnapshot calculateCandidateForGovernance(MetricsQuery query, AppUserPrincipal actor) {
|
||||
return withGovernanceSnapshot(() -> calculateForGovernance(query, actor, true));
|
||||
@@ -393,8 +500,12 @@ public class MetricsService {
|
||||
}
|
||||
|
||||
private List<TrendMetricRow> trendRows(AggregateSet aggregates, String granularity) {
|
||||
return trendRows(aggregates.periods(), granularity);
|
||||
}
|
||||
|
||||
private List<TrendMetricRow> trendRows(Map<String, AggregateStats> periods, String granularity) {
|
||||
List<TrendMetricRow> trend = new ArrayList<>();
|
||||
aggregates.periods().forEach((period, stats) -> {
|
||||
periods.forEach((period, stats) -> {
|
||||
String label = switch (granularity) {
|
||||
case "quarter" -> period.replace("-Q", "年第") + "季度";
|
||||
case "year" -> period + "年";
|
||||
@@ -688,6 +799,12 @@ public class MetricsService {
|
||||
Map.of("black", empty.black().defects(), "bright", empty.bright().defects()), coverage);
|
||||
}
|
||||
|
||||
private MetricTrendSnapshot emptyTrendSnapshot(MetricsQuery query) {
|
||||
Map<String, Object> coverage = Map.of("rawRows", 0, "includedRows", 0, "excludedBlankRows", 0,
|
||||
"unmappedRows", 0, "projectGroupUnconfiguredRows", 0, "missingStages", List.of(), "sourceMonths", List.of());
|
||||
return new MetricTrendSnapshot(null, context(query, query.includeUnassigned()), List.of(), coverage);
|
||||
}
|
||||
|
||||
void validate(MetricsQuery query) {
|
||||
if (query.year() != null && (query.year() < 2000 || query.year() > 2100)) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "年份无效");
|
||||
if (query.month() != null && (query.month() < 1 || query.month() > 12)) throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "月份无效");
|
||||
@@ -831,6 +948,8 @@ public class MetricsService {
|
||||
public record MetricSnapshot(Map<String, Object> release, Map<String, Object> context, MetricRow summary,
|
||||
List<MetricRow> rows, List<TrendMetricRow> trend, Map<String, Object> defects,
|
||||
Map<String, Object> coverage) {}
|
||||
public record MetricTrendSnapshot(Map<String, Object> release, Map<String, Object> context,
|
||||
List<TrendMetricRow> trend, Map<String, Object> coverage) {}
|
||||
public record ComparisonSnapshots(MetricSnapshot current, MetricSnapshot comparison) {}
|
||||
|
||||
private record Fact(String stage, String month, String department, String group, String projectGroup, String product,
|
||||
|
||||
@@ -2,6 +2,13 @@ server:
|
||||
address: 127.0.0.1
|
||||
port: ${PORT:5281}
|
||||
shutdown: graceful
|
||||
# 只压缩较大的 JSON 响应;SSE、表格和压缩包不在类型白名单中。
|
||||
compression:
|
||||
enabled: true
|
||||
min-response-size: 1KB
|
||||
mime-types:
|
||||
- application/json
|
||||
- application/problem+json
|
||||
servlet:
|
||||
session:
|
||||
cookie:
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package cn.yunsheng.quality.analysis;
|
||||
import java.util.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
class AnalysisDirectConversationTest {
|
||||
private Map<String,Object> task() {
|
||||
var t=new LinkedHashMap<String,Object>();t.put("kind","explain");t.put("visualPreference","none");t.put("historyMode","none");
|
||||
for(String k:List.of("freshQuery","comparisonRequired","trendRequired","verifySource","fullDetails","needsClarification"))t.put(k,false);
|
||||
for(String k:List.of("dimensions","stages","fields"))t.put(k,List.of());
|
||||
t.put("directResponse",new LinkedHashMap<>(Map.of("purpose","greeting","answer","你好!可以帮你查询质量指标,并比较期间变化。","requiresMemory",false)));return t;
|
||||
}
|
||||
@Test void acceptsModelSelectedConversationWithoutInventingADataPeriod() {
|
||||
var t=task();assertTrue(AnalysisDirectConversation.applies(t));assertDoesNotThrow(()->AnalysisDirectConversation.validate(t));
|
||||
t.put("period",Map.of("year",2026,"month",9));assertDoesNotThrow(()->AnalysisDirectConversation.validate(t));
|
||||
AnalysisProtocolService.map(t.get("directResponse")).put("answer","我可以帮你比较不同产业部谁表现更好,并整理已核实的历史结果。");
|
||||
assertDoesNotThrow(()->AnalysisDirectConversation.validate(t));
|
||||
}
|
||||
@Test void queryAndMemoryActionsCannotBypassTheEvidencePath() {
|
||||
for(String k:List.of("freshQuery","comparisonRequired","trendRequired","verifySource","fullDetails","needsClarification")) {
|
||||
var t=task();t.put(k,true);assertThrows(IllegalArgumentException.class,()->AnalysisDirectConversation.validate(t),k);
|
||||
}
|
||||
for(String k:List.of("fields","stages","dimensions","queryPlan","memberFields")) {
|
||||
var t=task();t.put(k,List.of("rate"));assertThrows(IllegalArgumentException.class,()->AnalysisDirectConversation.validate(t),k);
|
||||
}
|
||||
for(var change:List.<Map<String,Object>>of(Map.of("purpose","business_analysis"),Map.of("requiresMemory",true),Map.of("unexpected","hidden"))) {
|
||||
var t=task();AnalysisProtocolService.map(t.get("directResponse")).putAll(change);assertThrows(IllegalArgumentException.class,()->AnalysisDirectConversation.validate(t));
|
||||
}
|
||||
}
|
||||
@Test void unqueriedFactsTrendsAndUnperformedActionsAreRejected() {
|
||||
for(String s:List.of("合格率为95.5%","报废重量123","报废二十公斤","黑片合格率明显下降","黑片合格率下降了,主要原因是设备故障。","上月报废重量为一百。","国内报废主要来自设备问题","我已经保存你的偏好","已查询最新数据")) {
|
||||
var t=task();AnalysisProtocolService.map(t.get("directResponse")).put("answer",s);assertThrows(IllegalArgumentException.class,()->AnalysisDirectConversation.validate(t),s);
|
||||
}
|
||||
}
|
||||
@Test void linksCredentialsHtmlAndReferencesCannotBecomeConversationProse() {
|
||||
for(String s:List.of("见https://example.test","[QABCDEF12]","<b>你好</b>","Bearer synthetic","token=synthetic"," ","文".repeat(1201))) {
|
||||
var t=task();AnalysisProtocolService.map(t.get("directResponse")).put("answer",s);assertThrows(IllegalArgumentException.class,()->AnalysisDirectConversation.validate(t));
|
||||
}
|
||||
}
|
||||
@Test void theConfirmedModelTextIsPublishedOnceWithoutBusinessDataOrCharts() {
|
||||
var t=task();var answer=AnalysisDirectConversation.answer(t,"release",Map.of("releaseId","release"));
|
||||
assertEquals(AnalysisProtocolService.map(t.get("directResponse")).get("answer"),answer.get("answer"));assertEquals("direct_conversation",answer.get("completionMethod"));
|
||||
for(String k:List.of("results","visuals","queryEvidenceRefs","protocolQueryIds"))assertEquals(List.of(),answer.get(k));
|
||||
assertEquals(false,answer.get("businessResultsSentToModel"));
|
||||
}
|
||||
}
|
||||
+98
-8
@@ -273,6 +273,15 @@ class AnalysisProtocolServiceMySqlTest {
|
||||
tx.executeWithoutResult(s->service.completeVisualRecovery(claim.get("id").toString(),claim.get("token").toString(),proposed,actor));
|
||||
assertEquals(1,AnalysisProtocolService.list(tx.execute(s->service.visualRecoveryOverlay(turn,actor)).get("visuals")).size());
|
||||
}
|
||||
@Test void recoveredChartsCannotCompleteAnUnfinishedNarrative() {
|
||||
String turn=recoverableTurn(true,false);
|
||||
var claim=tx.execute(s->service.beginVisualRecovery(turn,actor));var input=AnalysisProtocolService.map(claim.get("input"));
|
||||
tx.executeWithoutResult(s->service.completeVisualRecovery(claim.get("id").toString(),claim.get("token").toString(),recoveryChart(input),actor));
|
||||
var overlay=tx.execute(s->service.visualRecoveryOverlay(turn,actor));
|
||||
assertFalse(overlay.containsKey("status"),json.writeValueAsString(overlay));
|
||||
assertEquals(true,AnalysisProtocolService.map(overlay.get("answerQuality")).get("chartsComplete"));
|
||||
assertEquals(false,AnalysisProtocolService.map(overlay.get("answerQuality")).get("narrativeComplete"));
|
||||
}
|
||||
@Test void aChartCannotCompleteMissingFactsOrPublishAfterTheOriginalAttemptIsRetried() {
|
||||
String turn=recoverableTurn(false);var claim=tx.execute(s->service.beginVisualRecovery(turn,actor));var input=AnalysisProtocolService.map(claim.get("input"));
|
||||
tx.executeWithoutResult(s->service.completeVisualRecovery(claim.get("id").toString(),claim.get("token").toString(),recoveryChart(input),actor));
|
||||
@@ -288,6 +297,9 @@ class AnalysisProtocolServiceMySqlTest {
|
||||
assertTrue(tx.execute(s->service.visualRecoveryOverlay(turn,actor)).isEmpty());
|
||||
}
|
||||
private String recoverableTurn(boolean facts) {
|
||||
return recoverableTurn(facts,true);
|
||||
}
|
||||
private String recoverableTurn(boolean facts,boolean narrative) {
|
||||
String turn=newTurn("2026年8至9月黑片报废重量月度趋势");var a=claim(turn,false);var t=task(turn,Map.of(),false);
|
||||
t.put("period",Map.of("year",2026,"monthStart",8,"monthEnd",9));t.put("periodCoverage","available");t.put("stages",List.of("black"));t.put("fields",List.of("scrapWeight"));t.put("visualPreference","required");
|
||||
var confirmed=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),t,actor)).get("task"));
|
||||
@@ -298,6 +310,8 @@ class AnalysisProtocolServiceMySqlTest {
|
||||
"coverage",Map.of("rawRows",2,"includedRows",2,"sourceMonths",List.of(Map.of("year",2026,"month",8,"blackRows",1,"brightRows",0),Map.of("year",2026,"month",9,"blackRows",1,"brightRows",0))));
|
||||
var proof=tx.execute(s->service.recordQuery(a.attemptId(),"GET","/api/metrics",parameters,response,actor));
|
||||
var result=answer();result.put("visualState","failed");result.put("visuals",List.of());
|
||||
if(!narrative)result.put("answer","");
|
||||
result.put("answerQuality",Map.of("version",1,"dataComplete",facts,"narrativeComplete",narrative,"chartsComplete",false));
|
||||
tx.executeWithoutResult(s->service.finish(a.attemptId(),"PARTIAL",result,Map.of("agentTask",confirmed,"protocolEvidence",List.of(proof),"factsComplete",facts,"evidenceCompletion",Map.of("serverCoverageSufficient",true)),actor));
|
||||
return turn;
|
||||
}
|
||||
@@ -1134,6 +1148,81 @@ class AnalysisProtocolServiceMySqlTest {
|
||||
assertEquals(40,jdbc.queryForObject("SELECT COUNT(*) FROM analysis_protocol_query",Integer.class));
|
||||
} finally {pool.shutdownNow();}
|
||||
}
|
||||
@Test void nativeWithoutFormalEvidenceKeepsOriginalBodyButCannotPublishMetricsOrSucceed() throws Exception {
|
||||
enableAutonomous();String turn=newTurn("原生回答缺少正式证据");var a=claim(turn,false);
|
||||
var task=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),nativeTask(turn,Map.of()),actor)).get("task"));
|
||||
String original="## 结论\n\n模型完整原文,不用平台错误句替换。";
|
||||
tx.executeWithoutResult(s->service.finish(a.attemptId(),"PARTIAL",Map.of("answer",original,"visuals",List.of(Map.of("id","unproved"))),Map.of("agentTask",task,"protocolEvidence",List.of()),actor));
|
||||
var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);
|
||||
assertEquals("FAILED",turnStatus(turn));assertEquals(original,saved.get("answer"));assertFalse(saved.containsKey("visuals"));
|
||||
assertEquals("native_agent",saved.get("executionMode"));
|
||||
assertEquals(false,AnalysisProtocolService.map(saved.get("answerQuality")).get("dataComplete"));
|
||||
assertEquals("formal_query_evidence_missing",saved.get("stopReason"));
|
||||
}
|
||||
@Test void nativePlanningFailureStoresReasonWithoutReplacingAnswerWithSystemError() throws Exception {
|
||||
enableAutonomous();String turn=newTurn("原生规划失败");var a=claim(turn,false);
|
||||
tx.executeWithoutResult(s->service.fail(a.attemptId(),"本轮分析未完成,请重试"));
|
||||
var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);
|
||||
assertEquals("FAILED",turnStatus(turn));assertEquals("",saved.get("answer"));
|
||||
assertEquals("本轮分析未完成,请重试",jdbc.queryForObject("SELECT stop_reason FROM analysis_turn WHERE id=?",String.class,turn));
|
||||
assertEquals(false,AnalysisProtocolService.map(saved.get("completion")).get("completed"));
|
||||
}
|
||||
@Test void ordinaryConversationCompletesWithoutPeriodOrFormalQueriesAndUsesConfirmedModelReply() throws Exception {
|
||||
enableAutonomous();String turn=newTurn("你好");var a=claim(turn,false);var proposal=task(turn,Map.of("columnFilters",List.of()),false);
|
||||
proposal.put("kind","explain");proposal.put("period",null);proposal.put("fields",List.of());proposal.put("trendRequired",false);
|
||||
for(String key:List.of("freshQuery","comparisonRequired","verifySource","fullDetails"))proposal.put(key,false);
|
||||
proposal.put("visualPreference","none");proposal.put("historyMode","none");
|
||||
String original="您好!我可以协助您查询质量指标、比较期间变化。";
|
||||
proposal.put("directResponse",Map.of("purpose","greeting","answer",original,"requiresMemory",false));
|
||||
var confirmed=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),proposal,actor)).get("task"));
|
||||
assertThrows(RuntimeException.class,()->tx.executeWithoutResult(s->service.checkTarget(a.attemptId(),"GET","/api/metrics",params(null),actor)));
|
||||
tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",Map.of("answer","不能替换已确认的原文","visuals",List.of(Map.of("id","forged"))),Map.of("agentTask",confirmed,"protocolEvidence",List.of()),actor));
|
||||
var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);
|
||||
assertEquals("COMPLETED",turnStatus(turn));assertEquals(original,saved.get("answer"));assertEquals("direct_conversation",saved.get("completionMethod"));
|
||||
assertEquals(List.of(),saved.get("visuals"));assertEquals(0,jdbc.queryForObject("SELECT COUNT(*) FROM analysis_protocol_query",Integer.class));
|
||||
String next=newTurn("继续分析");var nextAttempt=claim(next,false);assertEquals(Map.of(),nextAttempt.input().get("previousTask"));
|
||||
}
|
||||
@Test void thanksDoesNotReplaceTheBusinessGoalOrBecomeAHistoryReportSource() throws Exception {
|
||||
enableAutonomous();String business=completedHistoryMetric("18X15X4+T",9,"35.055");
|
||||
var before=AnalysisProtocolService.map(json.readValue(jdbc.queryForObject("SELECT plan_json FROM analysis_turn WHERE id=?",String.class,business),Map.class).get("task"));
|
||||
String turn=newTurn("谢谢");var a=claim(turn,false);var proposal=new LinkedHashMap<>(before);proposal.put("question","谢谢");proposal.put("goal","回应致谢");proposal.put("kind","explain");
|
||||
proposal.put("fields",List.of());proposal.put("stages",List.of());proposal.put("dimensions",List.of());proposal.put("historyMode","none");
|
||||
for(String key:List.of("freshQuery","comparisonRequired","trendRequired","verifySource","fullDetails","needsClarification"))proposal.put(key,false);
|
||||
proposal.put("directResponse",Map.of("purpose","acknowledgement","answer","不客气,可以继续提问。","requiresMemory",false));
|
||||
var confirmed=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),proposal,actor)).get("task"));
|
||||
tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",Map.of(),Map.of("agentTask",confirmed),actor));
|
||||
String report=newTurn("整理历史结果");var next=claim(report,false);assertEquals(before,next.input().get("previousTask"));
|
||||
var reportTask=historyTask(next,report,"all");assertEquals(List.of(business),reportTask.get("historySourceTurnIds"));
|
||||
}
|
||||
@Test void consecutiveConversationAndRetryPreserveThePendingClarificationGoal() {
|
||||
enableAutonomous();String business=newTurn("今年18×15×4综合率趋势");var a=claim(business,false);
|
||||
var pending=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),task(business,Map.of(),true),actor)).get("task"));
|
||||
tx.executeWithoutResult(s->service.finish(a.attemptId(),"NEEDS_CLARIFICATION",answer(),Map.of("agentTask",pending),actor));
|
||||
for(String question:List.of("谢谢","你好")) {
|
||||
String turn=newTurn(question);var b=claim(turn,false);assertEquals(pending,b.input().get("previousTask"));
|
||||
var confirmed=AnalysisProtocolService.map(tx.execute(s->service.confirm(b.attemptId(),ordinaryTask(turn),actor)).get("task"));
|
||||
tx.executeWithoutResult(s->service.finish(b.attemptId(),"COMPLETED",Map.of(),Map.of("agentTask",confirmed),actor));
|
||||
jdbc.update("UPDATE analysis_turn SET status='QUEUED' WHERE id=?",turn);
|
||||
var retried=claim(turn,true);var again=AnalysisProtocolService.map(tx.execute(s->service.confirm(retried.attemptId(),confirmed,actor)).get("task"));
|
||||
tx.executeWithoutResult(s->service.finish(retried.attemptId(),"COMPLETED",Map.of(),Map.of("agentTask",again),actor));
|
||||
}
|
||||
var next=claim(newTurn("选+T"),false);assertEquals(pending,next.input().get("previousTask"));
|
||||
}
|
||||
@Test void conversationDoesNotReviveACancelledBusinessGoal() {
|
||||
enableAutonomous();String business=newTurn("取消这个分析目标");var a=claim(business,false);
|
||||
tx.execute(s->service.confirm(a.attemptId(),task(business,Map.of("product","18X15X4+T"),false),actor));
|
||||
tx.executeWithoutResult(s->service.cancel(business,actor,"用户取消"));
|
||||
String greeting=newTurn("你好");var b=claim(greeting,false);assertEquals(Map.of(),b.input().get("previousTask"));
|
||||
var confirmed=AnalysisProtocolService.map(tx.execute(s->service.confirm(b.attemptId(),ordinaryTask(greeting),actor)).get("task"));
|
||||
tx.executeWithoutResult(s->service.finish(b.attemptId(),"COMPLETED",Map.of(),Map.of("agentTask",confirmed),actor));
|
||||
assertEquals(Map.of(),claim(newTurn("重新开始"),false).input().get("previousTask"));
|
||||
}
|
||||
private Map<String,Object> ordinaryTask(String turn) {
|
||||
var result=task(turn,Map.of(),false);result.put("kind","explain");result.put("goal","回应普通对话");result.put("period",null);result.put("fields",List.of());
|
||||
for(String key:List.of("freshQuery","comparisonRequired","trendRequired","verifySource","fullDetails","needsClarification"))result.put(key,false);
|
||||
result.put("visualPreference","none");result.put("historyMode","none");
|
||||
result.put("directResponse",Map.of("purpose","greeting","answer","你好,可以继续提问。","requiresMemory",false));return result;
|
||||
}
|
||||
@Test void autonomousReadBudgetAndFinishRequireRealRootEvidence() {
|
||||
enableAutonomous();String turn=newTurn("检查根任务证据");var a=claim(turn,false);var confirmed=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),nativeTask(turn,Map.of()),actor)).get("task"));
|
||||
var registered=step(a,"read",Map.of("kind","base"),List.of());var scope=AnalysisProtocolService.map(registered.get("scope"));var p=scopeParams(scope);var proofs=new ArrayList<Map<String,Object>>();
|
||||
@@ -1164,7 +1253,7 @@ class AnalysisProtocolServiceMySqlTest {
|
||||
assertThrows(RuntimeException.class,()->tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",answer(),details,actor)));
|
||||
details.put("conclusionProtocolQueryIds",citeFailed?List.of(rootProof.get("queryId"),failedProof.get("queryId")):List.of(rootProof.get("queryId")));
|
||||
tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",answer(),details,actor));assertEquals(citeFailed?"PARTIAL":"COMPLETED",turnStatus(turn));
|
||||
var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);assertEquals(details.get("conclusionProtocolQueryIds"),saved.get("conclusionProtocolQueryIds"));assertFalse(AnalysisProtocolService.list(saved.get("explorationWarnings")).isEmpty());assertEquals(citeFailed,saved.get("answer").toString().contains("18X15X4+T"));assertFalse(saved.containsKey("readingSummary"));assertEquals(!citeFailed,AnalysisProtocolService.map(saved.get("factCoverage")).get("complete"));
|
||||
var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);assertEquals(details.get("conclusionProtocolQueryIds"),saved.get("conclusionProtocolQueryIds"));assertFalse(AnalysisProtocolService.list(saved.get("explorationWarnings")).isEmpty());assertEquals(answer().get("answer"),saved.get("answer"));assertEquals(citeFailed,AnalysisProtocolService.list(AnalysisProtocolService.map(saved.get("answerQuality")).get("missingEvidence")).stream().anyMatch(gap->gap.toString().contains("18X15X4+T")));assertFalse(saved.containsKey("readingSummary"));assertEquals(!citeFailed,AnalysisProtocolService.map(saved.get("factCoverage")).get("complete"));
|
||||
if(!citeFailed) {
|
||||
assertEquals(List.of(rootProof.get("queryId")),saved.get("protocolQueryIds"));assertEquals(2,jdbc.queryForObject("SELECT COUNT(*) FROM analysis_protocol_query",Integer.class));
|
||||
String report=newTurn("汇总刚完成的质量解释");var reportAttempt=claim(report,false);var reportTask=historyTask(reportAttempt,report,"all");var imported=tx.execute(s->service.history(reportAttempt.attemptId(),actor));assertEquals(true,AnalysisProtocolService.map(imported.get("historyCoverage")).get("complete"),imported.toString());
|
||||
@@ -1221,11 +1310,12 @@ class AnalysisProtocolServiceMySqlTest {
|
||||
var result=answer();String fullAnswer="已核实的业务解释。\n\n## 完整附录\n自动图表未生成,详细范围保留在此。";result.put("answer",fullAnswer);result.put("reportMarkdown",fullAnswer);result.put("visualState",preference.equals("required")?"ready":"failed");result.put("visuals",List.of());
|
||||
if(preference.equals("required"))result.put("visuals",List.of(Map.of("metric","composite_rate","type","bar","period",Map.of("year",2026),"scope",Map.of("releaseId",release))));
|
||||
if(withSummary)result.put("readingSummary",Map.of("version",1,"lead","业务概括","evidence",List.of("核心业务依据"),"notices",List.of("Python已归并的业务局限"),"evidenceRefs",List.of()));tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",result,Map.of("agentTask",task,"protocolEvidence",List.of(rootProof,rankProof),"conclusionProtocolQueryIds",List.of(rootProof.get("queryId"),rankProof.get("queryId")),"evidenceCompletion",Map.of("serverCoverageSufficient",true)),actor));assertEquals("PARTIAL",turnStatus(turn));var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);assertEquals(true,AnalysisProtocolService.map(saved.get("factCoverage")).get("complete"));assertFalse(AnalysisProtocolService.list(saved.get("explorationWarnings")).isEmpty());assertEquals(fullAnswer,saved.get("reportMarkdown"));
|
||||
if(withSummary) {
|
||||
var notices=AnalysisProtocolService.list(AnalysisProtocolService.map(saved.get("readingSummary")).get("notices"));assertTrue(notices.contains("Python已归并的业务局限"));
|
||||
if(preference.equals("auto")){assertTrue(notices.contains("Python已归并的业务局限"));assertTrue(notices.stream().anyMatch(notice->notice.toString().contains("图表尚未完整生成")));assertTrue(saved.get("answer").toString().contains("图表尚未完整生成"));}
|
||||
else {assertTrue(notices.contains("用户要求的图表尚未完整生成"));assertTrue(saved.get("answer").toString().contains("用户要求的图表尚未完整生成"));assertTrue(notices.stream().noneMatch(n->n.toString().contains("可独立恢复图表")));}
|
||||
} else {assertFalse(saved.containsKey("readingSummary"));if(preference.equals("auto"))assertTrue(saved.get("answer").toString().contains("图表尚未完整生成"));}
|
||||
assertEquals(fullAnswer,saved.get("answer"));
|
||||
var gaps=AnalysisProtocolService.list(AnalysisProtocolService.map(saved.get("answerQuality")).get("missingEvidence"));
|
||||
assertTrue(gaps.stream().anyMatch(gap->gap.toString().contains("图表尚未完整生成")));
|
||||
if(preference.equals("required"))assertTrue(gaps.contains("用户要求的图表尚未完整生成"));
|
||||
if(withSummary)assertEquals(result.get("readingSummary"),saved.get("readingSummary"));
|
||||
else assertFalse(saved.containsKey("readingSummary"));
|
||||
}
|
||||
}
|
||||
@Test void nativeRecordsAppendixRetainsLegalPagesAtReadCapWithoutAcceptingIncompleteScope() {
|
||||
@@ -1236,7 +1326,7 @@ class AnalysisProtocolServiceMySqlTest {
|
||||
var result=answer();result.put("recordList",Map.of("queryComplete",true,"rows",List.of("invented")));
|
||||
tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",result,Map.of("agentTask",task,"protocolEvidence",proofs,"conclusionProtocolQueryIds",List.of(),"evidenceCompletion",Map.of("serverCoverageSufficient",false)),actor));assertEquals("PARTIAL",turnStatus(turn));var saved=json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class);var listing=AnalysisProtocolService.map(saved.get("recordList"));
|
||||
assertEquals(false,listing.get("queryComplete"));assertEquals(4001,listing.get("totalRows"));assertEquals(4000,listing.get("loadedRows"));var set=AnalysisProtocolService.map(AnalysisProtocolService.list(listing.get("sets")).getFirst());assertEquals(false,set.get("complete"));assertEquals("001",AnalysisProtocolService.map(AnalysisProtocolService.map(AnalysisProtocolService.list(set.get("rows")).getFirst()).get("values")).get("委托单"));assertEquals("4000",AnalysisProtocolService.map(AnalysisProtocolService.map(AnalysisProtocolService.list(set.get("rows")).getLast()).get("values")).get("委托单"));
|
||||
assertEquals(List.of(),saved.get("protocolQueryIds"));assertEquals(List.of(),saved.get("conclusionProtocolQueryIds"));assertEquals(40,AnalysisProtocolService.list(saved.get("attemptProtocolQueryIds")).size());assertEquals(false,AnalysisProtocolService.map(AnalysisProtocolService.list(saved.get("scopeCoverage")).getFirst()).get("complete"));assertTrue(saved.get("answer").toString().contains("尚未查全"));
|
||||
assertEquals(List.of(),saved.get("protocolQueryIds"));assertEquals(List.of(),saved.get("conclusionProtocolQueryIds"));assertEquals(40,AnalysisProtocolService.list(saved.get("attemptProtocolQueryIds")).size());assertEquals(false,AnalysisProtocolService.map(AnalysisProtocolService.list(saved.get("scopeCoverage")).getFirst()).get("complete"));assertEquals(result.get("answer"),saved.get("answer"));assertFalse(AnalysisProtocolService.list(AnalysisProtocolService.map(saved.get("answerQuality")).get("missingEvidence")).isEmpty());
|
||||
}
|
||||
@Test void explicitRawRootCannotCompleteByIgnoringAnUnreadRawScope() {
|
||||
enableAutonomous();String turn=newTurn("逐条读取全部黑片记录");var a=claim(turn,false);var proposal=rawTask(turn,"records");var rawNode=AnalysisProtocolService.map(AnalysisProtocolService.list(proposal.remove("queryPlan")).getFirst());proposal.put("executionMode","native_agent");var task=AnalysisProtocolService.map(tx.execute(s->service.confirm(a.attemptId(),proposal,actor)).get("task"));tx.execute(s->service.explorationStep(a.attemptId(),Map.of("requestKey","raw","node",rawNode),actor));
|
||||
@@ -1273,7 +1363,7 @@ class AnalysisProtocolServiceMySqlTest {
|
||||
var result=answer();result.put("readingSummary",Map.of("version",1,"lead","已核实总体率","notices",List.of("已有提示")));
|
||||
tx.executeWithoutResult(s->service.finish(a.attemptId(),"COMPLETED",result,Map.of("agentTask",confirmed,"protocolEvidence",proofs,"factsComplete",true,"evidenceCompletion",Map.of("serverCoverageSufficient",true)),actor));
|
||||
assertEquals("PARTIAL",turnStatus(turn));var saved=AnalysisProtocolService.map(json.readValue(jdbc.queryForObject("SELECT answer_json FROM analysis_turn WHERE id=?",String.class,turn),Map.class));
|
||||
var notices=AnalysisProtocolService.list(AnalysisProtocolService.map(saved.get("readingSummary")).get("notices"));assertTrue(notices.contains("已有提示"));assertTrue(notices.containsAll(gaps));assertTrue(saved.get("answer").toString().contains("尚未解决:"));assertTrue(saved.get("answer").toString().contains("18X15X4+T"));
|
||||
var notices=AnalysisProtocolService.list(AnalysisProtocolService.map(saved.get("answerQuality")).get("missingEvidence"));assertTrue(notices.containsAll(gaps));assertEquals(result.get("answer"),saved.get("answer"));assertFalse(saved.get("answer").toString().contains("尚未解决:"));
|
||||
}
|
||||
}
|
||||
@Test void rejectedRegistrationDoesNotPolluteLaterSuccessfulScopeCoverage() {
|
||||
|
||||
@@ -37,6 +37,19 @@ class AnalysisTurnSnapshotTest {
|
||||
private static final String SESSION_ID = "66b51f0e-0252-4ef1-9aeb-58bd262293db";
|
||||
private static final String QUERY_FILTERS = "SELECT field_key,black_column,bright_column FROM query_filter_field WHERE enabled=TRUE";
|
||||
|
||||
@Test void originalBodyQualityMetadataSurvivesSavedSnapshotWithoutClaimingFactVerification() {
|
||||
Harness harness=new Harness("valid");
|
||||
var quality=Map.<String,Object>of("version",1,"dataComplete",true,"narrativeComplete",true,"chartsComplete",false,
|
||||
"narrativeFactBinding","not_assessed","citedEvidenceRefs",List.of("Q1234ABCD","Q00000000","bad"),
|
||||
"unresolvedEvidenceRefs",List.of("QDEADBEEF","bad"),"notices",List.of("图表尚未齐全"),"missingEvidence",List.of("未知引用"));
|
||||
var details=Map.<String,Object>of("answerQuality",quality,"queryEvidenceRefs",List.of("Q1234ABCD"));
|
||||
var answer=harness.service.nativeAnswer(details,"完整AI正文",Map.of(),"release-1","PARTIAL","evidence_incomplete",TURN_ID,null);
|
||||
var savedQuality=AnalysisProtocolService.map(answer.get("answerQuality"));
|
||||
assertEquals("not_assessed",savedQuality.get("narrativeFactBinding"));assertEquals(false,savedQuality.get("citationComplete"));
|
||||
assertEquals(List.of("Q1234ABCD"),savedQuality.get("citedEvidenceRefs"));assertEquals(List.of("QDEADBEEF"),savedQuality.get("unresolvedEvidenceRefs"));
|
||||
harness.storedOverride=answer;var snapshot=harness.service.getSnapshot(TURN_ID,harness.submittedActor);
|
||||
assertEquals(savedQuality,snapshot.get("answerQuality"));assertEquals("完整AI正文",snapshot.get("answer"));
|
||||
}
|
||||
@Test
|
||||
void snapshotReadUsesFreshAuthorizationAndDoesNotRequeryBusinessMetrics() {
|
||||
Harness harness = new Harness("valid");
|
||||
|
||||
@@ -6,6 +6,22 @@ import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class NaoAnalysisRunnerResultTest {
|
||||
@Test void aStopReasonCannotOverrideConflictingFinishOrPendingTools() {
|
||||
for(var conflict:java.util.List.of(Map.<String,Object>of("finishReason","tool-calls"),
|
||||
Map.<String,Object>of("nativeStopSucceeded",false),
|
||||
Map.<String,Object>of("toolCalls",java.util.List.of(Map.of("tool","mcp_call","status","started"))),
|
||||
Map.<String,Object>of("answerQuality",Map.of("narrativeComplete",false)))) {
|
||||
var message=new java.util.LinkedHashMap<String,Object>();message.put("type","result");message.put("status","COMPLETED");message.put("stopReason","stop");message.put("answer","正在查询。");message.putAll(conflict);
|
||||
assertEquals("PARTIAL",NaoAnalysisRunner.Result.from(message,"",false).status());
|
||||
}
|
||||
}
|
||||
@Test void anEmptyStopResultCannotCompleteUnlessItHasAVisibleStructuredBody() {
|
||||
var empty=NaoAnalysisRunner.Result.from(Map.of("type","result","status","COMPLETED","answer","", "stopReason","stop"),"",false);
|
||||
assertEquals("PARTIAL",empty.status());assertEquals("answer_missing",empty.stopReason());
|
||||
assertEquals(false,AnalysisProtocolService.map(empty.details().get("answerQuality")).get("narrativeComplete"));
|
||||
var report=NaoAnalysisRunner.Result.from(Map.of("type","result","status","COMPLETED","answer","", "stopReason","stop","reportMarkdown","已生成的报告"),"",false);
|
||||
assertEquals("COMPLETED",report.status());
|
||||
}
|
||||
@Test
|
||||
void onlyNativeStopFinishReasonCanComplete() {
|
||||
NaoAnalysisRunner.Result completed = NaoAnalysisRunner.Result.from(Map.of(
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package cn.yunsheng.quality.analysis;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
class NativeOriginalCoverageTest {
|
||||
@Test void nativeCoverageKeepsModelProseByteForByteAndStoresGapsSeparately() {
|
||||
String original="## 结论\n\n原始模型正文。\n\n| 变化 |\n| --- |\n| -0.30 pp |";
|
||||
var answer=new LinkedHashMap<String,Object>();answer.put("answer",original);
|
||||
answer.put("answerQuality",Map.of("version",1,"dataComplete",true,"missingEvidence",List.of("已有缺口")));
|
||||
AnalysisProtocolService.appendNativeCoverageDiagnostics(answer,List.of("图表未齐","图表未齐", ""));
|
||||
assertEquals(original,answer.get("answer"));
|
||||
var quality=AnalysisProtocolService.map(answer.get("answerQuality"));
|
||||
assertEquals(true,quality.get("dataComplete"));assertEquals(List.of("已有缺口","图表未齐"),quality.get("missingEvidence"));
|
||||
assertFalse(answer.containsKey("readingSummary"));
|
||||
}
|
||||
@Test void noGapsDoNotCreateOrRewriteNarrativeMetadata() {
|
||||
var answer=new LinkedHashMap<String,Object>();answer.put("answer","原文");
|
||||
AnalysisProtocolService.appendNativeCoverageDiagnostics(answer,List.of());
|
||||
assertEquals(Map.of("answer","原文"),answer);
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,9 @@ class WorkspaceStateControllerTest {
|
||||
when(jdbc.queryForList(contains("user_access_policy"), any(Object[].class))).thenReturn(List.of(Map.of("allowed_fields","private-field")));
|
||||
var first = controller.state(actor(List.of("A","B")));
|
||||
assertEquals(first, controller.state(actor(List.of("B","A"))));
|
||||
assertTrue(first.values().stream().allMatch(value -> value.matches("[a-f0-9]{64}")));
|
||||
assertTrue(first.get("authRevision").matches("[a-f0-9]{64}"));
|
||||
assertTrue(first.get("dataRevision").matches("[a-f0-9]{64}"));
|
||||
assertNull(first.get("currentReleaseId"));
|
||||
assertFalse(first.toString().contains("private-field"));
|
||||
verify(access,times(2)).requireUserActivePolicy(any());
|
||||
}
|
||||
@@ -41,4 +43,17 @@ class WorkspaceStateControllerTest {
|
||||
assertThrows(IllegalStateException.class,()->controller.state(actor));
|
||||
verifyNoInteractions(jdbc);
|
||||
}
|
||||
|
||||
@Test void currentReleaseIdMatchesTheReleaseSnapshotIncludedInDataRevision() {
|
||||
String query = "SELECT * FROM current_release ORDER BY dataset_id";
|
||||
when(jdbc.queryForList(query)).thenReturn(List.of(Map.of("dataset_id", "quality", "release_id", "release-a")))
|
||||
.thenReturn(List.of(Map.of("dataset_id", "quality", "release_id", "release-b")));
|
||||
var first = controller.state(actor(List.of("A")));
|
||||
var second = controller.state(actor(List.of("A")));
|
||||
assertEquals("release-a", first.get("currentReleaseId"));
|
||||
assertEquals("release-b", second.get("currentReleaseId"));
|
||||
assertNotEquals(first.get("dataRevision"), second.get("dataRevision"));
|
||||
verify(jdbc, times(2)).queryForList(query);
|
||||
verify(access, times(2)).requireUserActivePolicy(any());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,4 +66,22 @@ class MetricsResponseAccessTest {
|
||||
when(governance.allowedFields(actor)).thenReturn(Set.of("*"));
|
||||
assertSame(source, new MetricsResponseAccess(governance).visible(source, actor));
|
||||
}
|
||||
|
||||
@Test void lightweightTrendStillHonorsDetailAndMetricFieldPermissions() {
|
||||
var trend = new MetricTrendSnapshot(Map.of("id", "release-a"), Map.of("view", "product"),
|
||||
source.trend(), Map.of("rawRows", 10));
|
||||
when(governance.policy(actor.getId().toString())).thenReturn(Map.of("detailAllowed", true));
|
||||
when(governance.allowedFields(actor)).thenReturn(Set.of("black_total_weight"));
|
||||
MetricTrendSnapshot visible = new MetricsResponseAccess(governance).visibleTrend(trend, actor);
|
||||
assertEquals(1, visible.trend().size());
|
||||
assertNull(visible.trend().getFirst().black().qualifiedWeight());
|
||||
assertNull(visible.trend().getFirst().black().scrapWeight());
|
||||
assertEquals(stage.totalWeight(), visible.trend().getFirst().black().totalWeight());
|
||||
|
||||
clearInvocations(governance);
|
||||
when(governance.policy(actor.getId().toString())).thenReturn(Map.of("detailAllowed", false));
|
||||
MetricTrendSnapshot aggregateOnly = new MetricsResponseAccess(governance).visibleTrend(trend, actor);
|
||||
assertTrue(aggregateOnly.trend().isEmpty());
|
||||
verify(governance, never()).requireBoundAction("QUERY", "query.detail");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package cn.yunsheng.quality.metrics;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import cn.yunsheng.quality.identity.AppUserPrincipal;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
class MetricsTrendControllerTest {
|
||||
@Test void trendRouteCarriesEveryPeriodFilterStageExclusionAndSourceFilterIntoMetrics() {
|
||||
MetricsService metrics = mock(MetricsService.class);
|
||||
MetricsResponseAccess access = mock(MetricsResponseAccess.class);
|
||||
AppUserPrincipal actor = new AppUserPrincipal(UUID.randomUUID(), "trend", "unused", "趋势", true, false,
|
||||
List.of("QUALITY_VIEWER"), List.of("D"), List.of("G"), List.of());
|
||||
MetricsService.MetricTrendSnapshot response = new MetricsService.MetricTrendSnapshot(
|
||||
Map.of(), Map.of(), List.of(), Map.of());
|
||||
when(metrics.calculateTrend(any(), eq(actor))).thenReturn(response);
|
||||
when(access.visibleTrend(response, actor)).thenReturn(response);
|
||||
|
||||
MetricsService.MetricTrendSnapshot actual = new MetricsController(metrics, access).trendHttp(
|
||||
2026, null, 3, 9, null, "D", "G", "P", "18X15", "PG", "product", false,
|
||||
"release-a", "quarter", "{\"customerCode\":[\"000123\"]}",
|
||||
"{\"product\":[\"P2\"]}",
|
||||
"[{\"field\":\"src_any\",\"stages\":[\"black\"],\"operator\":\"in\",\"values\":[\"000123\"]}]",
|
||||
"black", actor);
|
||||
|
||||
assertEquals(response, actual);
|
||||
ArgumentCaptor<MetricsService.MetricsQuery> query = ArgumentCaptor.forClass(MetricsService.MetricsQuery.class);
|
||||
verify(metrics).calculateTrend(query.capture(), eq(actor));
|
||||
MetricsService.MetricsQuery value = query.getValue();
|
||||
assertEquals(2026, value.year());
|
||||
assertEquals(3, value.monthStart());
|
||||
assertEquals(9, value.monthEnd());
|
||||
assertEquals("D", value.department());
|
||||
assertEquals("G", value.group());
|
||||
assertEquals("P", value.product());
|
||||
assertEquals("18X15", value.productSearch());
|
||||
assertEquals("PG", value.projectGroup());
|
||||
assertEquals("product", value.view());
|
||||
assertEquals("quarter", value.trendGranularity());
|
||||
assertEquals("black", value.stage());
|
||||
assertEquals(Map.of("product", List.of("P2")), value.exclusions());
|
||||
assertEquals(Map.of("customerCode", List.of("000123")), value.extraFilters());
|
||||
assertEquals("src_any", value.columnFilters().getFirst().get("field"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package cn.yunsheng.quality.metrics;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import cn.yunsheng.quality.governance.GovernanceAccessService;
|
||||
import cn.yunsheng.quality.identity.AppUserPrincipal;
|
||||
import cn.yunsheng.quality.ingestion.BusinessRowMapper;
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.RowCallbackHandler;
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
|
||||
class MetricsTrendServiceTest {
|
||||
private static final String RELEASE = "release-trend";
|
||||
private final AppUserPrincipal actor = new AppUserPrincipal(UUID.randomUUID(), "trend-reader", "unused", "趋势读者",
|
||||
true, false, List.of("SYSTEM_ADMIN"), List.of("*"), List.of("*"), List.of());
|
||||
|
||||
@Test void directTrendMatchesFullMetricsTrendWithoutBuildingProductGroups() {
|
||||
JdbcTemplate jdbc = jdbc(true, true);
|
||||
MetricsService service = new MetricsService(jdbc, mock(GovernanceAccessService.class));
|
||||
var query = new MetricsService.MetricsQuery(2026, null, null, null, null, null, null,
|
||||
"product", true, RELEASE, "month", Map.of());
|
||||
|
||||
MetricsService.MetricSnapshot full = service.calculate(query, actor);
|
||||
MetricsService.MetricTrendSnapshot trend = service.calculateTrend(query, actor);
|
||||
|
||||
assertEquals(full.trend(), trend.trend());
|
||||
assertEquals(full.coverage(), trend.coverage());
|
||||
assertEquals("release-trend", trend.release().get("id"));
|
||||
assertNull(trend.trend().getFirst().product());
|
||||
assertNull(trend.trend().getFirst().group());
|
||||
assertEquals(List.of("release", "context", "trend", "coverage"),
|
||||
Arrays.stream(MetricsService.MetricTrendSnapshot.class.getRecordComponents())
|
||||
.map(java.lang.reflect.RecordComponent::getName).toList());
|
||||
|
||||
List<String> trendSql = capturedSql(jdbc).stream()
|
||||
.filter(sql -> sql.contains("GROUP BY trend_period") && !sql.contains("GROUP BY trend_period,"))
|
||||
.toList();
|
||||
assertFalse(trendSql.isEmpty());
|
||||
assertTrue(trendSql.stream().allMatch(sql -> !sql.contains("bucket_key") && !sql.contains("f.product")));
|
||||
}
|
||||
|
||||
@Test void rangeStageAndFiltersReachOnlyTheRequestedTrendAndCoverageQueries() {
|
||||
JdbcTemplate jdbc = jdbc(true, true);
|
||||
MetricsService service = new MetricsService(jdbc, mock(GovernanceAccessService.class));
|
||||
var query = new MetricsService.MetricsQuery(2026, null, null, null, null, null, null,
|
||||
"product", true, RELEASE, "month", Map.of("product", List.of("excluded-product")))
|
||||
.withMonthRange(3, 5).withProductSearch("18X15").withStage("black");
|
||||
|
||||
MetricsService.MetricTrendSnapshot result = service.calculateTrend(query, actor);
|
||||
|
||||
assertEquals("black", result.context().get("stage"));
|
||||
assertEquals(3, result.context().get("monthStart"));
|
||||
assertEquals(5, result.context().get("monthEnd"));
|
||||
List<String> sql = capturedSql(jdbc);
|
||||
List<String> trendSql = sql.stream().filter(value -> value.contains("GROUP BY trend_period")).toList();
|
||||
assertEquals(1, trendSql.size());
|
||||
assertTrue(trendSql.getFirst().contains("f.month_key BETWEEN ? AND ?"));
|
||||
assertTrue(trendSql.getFirst().contains("LOCATE(LOWER(?), LOWER(COALESCE(f.product,''))) > 0"));
|
||||
assertTrue(trendSql.getFirst().contains("f.product COLLATE utf8mb4_0900_as_cs"));
|
||||
assertTrue(trendSql.getFirst().contains("f.stage=?"));
|
||||
assertFalse(trendSql.getFirst().contains("JOIN fact_bright"));
|
||||
}
|
||||
|
||||
@Test void emptyPeriodReturnsAnEmptyTrendAndZeroCoverage() {
|
||||
JdbcTemplate jdbc = jdbc(false, false);
|
||||
MetricsService service = new MetricsService(jdbc, mock(GovernanceAccessService.class));
|
||||
var query = new MetricsService.MetricsQuery(2026, 3, null, null, null, null, null,
|
||||
"overall", true, RELEASE, "month", Map.of());
|
||||
|
||||
MetricsService.MetricTrendSnapshot result = service.calculateTrend(query, actor);
|
||||
|
||||
assertTrue(result.trend().isEmpty());
|
||||
assertEquals(0L, result.coverage().get("rawRows"));
|
||||
assertEquals(0L, result.coverage().get("includedRows"));
|
||||
}
|
||||
|
||||
private static JdbcTemplate jdbc(boolean emitAggregates, boolean emitCoverage) {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForObject(contains("metric_rollup_build"), eq(Integer.class), any(Object[].class))).thenReturn(0);
|
||||
when(jdbc.queryForObject("SELECT rule_version FROM data_release WHERE id=?", String.class, RELEASE))
|
||||
.thenReturn(BusinessRowMapper.RULE_VERSION);
|
||||
when(jdbc.query(eq("SELECT id,name,status FROM data_release WHERE id=?"), any(RowMapper.class), eq(RELEASE)))
|
||||
.thenAnswer(invocation -> {
|
||||
RowMapper<?> mapper = invocation.getArgument(1);
|
||||
ResultSet row = mock(ResultSet.class);
|
||||
when(row.getString(1)).thenReturn(RELEASE);
|
||||
when(row.getString(2)).thenReturn("Trend fixture");
|
||||
when(row.getString(3)).thenReturn("PUBLISHED");
|
||||
return List.of(mapper.mapRow(row, 0));
|
||||
});
|
||||
doAnswer(invocation -> {
|
||||
String sql = invocation.getArgument(0);
|
||||
RowCallbackHandler callback = invocation.getArgument(1);
|
||||
Object[] invocationArgs = invocation.getArguments();
|
||||
Object[] args = Arrays.copyOfRange(invocationArgs, 2, invocationArgs.length);
|
||||
if (sql.contains("SELECT f.month_key,")) {
|
||||
if (emitCoverage) emitCoverageRow(callback, sql, args);
|
||||
} else if (emitAggregates) {
|
||||
emitAggregateRows(callback, sql, args);
|
||||
}
|
||||
return null;
|
||||
}).when(jdbc).query(anyString(), any(RowCallbackHandler.class), any(Object[].class));
|
||||
return jdbc;
|
||||
}
|
||||
|
||||
private static void emitCoverageRow(RowCallbackHandler callback, String sql, Object[] args) throws Exception {
|
||||
String stage = stage(sql, args);
|
||||
ResultSet row = mock(ResultSet.class);
|
||||
when(row.getString("month_key")).thenReturn("2026-03");
|
||||
when(row.getLong("row_count")).thenReturn(2L);
|
||||
when(row.getLong("excluded_blank_rows")).thenReturn(0L);
|
||||
when(row.getLong("unmapped_rows")).thenReturn(0L);
|
||||
when(row.getLong("project_unconfigured_rows")).thenReturn(0L);
|
||||
callback.processRow(row);
|
||||
}
|
||||
|
||||
private static void emitAggregateRows(RowCallbackHandler callback, String sql, Object[] args) throws Exception {
|
||||
String stage = stage(sql, args);
|
||||
List<Contribution> contributions = stage.equals("black")
|
||||
? List.of(new Contribution("P1", "90", "10", "100", "2"),
|
||||
new Contribution("P2", "40", "10", "50", "1"))
|
||||
: List.of(new Contribution("P1", "8", "2", "10", "1"),
|
||||
new Contribution("P2", "9", "1", "10", "0"));
|
||||
if (!sql.contains("AS bucket_key")) {
|
||||
BigDecimal good = contributions.stream().map(Contribution::good).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
BigDecimal scrap = contributions.stream().map(Contribution::scrap).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
BigDecimal total = contributions.stream().map(Contribution::total).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
BigDecimal component = contributions.stream().map(Contribution::component).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
emitAggregateRow(callback, stage, null, good, scrap, total, component, 2L);
|
||||
} else {
|
||||
for (Contribution contribution : contributions)
|
||||
emitAggregateRow(callback, stage, contribution.key(), contribution.good(), contribution.scrap(),
|
||||
contribution.total(), contribution.component(), 1L);
|
||||
}
|
||||
}
|
||||
|
||||
private static void emitAggregateRow(RowCallbackHandler callback, String stage, String key, BigDecimal good,
|
||||
BigDecimal scrap, BigDecimal total, BigDecimal component, long count)
|
||||
throws Exception {
|
||||
ResultSet row = mock(ResultSet.class);
|
||||
when(row.getString("trend_period")).thenReturn("2026-03");
|
||||
if (key != null) when(row.getString("bucket_key")).thenReturn(key);
|
||||
when(row.getLong("row_count")).thenReturn(count);
|
||||
when(row.getBigDecimal("qualified_weight")).thenReturn(good);
|
||||
when(row.getBigDecimal("scrap_weight")).thenReturn(scrap);
|
||||
when(row.getBigDecimal("total_weight")).thenReturn(total);
|
||||
for (String column : List.of("black_responsibility_scrap", "black_material_scrap", "black_external_scrap",
|
||||
"bright_headquarters_scrap", "bright_plating_scrap", "bright_material_scrap",
|
||||
"bright_processing_scrap", "bright_diffusion_scrap"))
|
||||
when(row.getBigDecimal(column)).thenReturn(BigDecimal.ZERO);
|
||||
when(row.getBigDecimal(stage.equals("black") ? "black_responsibility_scrap" : "bright_plating_scrap"))
|
||||
.thenReturn(component);
|
||||
callback.processRow(row);
|
||||
}
|
||||
|
||||
private static String stage(String sql, Object[] args) {
|
||||
if (sql.contains("JOIN fact_black f")) return "black";
|
||||
if (sql.contains("JOIN fact_bright f")) return "bright";
|
||||
for (Object value : args) if ("black".equals(value) || "bright".equals(value)) return String.valueOf(value);
|
||||
return "black";
|
||||
}
|
||||
|
||||
private static List<String> capturedSql(JdbcTemplate jdbc) {
|
||||
var details = mockingDetails(jdbc).getInvocations();
|
||||
List<String> result = new ArrayList<>();
|
||||
for (var invocation : details) {
|
||||
if (invocation.getMethod().getName().equals("query") && invocation.getArguments().length > 0
|
||||
&& invocation.getArguments()[0] instanceof String sql) result.add(sql);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private record Contribution(String key, String goodText, String scrapText, String totalText, String componentText) {
|
||||
BigDecimal good() { return new BigDecimal(goodText); }
|
||||
BigDecimal scrap() { return new BigDecimal(scrapText); }
|
||||
BigDecimal total() { return new BigDecimal(totalText); }
|
||||
BigDecimal component() { return new BigDecimal(componentText); }
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,12 @@ server {
|
||||
proxy_cookie_flags XSRF-TOKEN secure samesite=strict;
|
||||
}
|
||||
|
||||
# 静态文本压缩只在站点根目录启用;API 的 SSE 代理缓冲仍保持关闭。
|
||||
location / {
|
||||
gzip on;
|
||||
gzip_min_length 1024;
|
||||
gzip_vary on;
|
||||
gzip_types text/plain text/css application/javascript application/json image/svg+xml application/xml;
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# AI 智能分析当前要求与排查修复基准
|
||||
|
||||
适用项目:质量数据分析平台。更新日期:2026-10-31。
|
||||
适用项目:质量数据分析平台。更新日期:2026-11-02。
|
||||
|
||||
本文只列当前有效要求与对应验收标准,供智能分析排查、修复和交付时使用。
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
- AI 负责理解自然语言、选择查询、分析和表达;正式指标由现有业务服务、已发布规则和映射计算。
|
||||
- 保留可靠的数据底座、正式口径、权限和数据快照约束。系统规则、模型行为、结果校验及页面展示必须一致。
|
||||
- 用户最终看到清晰的结论、重点表格和重点图表,分析过程与最终结果对题、可信、可读。
|
||||
- 模型识别的一般问候、能力介绍和致谢直接保留其回复原文,不要求数据期间,不触发正式查询或二次生成;仍核验会话权限及取消状态。该路径不能输出未查询业务数值、趋势因果或声称已执行的操作,也不能代替记忆、报告或数据分析。后续业务目标与筛选保持原有效计划,普通对话不充当报告事实来源。
|
||||
|
||||
## 2. 默认业务口径
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# 全系统统一加载实现与验收
|
||||
|
||||
## 范围与约束
|
||||
|
||||
六类查询、来源明细、数据接入、规则、对应关系、基础数据、权限审计、任务监控、智能分析和导出共用现有 api.ts 的请求协调层。保留现有布局、主题、计算公式和来源数据;保留完整下载及前端分页、全范围搜索排序、Excel 全量导出。
|
||||
|
||||
## 实现契约
|
||||
|
||||
- GET 同键合并、最多 4 个在途读取;订阅者独立取消,最后一个退出才取消底层请求。身份、授权和版本变化中止旧读取,旧响应不得提交或导出。
|
||||
- 会话内存 LRU 上限 32 MiB;按用户、权限、数据发布及规范化参数隔离,不持久化业务结果。工作区校验合并,按资源失效,隐藏页面和未选管理页签不主动刷新。
|
||||
- 工作区授权变化立即撤下旧结果;工作区本身 403 同样阻断,恢复后重新核实身份并重建页面。单资源 403 仅触发重验,避免重复预读循环。
|
||||
- 普通读取 30 秒、身份/连接校验 8 秒,预算覆盖正文读取;只读网络失败和 502/503/504 最多延迟 1 秒重试一次。写入、上传、任务提交不自动重发。文件传输 900 秒;模型事件流不套普通查询超时。
|
||||
- 首次加载保留框架,150 毫秒后才显示忙碌;更新保留成功结果并标注其期间。首次错误有重试,更新错误保留旧结果并阻断旧范围的明细、钻取和导出;只有成功的空结果显示空态。
|
||||
- 页面返回保留筛选、页码及滚动位置;表格按查询条件识别分页范围,缓存读取的新对象不重置分页。隐藏时保留表格已知高度,避免返回时滚动被临时零高度夹紧。
|
||||
- 轮询按上次请求完成后排下一轮:任务 15 秒、活动操作 2 秒、分析会话 5 秒;隐藏暂停、返回立即核对。已知任务编号继续恢复,未保存输入保留。
|
||||
- 保留 280 毫秒页面淡化、520 毫秒数值/图表过渡及减少动态效果设置;图表接近可见区域才初始化,不良构成按需读取。
|
||||
- GET /api/metrics/trend 直接按期间聚合,返回 release/context/trend/coverage,不计算或返回产品完整表。汇总与趋势绑定同一 release 并行读取;原 /api/metrics 契约保留。
|
||||
- 后端对超过 1 KiB 的 JSON/problem+json 开 gzip;Nginx 仅补静态文本压缩,保留 HTTPS、事件流不缓冲及 900 秒代理时限。Excel、压缩包、SSE 不参与 JSON 压缩。
|
||||
- 诊断仅保存类别、耗时、字节、状态、重试次数;不记录业务正文、凭据及完整查询地址。
|
||||
|
||||
## 验证证据
|
||||
|
||||
隔离当前发布快照,关闭分析及报告后台写入;原接口与轻量趋势 36 组对照通过,覆盖维度、月/季/年、黑片/亮片、期间、产品选择/排除及来源字段。趋势最大解压 JSON 17,286 字节;原产品接口 7,485,818 字节,gzip 后 1,381,397 字节。
|
||||
|
||||
真实 Chrome、1440×900、10 Mbps、100 毫秒延迟、4 倍 CPU 降速、禁用浏览器缓存,每类独立冷加载 20 次。计时从导航开始,到趋势响应正文完成且非忙碌 SVG 的首个绘制帧:
|
||||
|
||||
| 页面 | 次数 | 趋势可见 P95 | 最大原始趋势响应 |
|
||||
|---|---:|---:|---:|
|
||||
| 产品 | 20 | 1,762.8 ms | 17,251 B |
|
||||
| 黑片 | 20 | 1,996.4 ms | 11,856 B |
|
||||
| 亮片 | 20 | 1,899.1 ms | 13,276 B |
|
||||
|
||||
黑片最慢单次为 2,026.4 ms,P95 仍小于 2 秒。该单次从导航到请求开始 1,732.4 ms;请求至正文结束 141.1 ms(其中首字节前 135.5 ms,包含模拟往返与服务端等待,未冒充独立服务端耗时);正文结束到可见帧 152.9 ms。性能数据是隔离快照的实验结果,不承诺所有设备或完整表格首屏都在 2 秒内。
|
||||
|
||||
真实返回验收:亮片第 2 页、scrollY=939.5,切产品再返回后页码与 scrollY 不变;返回期间指标/趋势底层请求数量不增加。六查询视图及桌面/390×844 手机六主题均有图表,无页面横向溢出。首次趋势失败显示错误和重试,汇总表仍可读,重试后恢复。竞态、共享取消、权限变更、首错/更新错、轮询与任务恢复由行为回归覆盖。
|
||||
|
||||
完整记录保存在本机 output/unified-loading-20261102:interface-comparison.json、browser-performance.json、cache-navigation.json、visual-checks.json、query-smoke.json 和截图。
|
||||
|
||||
## 发布与回退
|
||||
|
||||
一次集成发布:验证和冻结源码/产物 → 同步 Gitea → 备份实际运行 JAR、前端真实目标和 Nginx 配置 → 确认无活动任务 → 启动兼容旧前端的新后端 → 合并静态压缩配置并验证 Nginx → 原子切换新前端 → HTTPS/资源哈希/真实页面验收。
|
||||
|
||||
回退使用发布时捕获的实际运行 JAR 路径及 SHA、旧前端目录、原 Nginx 配置,不能依据陈旧 manifest 推断后端。保留旧哈希资源供已打开浏览器继续加载。无需数据库结构迁移,不恢复或重写业务数据。
|
||||
@@ -963,7 +963,7 @@ def _change_chart(document: dict[str, Any], result: dict[str, Any], turn_id: str
|
||||
note = "黑片与亮片两阶段报废重量之和仅作分组描述,不代表独立投入分母或总体变化贡献。"
|
||||
elif order == "rate_drop":
|
||||
title = "合格率变化排名" if stage is None else "分组合格率变化排名"
|
||||
metric, unit, label, field = "rate_drop_pp", "pp", "合格率下降(pp)", "rateDrop"
|
||||
metric, unit, label, field = "rate_drop_pp", "pp", "合格率变化(pp)", "rateDrop"
|
||||
required_fields = (["black_good_weight", "black_total_weight", "bright_good_weight", "bright_total_weight"]
|
||||
if stage is None else [f"{stage}_good_weight", f"{stage}_total_weight"])
|
||||
|
||||
@@ -971,11 +971,14 @@ def _change_chart(document: dict[str, Any], result: dict[str, Any], turn_id: str
|
||||
raw, ok = _finite_number(row.get(field))
|
||||
if not ok:
|
||||
return None, False
|
||||
return (raw * 100 if raw is not None else None), True
|
||||
points = -raw * 100 if raw is not None else None
|
||||
if points is not None and not math.isfinite(points):
|
||||
return None, False
|
||||
return points, True
|
||||
|
||||
note = "正值表示合格率下降,负值表示改善;百分点取自正式分组率差。"
|
||||
note = "正值表示本期合格率上升,负值表示下降;变化值为本期减比较期,排序仍沿用正式率降排名。"
|
||||
if stage is None:
|
||||
note = "正值表示综合合格率下降,负值表示改善;按正式综合率比较,不作为生产根因。"
|
||||
note = "正值表示本期综合合格率上升,负值表示下降;变化值为本期减比较期,排序仍沿用正式率降排名,不代表生产根因。"
|
||||
elif order == 'current_rate':
|
||||
title = '分组本期合格率排名'
|
||||
metric = (stage+'_rate') if stage else 'composite_rate'
|
||||
@@ -1023,7 +1026,7 @@ def _change_chart(document: dict[str, Any], result: dict[str, Any], turn_id: str
|
||||
title = title.replace("分组", "产品")
|
||||
if order == "rate_drop":
|
||||
title = title.replace("合格率变化排名", "合格率降幅线索")
|
||||
note = "条形末端显示具体变化:正值为下降,负值为改善,单位是百分点。本图只按率降幅排序,未纳入投入规模;少量生产或投入骤变的规格不能仅凭此图认定为重点,需结合分阶段投入与报废增量核查。"
|
||||
note = "条形末端显示本期减比较期的变化:负值为下降,正值为上升,单位是百分点。本图仍按率降幅排序,未纳入投入规模;少量生产或投入骤变的规格不能仅凭此图认定为重点,需结合分阶段投入与报废增量核查。"
|
||||
elif result["dimension"] == "group":
|
||||
title = title.replace("分组", "业务分组")
|
||||
else:
|
||||
|
||||
@@ -62,20 +62,29 @@ def capability_context(task=None):
|
||||
}
|
||||
|
||||
|
||||
def apply_platform_tools(payload):
|
||||
"""Do not advertise a native SQL-result renderer for quality API evidence."""
|
||||
QUALITY_NATIVE_TOOLS = frozenset({'read', 'list', 'grep', 'search', 'mcp_call', 'mcp_connect'})
|
||||
|
||||
|
||||
def apply_platform_tools(payload, *, native_agent=False):
|
||||
"""Expose tools compatible with platform evidence and answer completion."""
|
||||
tools = payload.get('tools')
|
||||
if not isinstance(tools, list): return payload
|
||||
kept = [tool for tool in tools if not (isinstance(tool, dict)
|
||||
and isinstance(tool.get('function'), dict)
|
||||
and tool['function'].get('name') == 'display_chart')]
|
||||
if len(kept) == len(tools): return payload
|
||||
allowed = QUALITY_NATIVE_TOOLS if native_agent else QUALITY_NATIVE_TOOLS | {'story'}
|
||||
# Clarification/warehouse selection are upstream stop conditions with native
|
||||
# UI replies that this platform cannot consume. SQL, renderers and writers
|
||||
# also use a different data/artifact lifecycle. Unknown tools stay disabled.
|
||||
tools = tools if isinstance(tools, list) else []
|
||||
kept = [tool for tool in tools if isinstance(tool, dict) and tool.get('type') == 'function'
|
||||
and isinstance(tool.get('function'), dict) and isinstance(tool['function'].get('name'), str)
|
||||
and tool['function'].get('name') in allowed]
|
||||
if kept: payload['tools'] = kept
|
||||
else: payload.pop('tools', None)
|
||||
choice = payload.get('tool_choice')
|
||||
if ((isinstance(choice, dict) and (choice.get('function') or {}).get('name') == 'display_chart')
|
||||
kept_names = {tool['function']['name'] for tool in kept}
|
||||
choice_name = choice.get('function', {}).get('name') if isinstance(choice, dict) and isinstance(choice.get('function'), dict) else None
|
||||
if ((isinstance(choice, dict) and choice_name not in kept_names)
|
||||
or not kept and choice in ('auto', 'required')):
|
||||
payload.pop('tool_choice', None)
|
||||
if not kept: payload.pop('parallel_tool_calls', None)
|
||||
return payload
|
||||
|
||||
|
||||
|
||||
@@ -1480,6 +1480,11 @@ kind=members仅用于列出有哪些委托单/批号/规格等唯一成员,不
|
||||
value = candidate
|
||||
recovery_repairs.extend(changes)
|
||||
protocol_context = (context or {}).get('_protocol') if isinstance(context, dict) else None
|
||||
if (isinstance(protocol_context, dict) and protocol_context.get('version') == 1
|
||||
and task['kind'] in ('explain', 'restate') and not task.get('directResponse')
|
||||
and not task['needsClarification']):
|
||||
raise TaskUnavailable('当前协议的普通对话须提供directResponse;业务解释须选择正式分析或历史报告任务。',
|
||||
field='kind.protocol', expected='supported business task or reviewed directResponse')
|
||||
if autonomous_session:
|
||||
from nao_native_planning import history_only_requested
|
||||
if (history_only_requested(question) and not task['needsClarification']
|
||||
@@ -1572,7 +1577,7 @@ kind=members仅用于列出有哪些委托单/批号/规格等唯一成员,不
|
||||
or _source_column_intent(question, (context or {}).get('_businessCatalog', {}))))
|
||||
member_list_review_required = task['kind'] == 'members'
|
||||
if ((task.get('directResponse') or (semantic_review and payload['previousUserQuestions']) or review_read_requirements)
|
||||
and not autonomous_session
|
||||
and (not autonomous_session or task.get('directResponse'))
|
||||
and (task['kind'] in ('analysis','metrics','members','explain','restate','source_verify','details')
|
||||
or review_read_requirements and task['kind'] == 'report')):
|
||||
review_system = ('你是只读任务计划的语义核对员。依据前序用户问题与最新问题核对计划是否真正回答最新意图,'
|
||||
@@ -1585,6 +1590,7 @@ kind=members仅用于列出有哪些委托单/批号/规格等唯一成员,不
|
||||
'若用户要求报废率的分子分母或计算基数,实际fields须同时包含scrapRate、scrapWeight、totalWeight,不能只有goal提及;缺少任一应aligned=false。'
|
||||
'前序未完成的问题只提供语义,不是已核实结果;truncated的问题不完整,不推断省略内容。'
|
||||
'directResponse仅用于一般问候、能力介绍或致谢;业务趋势、比较和原因判断即使没有数字也不能直答。'
|
||||
'同时核对directResponse.answer正文;即使用户仅问候,只要回复夹带未查询业务事实或因果,必须判aligned=false或requiresEvidence=true。'
|
||||
'历史报告kind=report与复述不同:报告来源由服务端在任务确认后冻结和导入,规划上下文不会包含历史来源正文;'
|
||||
'previousVerifiedTurns为空、缺失或没有来源摘要不能据此判断历史数据不存在,也不能把用户明确的报告意图改成explain/restate或要求用户证明历史来源存在。'
|
||||
'应按用户范围保留kind=report、historyMode=first/last/all、freshQuery=false及空root指标条件;来源可用性/缺口交由服务端导入结果决定。'
|
||||
@@ -1992,8 +1998,12 @@ kind=members仅用于列出有哪些委托单/批号/规格等唯一成员,不
|
||||
if error.field:
|
||||
payload['validationFeedback'] = error.field + ': ' + str(error)
|
||||
payload['repairInstructions'] = '根据错误和上一份计划修正协议格式,保留原业务目标、期间及范围,返回完整JSON计划,不输出解释。'
|
||||
if error.field == 'directResponse.business':
|
||||
payload['repairInstructions'] = '当前问题涉及业务事实,禁止directResponse;保留用户最新问题及前文目标,返回完整业务分析或指标计划。'
|
||||
if error.field == 'kind.protocol':
|
||||
payload['repairInstructions'] = ('重新核对最新意图:一般问候、能力介绍或致谢必须返回kind=explain及directResponse的模型回复;'
|
||||
'涉及业务事实则选择现有analysis/metrics/report等正式任务,不能用普通explain/restate绕过查询。记忆或操作要求不得伪装普通对话。')
|
||||
elif error.field == 'directResponse.business':
|
||||
payload['repairInstructions'] = ('上次回复夹带未经查询的业务判断,请重新核对最新用户意图:问候或能力介绍仍使用directResponse,仅介绍能做什么,不断言实际业务结果;'
|
||||
'只有用户确实要求业务事实、比较或原因解释时,才改为完整业务分析或指标计划。保留原问题,不因上次错误回复改写用户目标。')
|
||||
elif error.field and error.field.startswith('directResponse'):
|
||||
payload['repairInstructions'] = '保持最小一般对话JSON,仅修复错误字段,保留kind、goal、directResponse;无需补全业务计划字段。answer只写一般回复,列表用项目符号,不写业务数值。'
|
||||
elif error.field and (error.field == 'queryPlan' or error.field.startswith('queryPlan.')):
|
||||
|
||||
@@ -33,10 +33,10 @@ def direct_plan(value):
|
||||
# Convert their prefixes to bullets; any remaining value still fails.
|
||||
text = re.sub(r'(?m)^[ \t]*[1-9]\d?[.、)][ \t]*(?!\d)', '- ', text)
|
||||
quantified_fact = (r'(?:\d+(?:[.,]\d+)*|[零〇一二两三四五六七八九十百千万点]+)\s*(?:[%%]|kg\b|公斤|千克|吨|个百分点|pp\b)'
|
||||
r'|百分之|(?:合格率|投入|报废|总重|产量|重量|数量)(?:重量|数量|总数|率)?\s*(?:为|是|有|达到|共|合计|总计|[::])?\s*\d')
|
||||
unperformed_action = r'(?:已|已经)(?:查到|查询|核实|统计|生成|保存|记住|修改|设置|完成分析)'
|
||||
r'|百分之|(?:合格率|投入|报废|总重|产量|重量|数量)(?:重量|数量|总数|率)?\s*(?:为|是|有|达到|共|合计|总计|[::])?\s*(?:\d|[零〇一二两三四五六七八九十百千万点])')
|
||||
unperformed_action = r'(?:已|已经)(?:查到|查询|核实|统计|生成|保存|记住|修改|设置|完成分析)(?!的)'
|
||||
if (isinstance(text,str) and re.search(r'合格率|报废|投入|产量|重量|分组|规格|产业部|国内|海外|产品',text)
|
||||
and re.search(r'主要是.{0,40}所致|主要来自|所致|远高于|远低于|更大|更小|更差|更好|基本持平|明显.{0,8}(?:下降|上升|增加|减少)|导致.{0,12}(?:下降|上升)',text)):
|
||||
and re.search(r'主要是.{0,40}所致|主要来自|主要原因是|所致|远高于|远低于|确实更(?:大|小|差|好)|基本持平|(?:下降|上升|增加|减少|恶化|改善)了|明显.{0,8}(?:下降|上升|增加|减少)|导致.{0,12}(?:下降|上升)',text)):
|
||||
invalid('当前答复包含未经查询的业务趋势或因果判断,请返回完整分析计划', 'directResponse.business')
|
||||
if (not isinstance(text, str) or not text.strip() or len(text) > 1200
|
||||
or re.search(quantified_fact + '|' + unperformed_action + r'|https?://|Q[A-F0-9]{8}|<[^>]+>|Bearer\s+|\bsk-[A-Za-z0-9_-]+|(?:api[_-]?key|token|password)\s*[:=]',text,re.I)):
|
||||
|
||||
+50
-13
@@ -21,6 +21,10 @@ class _NoRedirect(HTTPRedirectHandler):
|
||||
return None
|
||||
|
||||
|
||||
class ToolPolicyError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class ModelGate:
|
||||
"""A stable per-session endpoint backed only by this turn's live delegation."""
|
||||
|
||||
@@ -41,7 +45,9 @@ class ModelGate:
|
||||
self._thinking = dict(thinking_options) if thinking_options is not None else None
|
||||
self._on_thinking = on_thinking
|
||||
self._native_turn_marker = native_turn_marker
|
||||
self.native_agent = False
|
||||
self.rejected_stale_requests = 0
|
||||
self.rejected_tool_calls = 0
|
||||
self._request_number = 0
|
||||
self._request_prefix = secrets.token_hex(4)
|
||||
self.request_audit = []
|
||||
@@ -92,9 +98,10 @@ class ModelGate:
|
||||
for message in messages)):
|
||||
with gate._audit_lock: gate.rejected_stale_requests += 1
|
||||
self.failure(403, '模型请求不属于当前轮次'); return
|
||||
decoded = gate.apply_thinking(decoded)
|
||||
from nao_agent_contract import apply_platform_tools
|
||||
decoded = apply_platform_tools(decoded)
|
||||
decoded = apply_platform_tools(decoded, native_agent=gate.native_agent)
|
||||
decoded = gate.apply_thinking(decoded)
|
||||
offered_tools = {tool['function']['name'] for tool in decoded.get('tools', [])}
|
||||
payload = json.dumps(decoded,ensure_ascii=False).encode()
|
||||
except (ValueError, OSError):
|
||||
self.failure(400, '模型请求格式无效'); return
|
||||
@@ -141,9 +148,10 @@ class ModelGate:
|
||||
thinking('start')
|
||||
# SSE termination is a transport concern even when no thinking
|
||||
# callback is installed (for example, native stream forwarding).
|
||||
observer = ProviderStream(lambda text:thinking('delta',text=text)) if gate._on_thinking or is_sse else None
|
||||
observer = ProviderStream(lambda text:thinking('delta',text=text))
|
||||
raw_json = bytearray()
|
||||
if not bridge:
|
||||
pending_wire = bytearray()
|
||||
if is_sse and not bridge:
|
||||
self.send_response(response.status)
|
||||
self.send_header('Content-Type', response.headers.get('Content-Type', 'application/json'))
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
@@ -161,21 +169,29 @@ class ModelGate:
|
||||
if time.monotonic() - checked_at >= 1:
|
||||
gate._check()
|
||||
checked_at = time.monotonic()
|
||||
if observer:
|
||||
if is_sse:observer.feed(chunk)
|
||||
else:raw_json.extend(chunk)
|
||||
if not bridge:
|
||||
self.wfile.write(chunk)
|
||||
self.wfile.flush()
|
||||
if is_sse:
|
||||
observer.feed(chunk)
|
||||
gate.check_returned_tools(observer, offered_tools)
|
||||
if not bridge:
|
||||
# A partial SSE line cannot be checked yet. Hold
|
||||
# it until its complete event has passed policy.
|
||||
pending_wire.extend(chunk)
|
||||
end=pending_wire.rfind(b'\n')+1
|
||||
if end:
|
||||
self.wfile.write(pending_wire[:end]);self.wfile.flush()
|
||||
del pending_wire[:end]
|
||||
else:raw_json.extend(chunk)
|
||||
# A provider may keep the HTTP connection alive with heartbeats
|
||||
# after its explicit terminal event. Do not wait for EOF, but
|
||||
# keep reading past finish_reason so the usage tail is preserved.
|
||||
if is_sse and observer.done:
|
||||
break
|
||||
gate._check()
|
||||
if observer:
|
||||
if is_sse:observer.finish()
|
||||
else:observer.document(json.loads(raw_json))
|
||||
if is_sse:observer.finish()
|
||||
else:observer.document(json.loads(raw_json))
|
||||
gate.check_returned_tools(observer, offered_tools, final=True)
|
||||
if is_sse and not bridge and pending_wire:
|
||||
self.wfile.write(pending_wire);self.wfile.flush()
|
||||
result = observer.completion() if bridge or is_sse else None
|
||||
stops = [row['finish_reason'] for row in observer.choices.values()] if observer else []
|
||||
thinking('end',finishReason='length' if 'length' in stops else (stops[-1] if stops else ''),interrupted=bool(observer and not stops))
|
||||
@@ -188,6 +204,15 @@ class ModelGate:
|
||||
self.send_response(200);self.send_header('Content-Type','application/json')
|
||||
self.send_header('Cache-Control','no-store');self.send_header('Content-Length',str(len(encoded)))
|
||||
self.end_headers();headers_sent=True;self.wfile.write(encoded);self.wfile.flush()
|
||||
elif not is_sse:
|
||||
self.send_response(response.status);self.send_header('Content-Type','application/json')
|
||||
self.send_header('Cache-Control','no-store');self.send_header('Content-Length',str(len(raw_json)))
|
||||
self.end_headers();headers_sent=True;self.wfile.write(raw_json);self.wfile.flush()
|
||||
except ToolPolicyError:
|
||||
if not headers_sent:self.failure(502,'模型返回了当前任务未开放的工具调用')
|
||||
else:
|
||||
with contextlib.suppress(OSError):
|
||||
self.wfile.write(b'data: {"error":{"message":"Tool call is unavailable for this task"}}\n\n');self.wfile.flush()
|
||||
except HTTPError as error:
|
||||
if not headers_sent:
|
||||
self.failure(error.code if 400 <= error.code <= 599 else 502, '模型接口暂不可用')
|
||||
@@ -230,6 +255,8 @@ class ModelGate:
|
||||
else:payload['reasoning_effort']=effort
|
||||
with self._audit_lock:
|
||||
if len(self.request_audit)<200:self.request_audit.append({'enabled':enabled,'effort':effort,
|
||||
'tools':[tool['function']['name'] for tool in payload.get('tools',[])],
|
||||
'nativeAgent':self.native_agent,
|
||||
'protocol':protocol,'stream':payload.get('stream',False),
|
||||
'maxCompletionTokens':payload.get('max_completion_tokens',payload.get('max_tokens')),
|
||||
'thinkingType':(payload.get('thinking') or {}).get('type'),
|
||||
@@ -237,6 +264,16 @@ class ModelGate:
|
||||
'reasoningEffort':payload.get('reasoning_effort',(payload.get('chat_template_kwargs') or {}).get('reasoning_effort'))})
|
||||
return payload
|
||||
|
||||
def check_returned_tools(self, observer, offered, *, final=False):
|
||||
for choice, tools in observer.tools.items():
|
||||
finished=final or bool(observer.choices.get(choice,{}).get('finish_reason')) or observer.done
|
||||
for tool in tools.values():
|
||||
name=tool.get('function',{}).get('name','')
|
||||
valid=(name in offered) if finished else (not name or any(allowed.startswith(name) for allowed in offered))
|
||||
if not valid:
|
||||
with self._audit_lock:self.rejected_tool_calls+=1
|
||||
raise ToolPolicyError('Unadvertised tool call')
|
||||
|
||||
def _check(self) -> None:
|
||||
if self._closed.is_set():
|
||||
raise PermissionError('模型授权已关闭')
|
||||
|
||||
@@ -135,6 +135,7 @@ NATIVE_ROOT_PROMPT = '''你是质量数据分析平台的任务理解器,只
|
||||
沿用previousTask中未取消的条件,以最新明确修改为准;previousUserQuestions和lastVisibleAnswer只是理解指代的资料,不能恢复已取消条件。
|
||||
返回JSON:goal、kind、executionMode、filterUpdates、period、comparisonPeriod、comparisonRequired、trendRequired、dimensions、stages、fields、dimensionStages、memberFields、freshQuery、verifySource、fullDetails、needsClarification、clarification、visualPreference、responseStyle、historyMode。clarification始终是字符串,无澄清用空字符串,不能写对象;候选另放clarificationRequest。period年份和月份均为JSON整数,如{\"year\":2026,\"month\":9},不可只输出月份或字符串日期。
|
||||
kind仅analysis/metrics/members/explain/restate/report/source_verify/details;visualPreference仅auto/required/none;responseStyle仅brief/standard/detailed(默认standard);historyMode仅none/first/last/all(默认none)。比较、趋势、freshQuery、verifySource、fullDetails、needsClarification均使用JSON布尔值,不写null。dimensions/stages/fields是数组,dimensionStages是对象,filterUpdates无变化时{}。
|
||||
一般问候、能力介绍和致谢必须返回kind=explain及directResponse={purpose:greeting/capabilities/acknowledgement,answer:你的完整简短回复,requiresMemory:false};仅声明explain/restate却不给出directResponse不受当前协议支持。业务解释仍使用正式analysis/metrics或历史report,不能改为普通对话。
|
||||
为什么、原因定位、深入调查、解释多种变化及其续问使用kind=analysis、executionMode=native_agent,不写queryPlan。dimensions只填用户明确必须覆盖的维度,不预列所有调查方向;一般原因问题dimensions=[]、fields=[rate]。智能体之后根据实际结果决定查哪些组织、产品及缺陷。
|
||||
简单单值/趋势用metrics;明确排序用原静态analysis及queryPlan;清单members、原表source_verify、记录details和历史report沿用原能力。非自主任务省略executionMode。kind=members只表示唯一成员清单,不是原始行读取;memberFields必须是当前businessCatalog.sourceFields中1到5个授权key,stages必须明确选一个或两个阶段,期间及普通filters照常保留,dimensions=[]、fields=[]、verifySource=false、fullDetails=false、freshQuery=true。kind=members时memberFields必须按当前businessCatalog.sourceFields字段label的语义选择,不能猜key或把筛选字段当输出成员。用户只说“有哪些规格”时按产品规格理解,选择真实“产品规格/成品规格/规格型号”目录列;不能用“产品图号/图纸号”或“客户代码”代替。“客户都有哪些规格”中的客户是筛选对象,输出仍是产品规格;明确问图号才选图号列,明确问“客户规格”才选客户规格列。用户明确说“成品规格”等具体目录label时,优先精确匹配该label;裸“规格”有多个可用产品规格候选或目标没有可用字段时,needsClarification=true、memberFields=[],保留原目标并请用户明确字段,不擅选近似列。并列、否定或复合字段意图保留模型确认的正向成员,不能补入用户已取消的字段。
|
||||
静态合格率排名必须输出queryPlan,使用一个批量changes节点,禁止逐对象查询。root的dimensions、fields、stages、dimensionStages与节点联合需求一致;changes必须comparisonRequired=true并给出前一个同长度完整comparisonPeriod,即使按本期率排序也使用该两期批量接口。sort=current_rate按本期率升序;rate_drop按降幅降序;current_scrap/scrap_delta用于报废规模与不良影响。用户说“表现较差/最差”未指定指标时按黑片+亮片报废总重及综合合格率判断优先级,不只按极小批量最低率排序;比较分析用sort=current_scrap或scrap_delta。仅明确要求最低率时sort=current_rate。只问“哪个”limit=1,明确数量以用户为准,未指定通常3,最大10。fields按问题保留rate/totalWeight/scrapWeight;综合率stages=[]、dimensionStages={\"product\":[]}。明确按一个阶段的totalWeight或scrapWeight选产品Top N并显示这批对象的同阶段rate时,仍用静态analysis/queryPlan:先用base产品ranking按该阶段重量取Top N,再用metrics节点fields=[rate]、stages=[同阶段]和ranking_top selector绑定前置排名、同阶段、同重量指标及count=N。重量和对象选择来自排名,rate单独查询;不要把rate改为排序指标、对全体产品另查rate、加入比较或转成原因/缺陷调查。
|
||||
|
||||
+80
-44
@@ -2,6 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import re
|
||||
import time
|
||||
|
||||
|
||||
@@ -22,12 +23,17 @@ def exploration_notices(scopes, coverage):
|
||||
for kind,labels in grouped.items()]
|
||||
|
||||
|
||||
def _answer_evidence_refs(answer):
|
||||
"""Return only explicit query references present in the upstream answer."""
|
||||
return list(dict.fromkeys(re.findall(r'\bQ[A-F0-9]{8}\b', answer)))
|
||||
|
||||
|
||||
def run_native_exploration(*, request, task, authority, actor_root, delegated, connection,
|
||||
manager, state, cancel_event, emit, prior_evidence_files, phase_timings=None):
|
||||
from nao_quality_runtime import _atomic_json, _authenticate, _sse_request, _read_json
|
||||
from nao_agent_task import bind_task
|
||||
from nao_protocol_execution import _identity, _platform_visual_context, query_evidence_bindings
|
||||
from nao_evidence_finalizer import evidence_summaries, synthesize_native
|
||||
from nao_protocol_execution import _identity, query_evidence_bindings
|
||||
from nao_evidence_finalizer import evidence_summaries
|
||||
from analysis_visual_evidence import protocol_visual_result
|
||||
from nao_runtime_policy import native_timeout
|
||||
from nao_native_exploration import _proofs
|
||||
@@ -106,12 +112,16 @@ def run_native_exploration(*, request, task, authority, actor_root, delegated, c
|
||||
and type(progress.get('noProgress')) is int and progress['noProgress'] >= 3)
|
||||
if controlled_no_progress:
|
||||
missing.append('连续三次没有取得新证据,调查已停止;其余线索尚未验证。')
|
||||
natural_finish = 'stop' in accumulator.finish_reasons and stop_succeeded is not False
|
||||
natural_finish = bool(accumulator.finish_reasons and accumulator.finish_reasons[-1] == 'stop'
|
||||
and stop_succeeded is not False
|
||||
and getattr(accumulator, 'final_answer_ready', True))
|
||||
corrected_tool_errors = (native_reason == 'mcp_error' and natural_finish
|
||||
and complete_scopes is not None and bool(documents)
|
||||
and not missing and not progress.get('halted'))
|
||||
if native_status != 'COMPLETED' and not corrected_tool_errors and not controlled_no_progress:
|
||||
missing.append('自主调查未正常结束(' + str(native_reason or native_status) + '),已保留核实结果。')
|
||||
elif native_status == 'COMPLETED' and not natural_finish:
|
||||
missing.append('自主调查未收到有效的正常结束信号。')
|
||||
if not documents:
|
||||
missing.append('本轮未取得当前执行的可核验查询证据。')
|
||||
context['_protocolScopes'] = {'scopes': scopes, 'pending': snapshot.get('pending', []), 'gaps': missing}
|
||||
@@ -119,24 +129,7 @@ def run_native_exploration(*, request, task, authority, actor_root, delegated, c
|
||||
visuals = protocol_visual_result(documents, scopes, request['question'], request['turnId'],
|
||||
release_id=request['releaseId'], base_context=context)
|
||||
timings['visuals'] = round((time.monotonic() - started) * 1000)
|
||||
context['_platformVisuals'] = _platform_visual_context(visuals)
|
||||
emit({'type': 'progress', 'message': '正在核对结论与图表…', 'executionMode': 'native_agent'})
|
||||
started = time.monotonic()
|
||||
final = synthesize_native(base_url=connection[0], api_key=connection[1], model=connection[2],
|
||||
question=request['question'], evidence=documents, cancel_event=cancel_event,
|
||||
context=context, native_answer=accumulator.answer)
|
||||
timings['synthesis'] = round((time.monotonic() - started) * 1000)
|
||||
_atomic_json(actor_root / 'private' / 'native-composition.json', {
|
||||
'turnId': request['turnId'], 'rawModelResponses': final.get('rawModelResponses', []),
|
||||
'compositionDiagnostics': final.get('compositionDiagnostics', {}),
|
||||
'bindingInput': final.get('_privateBindingInput'),
|
||||
'titleMetadata': {key: final.get(key) for key in
|
||||
('reportTitle', 'titleGeneratedByModel', 'titleValid', 'titleSource')},
|
||||
'readingSummary': final.get('readingSummary')})
|
||||
full_facts = final.get('fullEvidenceFacts', [])
|
||||
if full_facts:
|
||||
_atomic_json(actor_root / 'private' / 'native-full-evidence-facts.json', full_facts)
|
||||
missing.extend(final.get('missingEvidence', []))
|
||||
emit({'type': 'progress', 'message': '正在生成正式图表并整理证据状态…', 'executionMode': 'native_agent'})
|
||||
visual_warnings = list(visuals.get('missingEvidence', []))
|
||||
if task.get('visualPreference') == 'required':
|
||||
missing.extend(visual_warnings)
|
||||
@@ -144,41 +137,84 @@ def run_native_exploration(*, request, task, authority, actor_root, delegated, c
|
||||
if visual_warnings and not summary_warnings:
|
||||
summary_warnings = ['部分重点图表未能完整展示;已保留核实文字和表格。']
|
||||
missing = list(dict.fromkeys(str(item) for item in missing if item))
|
||||
complete = bool(documents and final.get('evidenceSufficient') and not missing)
|
||||
used_refs = set(final.get('usedEvidenceRefs', []))
|
||||
cited_ids = list(dict.fromkeys(p['queryId'] for doc in documents if doc.get('evidenceRef') in used_refs
|
||||
for p in _proofs(doc.get('result', {}))))
|
||||
if final.get('evidenceSufficient') and not cited_ids:
|
||||
missing.append('解释未关联当前执行的实际查询证明。')
|
||||
complete = False
|
||||
answer = accumulator.answer if isinstance(accumulator.answer, str) else ''
|
||||
original_refs = _answer_evidence_refs(answer)
|
||||
complete_receipt_ids = {p.get('queryId') for p in receipts if isinstance(p, dict)
|
||||
and p.get('executionId') == identity['executionId'] and isinstance(p.get('queryId'), str)
|
||||
and p.get('queryId') in accepted_ids
|
||||
and complete_scopes is not None and (p.get('nodeId'), p.get('scopeId')) in complete_scopes}
|
||||
verified_document_ids = {}
|
||||
for doc in documents:
|
||||
proofs = _proofs(doc.get('result', {})) if isinstance(doc, dict) else []
|
||||
proof_ids = list(dict.fromkeys(p.get('queryId') for p in proofs
|
||||
if isinstance(p, dict) and isinstance(p.get('queryId'), str)))
|
||||
if (doc.get('evidenceRef') and proof_ids
|
||||
and all(query_id in complete_receipt_ids for query_id in proof_ids)):
|
||||
verified_document_ids[doc['evidenceRef']] = proof_ids
|
||||
document_refs = set(verified_document_ids)
|
||||
cited_refs = set(original_refs) & document_refs
|
||||
cited_ids = list(dict.fromkeys(query_id for doc_ref in original_refs if doc_ref in cited_refs
|
||||
for query_id in verified_document_ids[doc_ref]))
|
||||
unresolved_refs = sorted(set(original_refs) - cited_refs)
|
||||
if unresolved_refs:
|
||||
missing.extend('原文引用未关联本轮完整scope正式查询证据:' + ref + '。' for ref in unresolved_refs)
|
||||
background_ids = list(dict.fromkeys(query_id for proof_ids in verified_document_ids.values()
|
||||
for query_id in proof_ids)) if not original_refs else []
|
||||
if not original_refs and not background_ids and documents:
|
||||
missing.append('本轮没有可关联的完整scope正式查询证明。')
|
||||
conclusion_ids = cited_ids if original_refs else background_ids
|
||||
if len(conclusion_ids) > 40:
|
||||
missing.append('完整查询证据引用超过平台允许的40项上限。')
|
||||
conclusion_ids = conclusion_ids[:40]
|
||||
if not answer.strip():
|
||||
missing.append('自主分析未生成正文。')
|
||||
missing = list(dict.fromkeys(str(item) for item in missing if item))
|
||||
data_complete = bool(documents and not snapshot.get('rootGoalGaps')
|
||||
and (complete_scopes is not None or not snapshot.get('gaps'))
|
||||
and bool(conclusion_ids) and not unresolved_refs
|
||||
and len(cited_ids if original_refs else background_ids) <= 40)
|
||||
narrative_complete = bool(answer.strip() and natural_finish
|
||||
and (native_status == 'COMPLETED' or corrected_tool_errors))
|
||||
charts_complete = not visual_warnings
|
||||
complete = bool(data_complete and narrative_complete and not missing)
|
||||
if warnings or visual_warnings:
|
||||
_atomic_json(actor_root / 'private' / 'native-warning-diagnostics.json', {
|
||||
'turnId': request['turnId'], 'explorationWarnings': warnings,
|
||||
'visualWarnings': visual_warnings})
|
||||
if summary_warnings:
|
||||
if isinstance(final.get('readingSummary'), dict):
|
||||
final['readingSummary']['notices'] = list(dict.fromkeys([
|
||||
*final['readingSummary'].get('notices', []), *summary_warnings]))
|
||||
else:
|
||||
final['answer'] += '\n\n' + '\n'.join(dict.fromkeys(summary_warnings))
|
||||
if missing:
|
||||
final['answer'] += '\n\n尚未解决:' + ';'.join(missing)
|
||||
if isinstance(final.get('readingSummary'), dict):
|
||||
final['readingSummary']['notices'] = list(dict.fromkeys([
|
||||
*final['readingSummary'].get('notices', []), *missing]))
|
||||
_atomic_json(actor_root / 'private' / 'native-original-body-diagnostics.json', {
|
||||
'turnId': request['turnId'], 'executionId': identity['executionId'],
|
||||
'nativeStatus': native_status, 'nativeReason': native_reason,
|
||||
'finishReasons': list(accumulator.finish_reasons),
|
||||
'originalBodyCharacters': len(answer), 'originalBodyNonempty': bool(answer.strip()),
|
||||
'narrativeComplete': narrative_complete, 'dataComplete': data_complete,
|
||||
'narrativeFactBinding': 'not_assessed', 'citedEvidenceRefs': sorted(cited_refs),
|
||||
'unresolvedEvidenceRefs': unresolved_refs, 'missingEvidence': missing,
|
||||
'visualWarnings': visual_warnings, 'notices': list(dict.fromkeys(summary_warnings))})
|
||||
result = {'type': 'result', 'engine': 'NAO', 'status': 'COMPLETED' if complete else 'PARTIAL',
|
||||
'answer': final['answer'], 'readingSummary': final.get('readingSummary'),
|
||||
'reportTitle': final.get('reportTitle'), 'agentTask': task, 'protocol': identity,
|
||||
'answer': answer, 'readingSummary': None,
|
||||
'reportTitle': None, 'agentTask': task, 'protocol': identity,
|
||||
'executionMode': 'native_agent', 'completionMethod': 'native_autonomous_analysis',
|
||||
'stopReason': 'evidence_finalized' if complete else 'evidence_incomplete', 'finishReason': 'stop',
|
||||
'stopReason': 'evidence_finalized' if complete else 'evidence_incomplete',
|
||||
'finishReason': ('stop' if narrative_complete else
|
||||
str(accumulator.finish_reasons[-1]) if natural_finish and accumulator.finish_reasons else
|
||||
'incomplete' if native_status == 'COMPLETED' else str(native_reason or native_status)),
|
||||
'nativeStopReason': native_reason, 'nativeStopSucceeded': stop_succeeded,
|
||||
'nativeFinishReason': 'stop' if natural_finish else native_reason,
|
||||
'conclusionProtocolQueryIds': cited_ids,
|
||||
'conclusionProtocolQueryIds': conclusion_ids,
|
||||
'answerQuality': {'version': 1, 'dataComplete': data_complete,
|
||||
'narrativeComplete': narrative_complete,
|
||||
'chartsComplete': charts_complete,
|
||||
'narrativeFactBinding': 'not_assessed',
|
||||
'citedEvidenceRefs': sorted(cited_refs),
|
||||
'backgroundEvidenceQueryIds': background_ids,
|
||||
'unresolvedEvidenceRefs': unresolved_refs,
|
||||
'missingEvidence': missing,
|
||||
'notices': list(dict.fromkeys(summary_warnings))},
|
||||
'actualModel': model, 'phaseTimingsMs': timings,
|
||||
'protocolEvidence': receipts, 'queryEvidenceRefs': [doc['evidenceRef'] for doc in documents],
|
||||
'queryEvidenceBindings': query_evidence_bindings(documents, receipts),
|
||||
'toolCalls': accumulator.tool_calls, 'toolCount': len(accumulator.tool_calls),
|
||||
'timeline': accumulator.timeline, 'factsComplete': bool(documents and not missing),
|
||||
'timeline': accumulator.timeline, 'factsComplete': None,
|
||||
'evidenceCompletion': {'serverCoverageSufficient': not snapshot.get('rootGoalGaps'),
|
||||
'missingEvidence': missing},
|
||||
'agentContext': {key: copy.deepcopy(task[key]) for key in
|
||||
|
||||
@@ -1770,6 +1770,25 @@ def execute(*, request, task, authority, actor_root, delegated, connection, canc
|
||||
return result
|
||||
if cancel_event.is_set():
|
||||
raise RuntimeError('cancelled')
|
||||
if isinstance(task.get('directResponse'), dict):
|
||||
from nao_quality_runtime import ConversationAccumulator, _atomic_json, _record_non_query_turn, public_progress_text
|
||||
answer = task['directResponse']['answer']
|
||||
conversation = ConversationAccumulator()
|
||||
conversation.record_event('assistant', text=public_progress_text(answer))
|
||||
_atomic_json(actor_root / 'private' / 'last-conversation-answer.json', {
|
||||
'turnId': request['turnId'], 'goal': task['goal'],
|
||||
'purpose': task['directResponse']['purpose'], 'answer': answer})
|
||||
_record_non_query_turn(actor_root, request)
|
||||
result = {'type': 'result', 'engine': 'NAO', 'status': 'COMPLETED', 'answer': answer,
|
||||
'agentTask': task, 'protocol': identity, 'completionMethod': 'direct_conversation',
|
||||
'agentContext': {key: value for key, value in context.items()
|
||||
if key in ('releaseId', 'period', 'comparisonPeriod', 'filters')},
|
||||
'toolCalls': [], 'timeline': conversation.timeline, 'protocolEvidence': [],
|
||||
'queryEvidenceRefs': [], 'visualSchemaVersion': 1, 'visualState': 'not_requested',
|
||||
'visuals': [], 'stopReason': 'direct_conversation', 'finishReason': 'stop',
|
||||
'actualModel': connection[2], 'phaseTimingsMs': timings}
|
||||
emit(result)
|
||||
return result
|
||||
if task.get('kind') == 'report':
|
||||
from nao_history_report import execute_history_report
|
||||
return execute_history_report(request=request, task=task, authority=authority,
|
||||
|
||||
@@ -763,6 +763,17 @@ class ConversationAccumulator:
|
||||
return value
|
||||
return ""
|
||||
|
||||
@property
|
||||
def final_answer_ready(self) -> bool:
|
||||
if not self.answer or any(call.get('status') == 'started' for call in self.tool_calls):
|
||||
return False
|
||||
if not self.tool_calls:
|
||||
return True
|
||||
last_tool = max((i for i, entry in enumerate(self.timeline)
|
||||
if entry.get('kind') in ('tool_start', 'tool_result')), default=-1)
|
||||
return any(entry.get('kind') == 'assistant' and str(entry.get('text') or '').strip()
|
||||
for entry in self.timeline[last_tool + 1:])
|
||||
|
||||
def status(self, *, cancel_cause: str | None = None, stop_succeeded: bool | None = None,
|
||||
transport_failed: bool = False) -> tuple[str, str | None]:
|
||||
if cancel_cause == "user":
|
||||
@@ -781,18 +792,27 @@ class ConversationAccumulator:
|
||||
return ("PARTIAL" if self.answer else "FAILED", "transport_or_stream_error")
|
||||
if self.tool_error and (self.unattributed_tool_error or any(call["status"] == "failed" and not call.get("recovered") for call in self.tool_calls)):
|
||||
return ("PARTIAL" if self.answer else "FAILED", "mcp_error")
|
||||
if self.answer and (self.done_received or "stop" in self.finish_reasons):
|
||||
if (self.final_answer_ready and self.finish_reasons[-1] == 'stop'
|
||||
and stop_succeeded is not False):
|
||||
return "COMPLETED", "stop"
|
||||
return ("PARTIAL" if self.answer else "FAILED", "incomplete")
|
||||
|
||||
|
||||
def _contains_error_flag(value: Any) -> bool:
|
||||
if isinstance(value, dict):
|
||||
if value.get("isError") is True or value.get("error"):
|
||||
if (any(value.get(flag) is True for flag in ('isError', 'mcpValidationError', 'mcpAuthRequired'))
|
||||
or value.get('success') is False or value.get('error')):
|
||||
return True
|
||||
return any(_contains_error_flag(item) for item in value.values())
|
||||
# Inspect only known response envelopes. Rows, source cells, notes and
|
||||
# arbitrary JSON strings are business data, not nested tool outcomes.
|
||||
content = value.get('content')
|
||||
if isinstance(content, list) and any(isinstance(part, dict) and part.get('type') == 'text'
|
||||
and _contains_error_flag(part.get('text')) for part in content):
|
||||
return True
|
||||
return _contains_error_flag(value['structuredContent']) if isinstance(value.get('structuredContent'), dict) else False
|
||||
if isinstance(value, list):
|
||||
return any(_contains_error_flag(item) for item in value)
|
||||
return any(isinstance(part, dict) and part.get('type') == 'text'
|
||||
and _contains_error_flag(part.get('text')) for part in value)
|
||||
if isinstance(value, str) and len(value) <= 64 * 1024:
|
||||
stripped = value.strip()
|
||||
if stripped.startswith(("{", "[")):
|
||||
@@ -1922,6 +1942,10 @@ def _sse_request(
|
||||
ready_state: dict[str, Any] = {"identity": None, "since": None}
|
||||
|
||||
def completion_ready() -> bool:
|
||||
# The watchdog can observe a stale halted exploration state between a
|
||||
# natural model finish and the stream's trailing [DONE] marker.
|
||||
if accumulator.done_received or (accumulator.finish_reasons and accumulator.finish_reasons[-1] == 'stop'):
|
||||
return False
|
||||
if autonomous:
|
||||
progress_path = actor_root / 'private' / 'native-exploration-state.json'
|
||||
if not _require_private_regular_file(progress_path):
|
||||
@@ -2630,6 +2654,7 @@ def _run_turn(payload: dict[str, Any], *, stdout: Any = sys.stdout, stdin: Any =
|
||||
from nao_protocol_execution import execute
|
||||
request['_autonomousAnswer'] = protocol.get('autonomousEnabled') is True
|
||||
if authority['task'].get('executionMode') == 'native_agent':
|
||||
model_gate.native_agent = True
|
||||
from nao_native_run import run_native_exploration
|
||||
return run_native_exploration(request=request, task=authority['task'], authority=authority,
|
||||
actor_root=actor_root, delegated=delegated, connection=selected_connection,
|
||||
@@ -3108,6 +3133,7 @@ def _run_turn(payload: dict[str, Any], *, stdout: Any = sys.stdout, stdin: Any =
|
||||
if model_gate is not None:
|
||||
try:
|
||||
_atomic_json(actor_root/'private'/'last-model-audit.json',{'model':selected_model,'requests':model_gate.request_audit,
|
||||
'rejectedToolCalls':model_gate.rejected_tool_calls if isinstance(model_gate.rejected_tool_calls,int) else 0,
|
||||
'rejectedStaleRequests':model_gate.rejected_stale_requests if isinstance(model_gate.rejected_stale_requests,int) else 0})
|
||||
except (OSError,TypeError,ValueError):pass
|
||||
model_gate.close()
|
||||
|
||||
@@ -316,14 +316,18 @@ class AnalysisVisualsTest(unittest.TestCase):
|
||||
|
||||
def test_rate_drop_is_signed_and_converted_to_percentage_points(self):
|
||||
result = changes_result(sort="rate_drop", rows=[
|
||||
{"rank": 1, "key": "p-1", "label": "规格一", "rateDrop": -0.025},
|
||||
{"rank": 2, "key": "p-2", "label": "规格二", "rateDrop": 0.04},
|
||||
{"rank": 1, "key": "p-1", "label": "规格一", "rateDrop": 0.025},
|
||||
{"rank": 2, "key": "p-2", "label": "规格二", "rateDrop": -0.04},
|
||||
])
|
||||
chart = build_visuals([evidence(result)], "画图比较产品合格率降幅", "turn-03")["visuals"][0]
|
||||
self.assertEqual(chart["metric"], "rate_drop_pp")
|
||||
self.assertEqual(chart["unit"], "pp")
|
||||
self.assertEqual(chart["series"][0]["values"], [-2.5, 4.0])
|
||||
self.assertEqual([row["key"] for row in result["rows"]], ["p-1", "p-2"])
|
||||
self.assertEqual([item["key"] for item in chart["categories"]], ["p-1", "p-2"])
|
||||
self.assertIn("率降幅线索", chart["title"])
|
||||
self.assertIn("本期减比较期", chart["note"])
|
||||
self.assertIn("仍按率降幅排序", chart["note"])
|
||||
self.assertIn("未纳入投入规模", chart["note"])
|
||||
|
||||
def test_broad_product_focus_omits_rate_only_ranking_chart(self):
|
||||
@@ -377,7 +381,9 @@ class AnalysisVisualsTest(unittest.TestCase):
|
||||
self.assertEqual(chart["requiredFields"], [
|
||||
"black_good_weight", "black_total_weight", "bright_good_weight", "bright_total_weight"
|
||||
])
|
||||
self.assertEqual(chart["series"][0]["values"], [2.0, -1.0])
|
||||
self.assertEqual(chart["series"][0]["values"], [-2.0, 1.0])
|
||||
self.assertIn("负值为下降,正值为上升", chart["note"])
|
||||
self.assertIn("本期减比较期", chart["note"])
|
||||
|
||||
def test_quality_top_uses_ranked_weights_and_never_share(self):
|
||||
result = {
|
||||
|
||||
@@ -97,7 +97,7 @@ class MinimalQueryTests(unittest.TestCase):
|
||||
context=bind_task({'releaseId':RELEASE},task))
|
||||
self.assertEqual(visual['visualState'],'ready',visual)
|
||||
self.assertEqual(visual['visuals'][0]['metric'],'rate_drop_pp')
|
||||
self.assertEqual(visual['visuals'][0]['series'][0]['values'],[20.0])
|
||||
self.assertEqual(visual['visuals'][0]['series'][0]['values'],[-20.0])
|
||||
result['sort']='current_rate';task['changeQuery']['sort']='current_rate'
|
||||
visual=build_visuals([doc],task['question'],TURN,
|
||||
context=bind_task({'releaseId':RELEASE},task))
|
||||
|
||||
@@ -99,4 +99,40 @@ class ConversationTests(unittest.TestCase):
|
||||
for sanitizer in (public_progress_text,public_thinking_text):
|
||||
output=sanitizer(text);self.assertNotIn('quality-turn:',output);self.assertIn('继续答复',output)
|
||||
|
||||
|
||||
class AutonomousConversationReviewTests(unittest.TestCase):
|
||||
def test_capability_descriptions_do_not_claim_to_have_run_a_query(self):
|
||||
value=direct();value['directResponse']['answer']='我可以帮你比较不同产业部谁表现更好,并整理已核实的历史结果。'
|
||||
self.assertEqual(normalize_task(value,'你能做什么')['directResponse']['answer'],value['directResponse']['answer'])
|
||||
def test_unsupported_bare_explain_is_repaired_before_protocol_confirmation(self):
|
||||
from test_nao_agent_task import task_value
|
||||
replies=[task_value(kind='explain',freshQuery=False,fields=[],stages=[],dimensions=[],dimensionStages={}),direct(),{'aligned':True,'requiresEvidence':False}]
|
||||
calls=[]
|
||||
def opener(request,timeout):
|
||||
calls.append(json.loads(request.data));reply=replies.pop(0)
|
||||
return io.BytesIO(json.dumps({'choices':[{'finish_reason':'stop','message':{'content':json.dumps(reply)}}]}).encode())
|
||||
task=plan_task(base_url='https://offline.invalid',api_key='synthetic',model='m',question='介绍一下能做哪些事',context={'_protocol':{'version':1,'autonomousEnabled':True}},cancel_event=threading.Event(),opener=opener)
|
||||
self.assertIn('directResponse',task);self.assertEqual(len(calls),3);self.assertEqual(task['planRecovery']['errors'][0]['field'],'kind.protocol')
|
||||
def test_autonomous_greeting_still_receives_independent_semantic_review(self):
|
||||
bodies=[]
|
||||
def opener(request,timeout):
|
||||
bodies.append(json.loads(request.data));reply=direct() if len(bodies)==1 else {'aligned':True,'requiresEvidence':False}
|
||||
return io.BytesIO(json.dumps({'choices':[{'finish_reason':'stop','message':{'content':json.dumps(reply)}}]}).encode())
|
||||
task=plan_task(base_url='https://offline.invalid',api_key='synthetic',model='m',question='你好',context={'_protocol':{'version':1,'autonomousEnabled':True}},cancel_event=threading.Event(),opener=opener)
|
||||
self.assertIn('directResponse',task);self.assertEqual(len(bodies),2);self.assertIn('plannedTask',json.loads(bodies[1]['messages'][1]['content']))
|
||||
def test_autonomous_business_answer_mislabelled_as_conversation_cannot_skip_evidence_review(self):
|
||||
calls=[]
|
||||
def opener(request,timeout):
|
||||
body=json.loads(request.data);calls.append(body)
|
||||
if 'plannedTask' in json.loads(body['messages'][1]['content']):reply={'aligned':True,'requiresEvidence':True}
|
||||
else:
|
||||
reply=direct();reply['directResponse']['answer']='这批比之前差,得调整设备。'
|
||||
return io.BytesIO(json.dumps({'choices':[{'finish_reason':'stop','message':{'content':json.dumps(reply)}}]}).encode())
|
||||
with self.assertRaises(TaskUnavailable):plan_task(base_url='https://offline.invalid',api_key='synthetic',model='m',question='解释这批次质量问题',context={'_protocol':{'version':1,'autonomousEnabled':True}},cancel_event=threading.Event(),opener=opener)
|
||||
self.assertTrue(any('plannedTask' in json.loads(body['messages'][1]['content']) for body in calls))
|
||||
def test_unqueried_chinese_values_and_plain_causal_assertions_are_rejected(self):
|
||||
for text in ['黑片合格率下降了,主要原因是设备故障。','上月报废重量为一百。']:
|
||||
value=direct();value['directResponse']['answer']=text
|
||||
with self.subTest(text=text),self.assertRaises(TaskUnavailable):normalize_task(value,'你好')
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
|
||||
@@ -149,14 +149,24 @@ class EvidenceFinalizerTest(unittest.TestCase):
|
||||
with self.assertRaises(finalizer.FinalizationUnavailable):
|
||||
finalizer.packed_evidence([{'unique': 'a'*finalizer.MAX_INPUT_CHARS}])
|
||||
|
||||
def test_real_second_turn_replay_fits_and_preserves_every_summary_value(self):
|
||||
def test_real_second_turn_replay_preserves_every_value_and_obeys_current_input_budget(self):
|
||||
root=Path(__file__).resolve().parents[1]/'output/20261023-autonomous-investigation/runtime'
|
||||
directories=list(root.glob('.runtime/nao-users/*/sessions/57676d5a-5138-48f4-9343-bae9731aae5a/evidence'))
|
||||
if not directories: self.skipTest('Private captured acceptance evidence not present')
|
||||
with patch.object(finalizer,'packed_evidence',side_effect=AssertionError('Local archives do not consume model input budget')):
|
||||
docs=finalizer.evidence_summaries(directories[0],'194b0287-9044-4d80-9138-ecd3c481015c')
|
||||
self.assertEqual(len(docs),15)
|
||||
self.assertEqual(unpack(finalizer.packed_evidence(docs)),docs)
|
||||
# Formal display metadata has grown since this private run was captured.
|
||||
# Local archives remain lossless; a bounded model handoff may reject an
|
||||
# oversized summary, but may never silently trim it to fit.
|
||||
limit=finalizer.MAX_INPUT_CHARS
|
||||
with patch.object(finalizer,'MAX_INPUT_CHARS',100_000_000):
|
||||
packed=finalizer.packed_evidence(docs)
|
||||
self.assertEqual(unpack(packed),docs)
|
||||
encoded=json.dumps(packed,ensure_ascii=False,separators=(',',':'))
|
||||
if len(encoded)>limit:
|
||||
with self.assertRaises(finalizer.FinalizationUnavailable):finalizer.packed_evidence(docs)
|
||||
else:self.assertEqual(unpack(finalizer.packed_evidence(docs)),docs)
|
||||
# This captured run predates paired black/bright defect reads for each
|
||||
# highlighted product, so it is now correctly labelled incomplete.
|
||||
self.assertFalse(finalizer.coverage_sufficient(docs,'分析质量变化'))
|
||||
|
||||
@@ -114,6 +114,71 @@ class ModelGateTests(unittest.TestCase):
|
||||
self.assertNotIn('fake-sensitive-provider-details', body)
|
||||
self.assertEqual(len(self.calls), 1)
|
||||
|
||||
def test_unadvertised_tool_calls_are_blocked_before_json_or_stream_execution(self):
|
||||
from unittest.mock import Mock
|
||||
data_tool={'type':'function','function':{'name':'mcp_call','parameters':{'type':'object'}}}
|
||||
tool={'id':'call-blocked','type':'function','function':{'name':'clarification','arguments':'{}'}}
|
||||
reply={'choices':[{'index':0,'message':{'role':'assistant','content':None,'tool_calls':[tool]},'finish_reason':'tool_calls'}]}
|
||||
upstream=HeldOpenProviderResponse([json.dumps(reply).encode()]);upstream.headers={'Content-Type':'application/json'};upstream.release.set()
|
||||
self.gate._opener=Mock();self.gate._opener.open.return_value=upstream
|
||||
code,body=self.request(extra={'tools':[data_tool]})
|
||||
self.assertEqual(code,502);self.assertNotIn('clarification',body)
|
||||
for newline in (True,False):
|
||||
prefix=b'data: {"choices":[{"index":0,"delta":{"content":"Preserved text"}}]}\n\n'
|
||||
bad=('data: '+json.dumps({'choices':[{'index':0,'delta':{'tool_calls':[tool]},'finish_reason':'tool_calls'}]})+ ('\n\n' if newline else '')).encode()
|
||||
upstream=HeldOpenProviderResponse([prefix,bad[:19],bad[19:]]);upstream.release.set()
|
||||
self.gate._opener.open.return_value=upstream
|
||||
code,body=self.request(extra={'stream':True,'tools':[data_tool]})
|
||||
self.assertEqual(code,200);self.assertIn('Preserved text',body)
|
||||
self.assertNotIn('clarification',body);self.assertIn('error',body)
|
||||
|
||||
def test_allowed_fragmented_tool_calls_keep_their_exact_wire_data(self):
|
||||
from unittest.mock import Mock
|
||||
rows=[{'choices':[{'index':0,'delta':{'tool_calls':[{'index':0,'id':'q','type':'function','function':{'name':'mcp_','arguments':''}}]}}]},
|
||||
{'choices':[{'index':0,'delta':{'tool_calls':[{'index':0,'function':{'name':'call','arguments':'{}'}}]},'finish_reason':'tool_calls'}]}]
|
||||
wire=b''.join(('data: '+json.dumps(row)+'\n\n').encode() for row in rows)+b'data: [DONE]\n\n'
|
||||
upstream=HeldOpenProviderResponse([wire[:23],wire[23:71],wire[71:]]);upstream.release.set()
|
||||
self.gate._opener=Mock();self.gate._opener.open.return_value=upstream
|
||||
code,body=self.request(extra={'stream':True,'tools':[{'type':'function','function':{'name':'mcp_call'}}]})
|
||||
self.assertEqual(code,200);self.assertEqual(body.encode(),wire)
|
||||
|
||||
def test_follow_up_tool_cannot_end_analysis_before_the_model_writes_an_answer(self):
|
||||
data_tool = {'type': 'function', 'function': {'name': 'mcp_call', 'parameters': {'type': 'object'}}}
|
||||
follow_up = {'type': 'function', 'function': {'name': 'suggest_follow_ups', 'parameters': {'type': 'object'}}}
|
||||
for choice in ('auto', {'type': 'function', 'function': {'name': 'suggest_follow_ups'}}):
|
||||
with self.subTest(choice=choice):
|
||||
self.assertEqual(self.request(extra={'tools': [data_tool, follow_up], 'tool_choice': choice})[0], 200)
|
||||
self.assertEqual(self.calls[-1]['tools'], [data_tool])
|
||||
if isinstance(choice, dict):
|
||||
self.assertNotIn('tool_choice', self.calls[-1])
|
||||
self.assertEqual(self.request(extra={'tools': [follow_up], 'tool_choice': 'required'})[0], 200)
|
||||
self.assertNotIn('tools', self.calls[-1])
|
||||
self.assertNotIn('tool_choice', self.calls[-1])
|
||||
|
||||
def test_only_supported_tools_reach_the_native_model_in_each_execution_mode(self):
|
||||
helpers = ['read', 'list', 'grep', 'search', 'mcp_call', 'mcp_connect']
|
||||
incompatible = ['clarification', 'request_warehouse_selection', 'request_warehouse_credentials',
|
||||
'execute_sql', 'execute_semantic_query', 'read_query_result', 'display_chart', 'display_map',
|
||||
'write', 'str_replace', 'execute_python', 'execute_sandboxed_code', 'task',
|
||||
'onboarding_command', 'onboarding_progress', 'generate_onboarding_rules',
|
||||
'suggest_follow_ups', 'future_unknown_tool']
|
||||
tools = [{'type': 'function', 'function': {'name': n, 'parameters': {'type': 'object'}}}
|
||||
for n in helpers + ['story'] + incompatible]
|
||||
for native in (False, True):
|
||||
self.gate.native_agent = native
|
||||
self.assertEqual(self.request(extra={'tools': tools})[0], 200)
|
||||
self.assertEqual([t['function']['name'] for t in self.calls[-1]['tools']],
|
||||
helpers + ([] if native else ['story']))
|
||||
|
||||
def test_forced_unavailable_tool_cannot_survive_even_without_a_tool_definition(self):
|
||||
for extra in ({'tool_choice': {'type': 'function', 'function': {'name': 'clarification'}}},
|
||||
{'tool_choice': {'type': 'function', 'function': 'malformed'}},
|
||||
{'tools': [], 'tool_choice': 'required'},
|
||||
{'tools': [{'type': 'function', 'function': {'name': 'read'}}],
|
||||
'tool_choice': {'type': 'function', 'function': {'name': 'execute_sql'}}}):
|
||||
self.assertEqual(self.request(extra=extra)[0], 200)
|
||||
self.assertNotIn('tool_choice', self.calls[-1])
|
||||
|
||||
def test_previous_turn_background_call_cannot_enter_current_thinking_or_provider(self):
|
||||
marker='quality-turn:current-request'
|
||||
self.gate._native_turn_marker=marker
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
"""Regression tests for the isolated native-agent original-body runtime copy."""
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import ModuleType, SimpleNamespace
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
|
||||
PROJECT = Path(__file__).resolve().parents[1]
|
||||
RUNTIME_COPY = Path(os.environ.get('NAO_ORIGINAL_BODY_PATH',
|
||||
str(PROJECT / 'scripts/nao_native_run.py'))).expanduser().resolve()
|
||||
SPEC = importlib.util.spec_from_file_location('nao_native_run_original_body', RUNTIME_COPY)
|
||||
NATIVE_RUN = importlib.util.module_from_spec(SPEC)
|
||||
sys.modules[SPEC.name] = NATIVE_RUN
|
||||
SPEC.loader.exec_module(NATIVE_RUN)
|
||||
|
||||
|
||||
IDENTITY = {'attemptId': 'attempt-current', 'sessionId': 'session-current',
|
||||
'turnId': 'turn-current', 'revision': 3, 'executionId': 'execution-current'}
|
||||
|
||||
|
||||
def proof(query_id='query-current'):
|
||||
return {**IDENTITY, 'queryId': query_id, 'nodeId': 'root', 'scopeId': 'scope-root',
|
||||
'responseHash': 'a' * 64}
|
||||
|
||||
|
||||
def document(ref='Q00000001', evidence_proof=None):
|
||||
return {'evidenceRef': ref, 'result': {'protocolEvidence': evidence_proof or proof()}}
|
||||
|
||||
|
||||
def task():
|
||||
return {'version': 1, 'goal': '解释下降并根据实际结果调查', 'question': '本期下降原因',
|
||||
'executionMode': 'native_agent', 'kind': 'analysis',
|
||||
'period': {'year': 2026, 'month': 9}, 'comparisonPeriod': {'year': 2026, 'month': 8},
|
||||
'filters': {'department': '当前产业部'}, 'fields': ['rate'], 'stages': [],
|
||||
'dimensions': [], 'dimensionStages': {}, 'visualPreference': 'auto',
|
||||
'comparisonRequired': True, 'trendRequired': False,
|
||||
'verifySource': False, 'fullDetails': False}
|
||||
|
||||
|
||||
class NativeOriginalBodyTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.actor_root = Path(self.temp.name)
|
||||
(self.actor_root / 'private').mkdir()
|
||||
(self.actor_root / 'evidence').mkdir()
|
||||
self.cancel_event = threading.Event()
|
||||
self.task = task()
|
||||
self.request = {'sessionId': IDENTITY['sessionId'], 'turnId': IDENTITY['turnId'],
|
||||
'actorId': 'actor-current', 'releaseId': 'release-current',
|
||||
'question': self.task['question'],
|
||||
'context': {'_serverHistory': [], '_serverQuestions': [], '_protocol': {}}}
|
||||
self.current_proof = proof()
|
||||
self.documents = [document(evidence_proof=self.current_proof)]
|
||||
self.snapshot = {'scopes': [{'nodeId': 'root', 'scopeId': 'scope-root', 'task': self.task}],
|
||||
'queries': [{'proof': self.current_proof}],
|
||||
'scopeCoverage': [{'nodeId': 'root', 'scopeId': 'scope-root', 'complete': True}],
|
||||
'rootGoalGaps': [], 'gaps': [], 'pending': [], 'explorationWarnings': []}
|
||||
self.accumulator = SimpleNamespace(answer='原始回答 [Q00000001]', finish_reasons=['stop'],
|
||||
tool_calls=[{'tool': 'quality_data', 'status': 'completed', 'input': {'mode': 'compare'}}],
|
||||
timeline=[{'kind': 'assistant', 'text': '原始回答'}])
|
||||
self.native_status, self.native_reason, self.stop_succeeded = 'COMPLETED', 'stop', None
|
||||
self.events = []
|
||||
self.manager = Mock()
|
||||
self.manager.ensure_instance.return_value = (None, None, 'fixture-model', 'http://native.invalid')
|
||||
self.delegated = Mock()
|
||||
self.delegated.call.side_effect = lambda *args, **kwargs: copy.deepcopy(self.snapshot)
|
||||
self.synthetic_writer = Mock(side_effect=AssertionError('native original-body path must not synthesize text'))
|
||||
|
||||
quality_runtime = ModuleType('nao_quality_runtime')
|
||||
quality_runtime._atomic_json = self.atomic_json
|
||||
quality_runtime._authenticate = Mock(return_value=object())
|
||||
quality_runtime._sse_request = self.native
|
||||
quality_runtime._read_json = self.read_json
|
||||
agent_task = ModuleType('nao_agent_task')
|
||||
agent_task.bind_task = lambda seed, current_task: {**copy.deepcopy(current_task), **copy.deepcopy(seed)}
|
||||
protocol_execution = ModuleType('nao_protocol_execution')
|
||||
protocol_execution._identity = lambda authority: copy.deepcopy(IDENTITY)
|
||||
protocol_execution._platform_visual_context = lambda visuals: {'visualState': visuals.get('visualState')}
|
||||
protocol_execution.query_evidence_bindings = lambda docs, receipts: [
|
||||
{'evidenceRef': item['evidenceRef'], 'proofs': item['result'].get('protocolEvidence')}
|
||||
for item in docs]
|
||||
evidence_finalizer = ModuleType('nao_evidence_finalizer')
|
||||
evidence_finalizer.evidence_summaries = lambda *args, **kwargs: copy.deepcopy(self.documents)
|
||||
evidence_finalizer.synthesize_native = self.synthetic_writer
|
||||
visual_evidence = ModuleType('analysis_visual_evidence')
|
||||
visual_evidence.protocol_visual_result = self.visual_result
|
||||
runtime_policy = ModuleType('nao_runtime_policy')
|
||||
runtime_policy.native_timeout = lambda: 30
|
||||
native_exploration = ModuleType('nao_native_exploration')
|
||||
native_exploration._proofs = lambda result: ([result['protocolEvidence']]
|
||||
if isinstance(result, dict) and isinstance(result.get('protocolEvidence'), dict) else [])
|
||||
self.modules = {'nao_quality_runtime': quality_runtime, 'nao_agent_task': agent_task,
|
||||
'nao_protocol_execution': protocol_execution,
|
||||
'nao_evidence_finalizer': evidence_finalizer,
|
||||
'analysis_visual_evidence': visual_evidence,
|
||||
'nao_runtime_policy': runtime_policy,
|
||||
'nao_native_exploration': native_exploration}
|
||||
self.module_patch = patch.dict(sys.modules, self.modules)
|
||||
self.module_patch.start()
|
||||
self.addCleanup(self.module_patch.stop)
|
||||
|
||||
def atomic_json(self, path, payload):
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(payload, ensure_ascii=False), encoding='utf-8')
|
||||
|
||||
@staticmethod
|
||||
def read_json(path):
|
||||
return json.loads(Path(path).read_text(encoding='utf-8'))
|
||||
|
||||
def native(self, **kwargs):
|
||||
return self.accumulator, self.native_status, self.native_reason, self.stop_succeeded
|
||||
|
||||
def visual_result(self, documents, scopes, question, turn_id, **kwargs):
|
||||
return {'visualState': 'ready', 'visuals': [{'id': 'formal-query-chart',
|
||||
'evidenceRefs': [item['evidenceRef'] for item in documents]}], 'missingEvidence': []}
|
||||
|
||||
def invoke(self):
|
||||
return NATIVE_RUN.run_native_exploration(request=copy.deepcopy(self.request),
|
||||
task=copy.deepcopy(self.task), authority=copy.deepcopy(IDENTITY),
|
||||
actor_root=self.actor_root, delegated=self.delegated,
|
||||
connection=('https://model.invalid/v1', 'synthetic-fixture-key', 'fixture-model'),
|
||||
manager=self.manager, state={}, cancel_event=self.cancel_event,
|
||||
emit=self.events.append, prior_evidence_files={'prior-evidence.json'},
|
||||
phase_timings={'planningAndReview': 10, 'taskConfirmation': 20})
|
||||
|
||||
def test_persists_the_complete_original_body_and_keeps_formal_charts(self):
|
||||
body = '原生回答第一行\n' + ('原生正文' * 1800) + '\n[Q00000001]'
|
||||
self.accumulator.answer = body
|
||||
self.accumulator.timeline = [{'kind': 'assistant', 'text': 'x' * 8000}]
|
||||
|
||||
result = self.invoke()
|
||||
|
||||
self.assertEqual(result['status'], 'COMPLETED')
|
||||
self.assertEqual(result['answer'], body)
|
||||
self.assertIsNone(result['readingSummary'])
|
||||
self.assertEqual(result['visuals'][0]['id'], 'formal-query-chart')
|
||||
self.assertEqual(result['queryEvidenceRefs'], ['Q00000001'])
|
||||
self.assertEqual(result['conclusionProtocolQueryIds'], ['query-current'])
|
||||
self.assertEqual(result['answerQuality']['narrativeFactBinding'], 'not_assessed')
|
||||
self.assertEqual(result['answerQuality']['backgroundEvidenceQueryIds'], [])
|
||||
self.assertIsNone(result['factsComplete'])
|
||||
self.assertEqual(self.read_json(self.actor_root / 'private/native-draft.json')['answer'], body)
|
||||
self.assertEqual(self.read_json(self.actor_root / 'private/native-completion.json')['answer'], body)
|
||||
self.assertEqual(self.read_json(self.actor_root / 'private/native-original-body-diagnostics.json')
|
||||
['originalBodyCharacters'], len(body))
|
||||
self.synthetic_writer.assert_not_called()
|
||||
|
||||
def test_empty_native_body_stays_empty_and_cannot_be_completed(self):
|
||||
self.accumulator.answer = ''
|
||||
|
||||
result = self.invoke()
|
||||
|
||||
self.assertEqual(result['answer'], '')
|
||||
self.assertEqual(result['status'], 'PARTIAL')
|
||||
self.assertFalse(result['answerQuality']['narrativeComplete'])
|
||||
self.assertIn('自主分析未生成正文。', result['answerQuality']['missingEvidence'])
|
||||
self.synthetic_writer.assert_not_called()
|
||||
|
||||
def test_missing_formal_evidence_is_metadata_and_does_not_rewrite_the_body(self):
|
||||
self.documents = []
|
||||
body = '原始正文照常保留。'
|
||||
self.accumulator.answer = body
|
||||
|
||||
result = self.invoke()
|
||||
|
||||
self.assertEqual(result['answer'], body)
|
||||
self.assertEqual(result['status'], 'PARTIAL')
|
||||
self.assertFalse(result['answerQuality']['dataComplete'])
|
||||
self.assertIn('本轮未取得当前执行的可核验查询证据。', result['answerQuality']['missingEvidence'])
|
||||
self.assertNotIn('尚未解决', result['answer'])
|
||||
self.synthetic_writer.assert_not_called()
|
||||
|
||||
def test_partial_or_interrupted_generation_is_not_rewritten_or_marked_complete(self):
|
||||
self.native_status, self.native_reason = 'PARTIAL', 'length'
|
||||
self.accumulator.finish_reasons = ['length']
|
||||
body = '模型已输出的局限与正文。'
|
||||
self.accumulator.answer = body
|
||||
|
||||
result = self.invoke()
|
||||
|
||||
self.assertEqual(result['answer'], body)
|
||||
self.assertEqual(result['status'], 'PARTIAL')
|
||||
self.assertFalse(result['answerQuality']['narrativeComplete'])
|
||||
self.assertEqual(result['finishReason'], 'length')
|
||||
self.synthetic_writer.assert_not_called()
|
||||
|
||||
def test_completed_status_without_natural_stop_remains_partial(self):
|
||||
body = '原生回答保留,结束信号不足。'
|
||||
self.accumulator.answer = body
|
||||
cases = (
|
||||
('missing_stop_finish_reason', [], None),
|
||||
('stop_control_failed', ['stop'], False),
|
||||
)
|
||||
for label, finish_reasons, stop_succeeded in cases:
|
||||
with self.subTest(label=label):
|
||||
self.accumulator.finish_reasons = finish_reasons
|
||||
self.stop_succeeded = stop_succeeded
|
||||
|
||||
result = self.invoke()
|
||||
|
||||
self.assertEqual(result['answer'], body)
|
||||
self.assertEqual(result['status'], 'PARTIAL')
|
||||
self.assertFalse(result['answerQuality']['narrativeComplete'])
|
||||
self.assertEqual(result['finishReason'], 'incomplete')
|
||||
self.assertIn('自主调查未收到有效的正常结束信号。',
|
||||
result['answerQuality']['missingEvidence'])
|
||||
self.synthetic_writer.assert_not_called()
|
||||
|
||||
def test_recovered_tool_error_keeps_natural_stop_completion_without_fact_binding(self):
|
||||
self.native_status, self.native_reason = 'PARTIAL', 'mcp_error'
|
||||
body = '原生回答保留自己的局限。'
|
||||
self.accumulator.answer = body
|
||||
|
||||
result = self.invoke()
|
||||
|
||||
self.assertEqual(result['status'], 'COMPLETED')
|
||||
self.assertEqual(result['answer'], body)
|
||||
self.assertEqual(result['conclusionProtocolQueryIds'], ['query-current'])
|
||||
self.assertEqual(result['answerQuality']['backgroundEvidenceQueryIds'], ['query-current'])
|
||||
self.assertTrue(result['answerQuality']['narrativeComplete'])
|
||||
self.assertEqual(result['answerQuality']['narrativeFactBinding'], 'not_assessed')
|
||||
self.assertIsNone(result['factsComplete'])
|
||||
self.synthetic_writer.assert_not_called()
|
||||
|
||||
def test_no_explicit_refs_cannot_use_docs_without_verified_complete_scope_receipts(self):
|
||||
self.snapshot['scopeCoverage'] = None
|
||||
body = '正常原生正文不写证据编号。'
|
||||
self.accumulator.answer = body
|
||||
|
||||
result = self.invoke()
|
||||
|
||||
self.assertEqual(result['answer'], body)
|
||||
self.assertEqual(result['status'], 'PARTIAL')
|
||||
self.assertEqual(result['conclusionProtocolQueryIds'], [])
|
||||
self.assertEqual(result['answerQuality']['backgroundEvidenceQueryIds'], [])
|
||||
self.assertFalse(result['answerQuality']['dataComplete'])
|
||||
self.assertIn('本轮没有可关联的完整scope正式查询证明。',
|
||||
result['answerQuality']['missingEvidence'])
|
||||
self.synthetic_writer.assert_not_called()
|
||||
|
||||
def test_unbound_original_citation_is_a_gap_without_rewriting_the_body(self):
|
||||
body = '原生回答里保留未绑定的引用。[QABCDEF99]'
|
||||
self.accumulator.answer = body
|
||||
|
||||
result = self.invoke()
|
||||
|
||||
self.assertEqual(result['status'], 'PARTIAL')
|
||||
self.assertEqual(result['answer'], body)
|
||||
self.assertFalse(result['answerQuality']['dataComplete'])
|
||||
self.assertEqual(result['answerQuality']['unresolvedEvidenceRefs'], ['QABCDEF99'])
|
||||
self.assertIn('原文引用未关联本轮完整scope正式查询证据:QABCDEF99。',
|
||||
result['answerQuality']['missingEvidence'])
|
||||
self.assertNotIn('QABCDEF99', result['conclusionProtocolQueryIds'])
|
||||
self.synthetic_writer.assert_not_called()
|
||||
|
||||
def test_explicit_hexadecimal_query_reference_maps_only_its_receipt(self):
|
||||
hex_proof = proof('query-hex')
|
||||
self.snapshot['queries'].append({'proof': hex_proof})
|
||||
self.documents.append(document('QABCDEF12', hex_proof))
|
||||
body = '原文引用正式查询[QABCDEF12]。'
|
||||
self.accumulator.answer = body
|
||||
|
||||
result = self.invoke()
|
||||
|
||||
self.assertEqual(result['status'], 'COMPLETED')
|
||||
self.assertEqual(result['answer'], body)
|
||||
self.assertEqual(result['answerQuality']['citedEvidenceRefs'], ['QABCDEF12'])
|
||||
self.assertEqual(result['conclusionProtocolQueryIds'], ['query-hex'])
|
||||
self.synthetic_writer.assert_not_called()
|
||||
|
||||
def test_cancelled_turn_remains_cancelled_and_does_not_read_or_synthesize(self):
|
||||
for cancellation in ('event', 'native_status'):
|
||||
with self.subTest(cancellation=cancellation):
|
||||
self.cancel_event.clear()
|
||||
self.native_status, self.native_reason = 'COMPLETED', 'stop'
|
||||
if cancellation == 'event':
|
||||
self.cancel_event.set()
|
||||
else:
|
||||
self.native_status = 'CANCELLED'
|
||||
self.accumulator.answer = '中断前的草稿'
|
||||
|
||||
result = self.invoke()
|
||||
|
||||
self.assertEqual(result['status'], 'CANCELLED')
|
||||
self.assertEqual(result['answer'], '')
|
||||
self.delegated.call.assert_not_called()
|
||||
self.synthetic_writer.assert_not_called()
|
||||
|
||||
def test_server_coverage_gap_keeps_body_and_prevents_completed_status(self):
|
||||
self.snapshot['rootGoalGaps'] = ['亮片必答阶段尚无完整两期依据。']
|
||||
body = '原生结论及其局限。'
|
||||
self.accumulator.answer = body
|
||||
|
||||
result = self.invoke()
|
||||
|
||||
self.assertEqual(result['answer'], body)
|
||||
self.assertEqual(result['status'], 'PARTIAL')
|
||||
self.assertFalse(result['answerQuality']['dataComplete'])
|
||||
self.assertIn('亮片必答阶段尚无完整两期依据。', result['answerQuality']['missingEvidence'])
|
||||
self.synthetic_writer.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -216,6 +216,53 @@ class RuntimeStreamTests(unittest.TestCase):
|
||||
truncated.feed({"type": "finish", "finishReason": "length"})
|
||||
self.assertEqual(truncated.status(), ("PARTIAL", "length"))
|
||||
|
||||
def test_tool_errors_are_read_from_envelopes_not_business_data_cells(self):
|
||||
for flag in ('mcpValidationError','mcpAuthRequired'):
|
||||
stream=runtime.ConversationAccumulator()
|
||||
stream.feed({'type':'tool-input-available','toolName':'mcp_call','toolCallId':'q'})
|
||||
stream.feed({'type':'tool-output-available','toolCallId':'q','output':{flag:True,'server':'quality'}})
|
||||
stream.feed({'type':'text-delta','id':'final','delta':'尚未查到数据。'})
|
||||
stream.feed({'type':'finish','finishReason':'stop'})
|
||||
self.assertEqual(stream.tool_calls[0]['status'],'failed')
|
||||
self.assertEqual(stream.status(),('PARTIAL','mcp_error'))
|
||||
payload={'kind':'quality_records','rows':[{'error':'缺角','isError':True}], 'note':'{"error":"原始单元格内容"}'}
|
||||
stream=runtime.ConversationAccumulator()
|
||||
stream.feed({'type':'tool-input-available','toolName':'mcp_call','toolCallId':'q'})
|
||||
stream.feed({'type':'tool-output-available','toolCallId':'q','output':{'content':[{'type':'text','text':json.dumps(payload)}]}})
|
||||
stream.feed({'type':'text-delta','id':'final','delta':'已查询并保留原始字段。'})
|
||||
stream.feed({'type':'finish','finishReason':'stop'})
|
||||
self.assertEqual(stream.tool_calls[0]['status'],'completed')
|
||||
self.assertEqual(stream.status(),('COMPLETED','stop'))
|
||||
|
||||
def test_transport_done_is_not_a_normal_model_finish(self):
|
||||
stream = runtime.ConversationAccumulator()
|
||||
stream.feed({'type': 'text-delta', 'id': 'progress', 'delta': '先查一下。'})
|
||||
stream.feed({'type': 'tool-input-available', 'toolName': 'mcp_call', 'toolCallId': 'q'})
|
||||
stream.feed({'type': 'tool-output-available', 'toolCallId': 'q', 'output': {}})
|
||||
stream.feed({'type': 'finish', 'finishReason': 'tool-calls'})
|
||||
stream.feed({'type': '[DONE]'})
|
||||
self.assertNotEqual(stream.status()[0], 'COMPLETED')
|
||||
self.assertEqual(stream.answer, '先查一下。')
|
||||
|
||||
def test_progress_before_a_tool_or_unsettled_tool_cannot_count_as_final_answer(self):
|
||||
for settled in (False, True):
|
||||
stream = runtime.ConversationAccumulator()
|
||||
stream.feed({'type': 'text-delta', 'id': 'progress', 'delta': '正在查询。'})
|
||||
stream.feed({'type': 'tool-input-available', 'toolName': 'mcp_call', 'toolCallId': 'q'})
|
||||
if settled:stream.feed({'type': 'tool-output-available', 'toolCallId': 'q', 'output': {}})
|
||||
stream.feed({'type': 'finish', 'finishReason': 'stop'})
|
||||
self.assertNotEqual(stream.status()[0], 'COMPLETED')
|
||||
stream.feed({'type': 'text-delta', 'id': 'final', 'delta': '已核实的最终回答。'})
|
||||
self.assertEqual(stream.status()[0], 'COMPLETED' if settled else 'PARTIAL')
|
||||
|
||||
def test_only_the_terminal_finish_and_successful_stop_control_can_complete(self):
|
||||
for reasons, stopped in ((['stop', 'tool-calls'], None), (['stop'], False)):
|
||||
stream = runtime.ConversationAccumulator()
|
||||
stream.feed({'type': 'text-delta', 'id': 'answer', 'delta': '保留原文'})
|
||||
for reason in reasons:stream.feed({'type': 'finish', 'finishReason': reason})
|
||||
stream.feed({'type': '[DONE]'})
|
||||
self.assertNotEqual(stream.status(stop_succeeded=stopped)[0], 'COMPLETED')
|
||||
|
||||
def test_native_stop_controller_stops_before_closing_stream_on_cancel(self):
|
||||
calls = []
|
||||
response = FakeResponse()
|
||||
@@ -306,6 +353,28 @@ class RuntimeStreamTests(unittest.TestCase):
|
||||
self.assertEqual(result[2], "transport_or_stream_error")
|
||||
native_stop.assert_called_once_with(unittest.mock.ANY, "http://127.0.0.1:10000", "existing-native-id")
|
||||
|
||||
def test_an_already_finished_native_reply_cannot_be_cancelled_by_stale_no_progress_state(self):
|
||||
controls=[];ready=[];controller=runtime.NativeStopController
|
||||
def capture(*args):
|
||||
value=controller(*args);controls.append(value);return value
|
||||
class Response:
|
||||
def __enter__(self):return self
|
||||
def __exit__(self,*_):pass
|
||||
def close(self):pass
|
||||
def __iter__(self):
|
||||
yield b'data: {"type":"text-delta","id":"final","delta":"final reply"}\n'
|
||||
yield b'data: {"type":"finish","finishReason":"stop"}\n'
|
||||
ready.append(controls[0].completion_ready())
|
||||
yield b'data: [DONE]\n'
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root=Path(temp)/str(uuid.uuid4());root.mkdir();actor=root.name;sid=str(uuid.uuid4())
|
||||
runtime._atomic_json(root/'private/native-exploration-state.json',{'executionId':'e','halted':True})
|
||||
client=unittest.mock.Mock();client.open.return_value=Response()
|
||||
with patch.object(runtime,'NativeStopController',side_effect=capture),patch('nao_agent_task.task_from_context',return_value={'executionMode':'native_agent','freshQuery':True}):
|
||||
result=runtime._sse_request(client=client,base_url='http://native.invalid',model='fixture',question='q',release_id=str(uuid.uuid4()),
|
||||
context={'_nativeExecutionId':'e'},chat_id='chat',session_state=runtime.SessionState(root,actor),session_id=sid,actor_root=root,emit=lambda _:None,timeout=5)
|
||||
self.assertEqual(ready,[False]);self.assertEqual(result[1],'COMPLETED')
|
||||
|
||||
def test_story_export_uses_last_successful_call_and_matching_markdown(self):
|
||||
class StoryClient:
|
||||
def __init__(self):
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"""Exercise the native runner with isolated files and mocked upstream/bridge calls."""
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
@@ -10,8 +12,15 @@ from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
sys.path[:0] = [str(Path(__file__).resolve().parents[1] / 'scripts')]
|
||||
from nao_native_run import run_native_exploration
|
||||
PROJECT = Path(__file__).resolve().parents[1]
|
||||
sys.path[:0] = [str(PROJECT / 'scripts')]
|
||||
RUNTIME_PATH = Path(os.environ.get('NAO_ORIGINAL_BODY_PATH',
|
||||
str(PROJECT / 'scripts/nao_native_run.py'))).expanduser().resolve()
|
||||
RUNTIME_SPEC = importlib.util.spec_from_file_location('nao_native_run_integration', RUNTIME_PATH)
|
||||
RUNTIME_MODULE = importlib.util.module_from_spec(RUNTIME_SPEC)
|
||||
sys.modules[RUNTIME_SPEC.name] = RUNTIME_MODULE
|
||||
RUNTIME_SPEC.loader.exec_module(RUNTIME_MODULE)
|
||||
run_native_exploration = RUNTIME_MODULE.run_native_exploration
|
||||
from nao_quality_runtime import _atomic_json
|
||||
|
||||
|
||||
@@ -43,6 +52,18 @@ def document(ref, *proofs):
|
||||
|
||||
|
||||
class NativeRunTests(unittest.TestCase):
|
||||
def test_pretool_progress_cannot_be_promoted_by_a_stop_finish(self):
|
||||
from nao_quality_runtime import ConversationAccumulator
|
||||
self.accumulator=ConversationAccumulator()
|
||||
for event in ({'type':'text-delta','id':'progress','delta':'正在查询。'},
|
||||
{'type':'tool-input-available','toolName':'mcp_call','toolCallId':'q'},
|
||||
{'type':'tool-output-available','toolCallId':'q','output':{}},
|
||||
{'type':'finish','finishReason':'stop'}):self.accumulator.feed(event)
|
||||
result=self.invoke()
|
||||
self.assertEqual(result['status'],'PARTIAL')
|
||||
self.assertFalse(result['answerQuality']['narrativeComplete'])
|
||||
self.assertEqual(result['answer'],'正在查询。')
|
||||
|
||||
def test_optional_scope_notice_is_shown_once_without_internal_visual_diagnostics(self):
|
||||
child = {**self.task, 'stages': ['bright']}
|
||||
self.snapshot['scopes'].append({'nodeId': 'bright-detail', 'scopeId': 'bright-detail',
|
||||
@@ -54,31 +75,25 @@ class NativeRunTests(unittest.TestCase):
|
||||
'missingEvidence': ['节点bright-detail范围基础范围缺少bright来源具体缺陷重量图。']}
|
||||
result = self.invoke()
|
||||
self.assertEqual(result['status'], 'COMPLETED')
|
||||
self.assertEqual(result['readingSummary']['notices'],
|
||||
self.assertEqual(result['answerQuality']['notices'],
|
||||
['亮片细分缺陷尚未完整核实:当前范围;未用于已核实结论。'])
|
||||
self.assertNotIn('调查局限', result['answer'])
|
||||
self.assertNotIn('bright', result['answer'])
|
||||
stored = json.loads((self.actor_root / 'private/native-warning-diagnostics.json').read_text())
|
||||
self.assertIn('bright', stored['visualWarnings'][0])
|
||||
|
||||
def test_full_facts_remain_private_instead_of_being_appended_to_the_business_answer(self):
|
||||
self.final['fullEvidenceFacts'] = [{'text': '后台保留的完整统计事实', 'evidenceRef': 'Q00000001'}]
|
||||
def test_original_answer_is_not_replaced_by_a_generated_report(self):
|
||||
self.accumulator.answer = '原生回答原样保留,局限也照原文保留。'
|
||||
result = self.invoke()
|
||||
self.assertNotIn('完整统计依据', result['answer'])
|
||||
self.assertNotIn('后台保留的完整统计事实', result['answer'])
|
||||
stored = json.loads((self.actor_root / 'private/native-full-evidence-facts.json').read_text())
|
||||
self.assertEqual(stored, self.final['fullEvidenceFacts'])
|
||||
self.assertEqual(result['answer'], self.accumulator.answer)
|
||||
self.assertIsNone(result['readingSummary'])
|
||||
self.synthesis.assert_not_called()
|
||||
|
||||
def test_issued_binding_catalog_remains_private_for_exact_replay(self):
|
||||
issued = {'bindingInventory': {'N17': {'factId': 'F2', 'value': '493.9966', 'unit': 'kg'}},
|
||||
'facts': [{'id': 'F2', 'rawValue': '493.99660000'}]}
|
||||
self.final['_privateBindingInput'] = issued
|
||||
def test_no_second_composition_artifact_is_written(self):
|
||||
result = self.invoke()
|
||||
stored = json.loads((self.actor_root / 'private/native-composition.json').read_text())
|
||||
self.assertEqual(stored['bindingInput'], issued)
|
||||
self.assertNotIn('_privateBindingInput', result)
|
||||
self.assertNotIn('bindingInput', result)
|
||||
self.assertNotIn('bindingInventory', json.dumps(self.events, ensure_ascii=False))
|
||||
self.assertEqual(result['answer'], self.accumulator.answer)
|
||||
self.assertFalse((self.actor_root / 'private/native-composition.json').exists())
|
||||
self.synthesis.assert_not_called()
|
||||
|
||||
def setUp(self):
|
||||
self.folder = tempfile.TemporaryDirectory()
|
||||
@@ -105,11 +120,6 @@ class NativeRunTests(unittest.TestCase):
|
||||
'scopeCoverage': [{'nodeId': 'root', 'scopeId': 'scope-root', 'complete': True},
|
||||
{'nodeId': 'group', 'scopeId': 'scope-group', 'complete': True}],
|
||||
'rootGoalGaps': [], 'gaps': [], 'pending': [], 'explorationWarnings': []}
|
||||
self.final = {'answer': '按已核实结果解释[Q00000001]', 'reportTitle': '质量数据分析',
|
||||
'readingSummary': {'version': 1, 'lead': '已核实解释[Q00000001]',
|
||||
'evidence': [], 'notices': [], 'evidenceRefs': ['Q00000001']},
|
||||
'usedEvidenceRefs': ['Q00000001'], 'evidenceSufficient': True,
|
||||
'missingEvidence': [], 'rawModelResponses': [], 'compositionDiagnostics': {}}
|
||||
self.accumulator = SimpleNamespace(answer='原生草稿', finish_reasons=['stop'],
|
||||
tool_calls=[{'tool': 'quality_data', 'status': 'failed', 'input': {'mode': 'compare'}},
|
||||
{'tool': 'quality_data', 'status': 'completed', 'input': {'mode': 'compare'}}],
|
||||
@@ -127,7 +137,7 @@ class NativeRunTests(unittest.TestCase):
|
||||
self.read_evidence = stack.enter_context(patch('nao_evidence_finalizer.evidence_summaries',
|
||||
side_effect=lambda *args, **kwargs: copy.deepcopy(self.documents)))
|
||||
self.synthesis = stack.enter_context(patch('nao_evidence_finalizer.synthesize_native',
|
||||
side_effect=lambda **kwargs: copy.deepcopy(self.final)))
|
||||
side_effect=AssertionError('native-agent original body must not be synthesized')))
|
||||
self.visuals = stack.enter_context(patch('analysis_visual_evidence.protocol_visual_result',
|
||||
return_value={'visualState': 'not_requested', 'visuals': [], 'missingEvidence': []}))
|
||||
stack.enter_context(patch('nao_runtime_policy.native_timeout', return_value=30))
|
||||
@@ -161,8 +171,12 @@ class NativeRunTests(unittest.TestCase):
|
||||
|
||||
self.assertTrue(result['evidenceCompletion']['serverCoverageSufficient'])
|
||||
self.assertEqual(result['timeline'], self.accumulator.timeline)
|
||||
self.assertEqual(result['conclusionProtocolQueryIds'], ['query-current', 'query-compare'])
|
||||
self.assertIn(self.snapshot['explorationWarnings'][0], result['readingSummary']['notices'])
|
||||
self.assertEqual(result['conclusionProtocolQueryIds'],
|
||||
['query-current', 'query-compare', 'query-group'])
|
||||
self.assertEqual(result['answerQuality']['citedEvidenceRefs'], [])
|
||||
self.assertEqual(result['answerQuality']['narrativeFactBinding'], 'not_assessed')
|
||||
self.assertIn(self.snapshot['explorationWarnings'][0], result['answerQuality']['notices'])
|
||||
self.assertEqual(result['answer'], self.accumulator.answer)
|
||||
self.assertIn('firstUsefulMs', result['phaseTimingsMs'])
|
||||
self.assertGreaterEqual(result['phaseTimingsMs']['firstUsefulMs'], 30)
|
||||
self.delegated.call.assert_called_once_with('/api/analysis/protocol/queries', payload={}, method='POST')
|
||||
@@ -172,35 +186,33 @@ class NativeRunTests(unittest.TestCase):
|
||||
self.assertIsNone(self.sse.call_args.kwargs['chat_id'])
|
||||
stored = json.loads((self.actor_root / 'private/native-completion.json').read_text())
|
||||
self.assertEqual(stored['status'], 'COMPLETED')
|
||||
self.assertEqual(stored['answer'], self.accumulator.answer)
|
||||
self.assertEqual(self.events[-1], result)
|
||||
|
||||
def test_generated_chart_contract_is_available_before_the_single_synthesis(self):
|
||||
def test_generated_chart_contract_uses_formal_query_evidence_without_rewriting_answer(self):
|
||||
self.task['visualPreference']='required'
|
||||
self.visuals.return_value={'visualState':'ready','missingEvidence':[], 'visuals':[{
|
||||
'id':'actual-chart','type':'line','metric':'composite_rate','title':'正式趋势',
|
||||
'scope':{'department':'当前产业部'},'period':{'year':2026,'month':9},
|
||||
'categories':[{'key':'2026-09'}],'series':[{'values':[.95]}],
|
||||
'evidenceRefs':['Q00000001']}]}
|
||||
def synthesize(**kwargs):
|
||||
preview=kwargs['context']['_platformVisuals']
|
||||
self.assertEqual(preview['visualState'],'ready')
|
||||
self.assertEqual(preview['charts'][0]['id'],'actual-chart')
|
||||
self.assertEqual(preview['charts'][0]['evidenceRefs'],['Q00000001'])
|
||||
self.assertEqual(preview['charts'][0]['pointCount'],1)
|
||||
self.assertNotIn('series',preview['charts'][0])
|
||||
return copy.deepcopy(self.final)
|
||||
self.synthesis.side_effect=synthesize
|
||||
result=self.invoke()
|
||||
self.assertEqual(result['status'],'COMPLETED')
|
||||
self.visuals.assert_called_once();self.synthesis.assert_called_once()
|
||||
self.visuals.assert_called_once()
|
||||
self.assertEqual(self.visuals.call_args.args[0], self.documents)
|
||||
self.assertEqual(result['visuals'][0]['id'], 'actual-chart')
|
||||
self.assertEqual(result['visuals'][0]['evidenceRefs'], ['Q00000001'])
|
||||
self.assertEqual(result['answer'], self.accumulator.answer)
|
||||
self.synthesis.assert_not_called()
|
||||
|
||||
def test_root_gap_remains_partial_even_with_stop_and_available_evidence(self):
|
||||
self.snapshot['rootGoalGaps'] = ['亮片必答阶段尚无完整两期依据。']
|
||||
result = self.invoke()
|
||||
self.assertEqual(result['status'], 'PARTIAL')
|
||||
self.assertFalse(result['evidenceCompletion']['serverCoverageSufficient'])
|
||||
self.assertIn(self.snapshot['rootGoalGaps'][0], result['answer'])
|
||||
self.assertIn(self.snapshot['rootGoalGaps'][0], result['readingSummary']['notices'])
|
||||
self.assertEqual(result['answer'], self.accumulator.answer)
|
||||
self.assertIn(self.snapshot['rootGoalGaps'][0], result['evidenceCompletion']['missingEvidence'])
|
||||
self.assertIn(self.snapshot['rootGoalGaps'][0], result['answerQuality']['missingEvidence'])
|
||||
|
||||
def test_three_no_progress_attempts_remain_partial_after_natural_stop(self):
|
||||
_atomic_json(self.actor_root / 'private/native-exploration-state.json',
|
||||
@@ -210,7 +222,8 @@ class NativeRunTests(unittest.TestCase):
|
||||
self.assertEqual(result['status'], 'PARTIAL')
|
||||
self.assertTrue(any('连续三次' in gap for gap in result['evidenceCompletion']['missingEvidence']))
|
||||
self.assertEqual(result['phaseTimingsMs']['formalQuery'], 1234)
|
||||
self.assertTrue(any('连续三次' in notice for notice in result['readingSummary']['notices']))
|
||||
self.assertTrue(any('连续三次' in gap for gap in result['answerQuality']['missingEvidence']))
|
||||
self.assertEqual(result['answer'], self.accumulator.answer)
|
||||
|
||||
def test_controlled_no_progress_stop_does_not_add_generic_tool_failure(self):
|
||||
_atomic_json(self.actor_root / 'private/native-exploration-state.json',
|
||||
@@ -233,7 +246,7 @@ class NativeRunTests(unittest.TestCase):
|
||||
self.assertEqual(result['status'], 'PARTIAL')
|
||||
self.assertTrue(any('未正常结束' in gap for gap in result['evidenceCompletion']['missingEvidence']))
|
||||
|
||||
def test_only_complete_current_scope_documents_reach_synthesis(self):
|
||||
def test_only_complete_current_scope_documents_reach_visual_generation_and_result(self):
|
||||
self.snapshot['queries'].extend([{'proof': self.p_failed}, {'proof': self.p_old}])
|
||||
self.snapshot['scopeCoverage'].append(
|
||||
{'nodeId': 'failed', 'scopeId': 'scope-failed', 'complete': False})
|
||||
@@ -245,27 +258,52 @@ class NativeRunTests(unittest.TestCase):
|
||||
{'evidenceRef': 'Q00000007', 'result': {'summary': {'unproved': True}}},
|
||||
])
|
||||
result = self.invoke()
|
||||
admitted = self.synthesis.call_args.kwargs['evidence']
|
||||
admitted = self.visuals.call_args.args[0]
|
||||
self.assertEqual([doc['evidenceRef'] for doc in admitted], ['Q00000001', 'Q00000002'])
|
||||
self.assertEqual(result['queryEvidenceRefs'], ['Q00000001', 'Q00000002'])
|
||||
self.assertEqual(result['conclusionProtocolQueryIds'],
|
||||
['query-current', 'query-compare', 'query-group'])
|
||||
self.assertNotIn('query-failed', result['conclusionProtocolQueryIds'])
|
||||
self.assertNotIn('query-old', result['conclusionProtocolQueryIds'])
|
||||
self.assertNotIn('query-not-in-current-receipts', result['conclusionProtocolQueryIds'])
|
||||
self.assertEqual(result['answer'], self.accumulator.answer)
|
||||
self.read_evidence.assert_called_once_with(self.actor_root / 'evidence', RELEASE,
|
||||
exclude_files={'prior-evidence.json'}, allow_empty=True)
|
||||
self.synthesis.assert_not_called()
|
||||
|
||||
def test_used_refs_map_only_to_actual_current_proofs_not_unused_or_foreign_documents(self):
|
||||
def test_original_citations_map_only_to_actual_current_query_proofs(self):
|
||||
self.snapshot['queries'].append({'proof': self.p_old})
|
||||
self.documents.append(document('Q00000003', self.p_old))
|
||||
self.final['usedEvidenceRefs'] = ['Q00000001', 'Q00000003', 'QDEADBEEF', 'Q00000001']
|
||||
self.accumulator.answer = '原文引用当前证据[Q00000001],以及外部证据[Q00000003]。'
|
||||
result = self.invoke()
|
||||
self.assertEqual(result['conclusionProtocolQueryIds'], ['query-current', 'query-compare'])
|
||||
self.assertEqual(result['answer'], self.accumulator.answer)
|
||||
self.assertEqual(result['answerQuality']['unresolvedEvidenceRefs'], ['Q00000003'])
|
||||
self.assertEqual(result['status'], 'PARTIAL')
|
||||
self.assertNotIn('query-group', result['conclusionProtocolQueryIds'])
|
||||
self.assertNotIn('query-old', result['conclusionProtocolQueryIds'])
|
||||
|
||||
def test_claimed_sufficient_answer_without_current_cited_proof_remains_partial(self):
|
||||
self.final['usedEvidenceRefs'] = ['QDEADBEEF']
|
||||
def test_uppercase_hexadecimal_reference_maps_to_its_actual_receipt(self):
|
||||
hexadecimal = proof('query-hexadecimal')
|
||||
self.snapshot['queries'].append({'proof': hexadecimal})
|
||||
self.documents.append(document('QABCDEF12', hexadecimal))
|
||||
self.accumulator.answer = '原文显式引用[QABCDEF12]。'
|
||||
|
||||
result = self.invoke()
|
||||
|
||||
self.assertEqual(result['status'], 'COMPLETED')
|
||||
self.assertEqual(result['answer'], self.accumulator.answer)
|
||||
self.assertEqual(result['conclusionProtocolQueryIds'], ['query-hexadecimal'])
|
||||
self.assertEqual(result['answerQuality']['citedEvidenceRefs'], ['QABCDEF12'])
|
||||
|
||||
def test_unbound_original_citation_remains_a_metadata_gap(self):
|
||||
self.accumulator.answer = '原生回答的引用[QABCDEF99]仍按原文保留。'
|
||||
result = self.invoke()
|
||||
self.assertEqual(result['status'], 'PARTIAL')
|
||||
self.assertEqual(result['conclusionProtocolQueryIds'], [])
|
||||
self.assertTrue(any('实际查询证明' in gap for gap in result['evidenceCompletion']['missingEvidence']))
|
||||
self.assertEqual(result['answer'], self.accumulator.answer)
|
||||
self.assertEqual(result['answerQuality']['unresolvedEvidenceRefs'], ['QABCDEF99'])
|
||||
self.assertTrue(any('QABCDEF99' in gap for gap in result['evidenceCompletion']['missingEvidence']))
|
||||
|
||||
def test_cancelled_native_turn_never_reads_query_snapshot_or_synthesizes(self):
|
||||
for cancellation in ('event', 'native_status'):
|
||||
@@ -295,12 +333,12 @@ class NativeRunTests(unittest.TestCase):
|
||||
self.assertNotIn('图表尚未完整生成,可独立恢复。', result['answer'])
|
||||
self.assertNotIn('结果为部分完成', result['answer'])
|
||||
self.assertNotIn('共有15张图表', result['answer'])
|
||||
self.assertEqual(result['readingSummary']['notices'],
|
||||
self.assertEqual(result['answerQuality']['notices'],
|
||||
['部分重点图表未能完整展示;已保留核实文字和表格。'])
|
||||
else:
|
||||
self.assertIn('图表尚未完整生成,可独立恢复。', result['answer'])
|
||||
self.assertIn('图表尚未完整生成,可独立恢复。', result['readingSummary']['notices'])
|
||||
self.assertIn('结果为部分完成', result['answer'])
|
||||
self.assertNotIn('图表尚未完整生成,可独立恢复。', result['answer'])
|
||||
self.assertNotIn('结果为部分完成', result['answer'])
|
||||
self.assertIn('图表尚未完整生成,可独立恢复。', result['answerQuality']['missingEvidence'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
"""普通对话通过真实协议执行入口,不启动数据查询或二次模型生成。"""
|
||||
import json,sys,tempfile,threading,unittest,uuid
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock,patch
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts'))
|
||||
from nao_agent_task import normalize_task
|
||||
from nao_protocol_execution import execute
|
||||
class ProtocolConversationTests(unittest.TestCase):
|
||||
def invoke(self,cancel=False,context=None):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root=Path(temp);(root/'private').mkdir();(root/'evidence').mkdir();prior=root/'private/last-agent-task.json';prior.write_text('{"task":"prior business"}');before=prior.read_bytes()
|
||||
raw={'kind':'explain','goal':'回应问候','directResponse':{'purpose':'greeting','answer':'你好!我可以协助你查询质量指标并比较期间变化。','requiresMemory':False}}
|
||||
task=normalize_task(raw,'你好',context)
|
||||
request={key:str(uuid.uuid4()) for key in ['turnId','sessionId','releaseId','actorId']};request['question']='你好';request['context']=context or {}
|
||||
authority={key:request[key] for key in ['turnId','sessionId']};authority.update(attemptId=str(uuid.uuid4()),executionId=str(uuid.uuid4()),revision=1)
|
||||
delegated=Mock();delegated.call.side_effect=AssertionError('ordinary conversation cannot read business data');events=[];event=threading.Event()
|
||||
if cancel:event.set()
|
||||
with patch('nao_evidence_finalizer.synthesize',side_effect=AssertionError('must keep the confirmed model reply')),patch('analysis_visual_evidence.visual_result',side_effect=AssertionError('no charts for a greeting')):
|
||||
if cancel:
|
||||
with self.assertRaises(RuntimeError):execute(request=request,task=task,authority=authority,actor_root=root,delegated=delegated,connection=('https://offline.invalid','synthetic','fixture'),cancel_event=event,emit=events.append)
|
||||
self.assertEqual(events,[])
|
||||
else:
|
||||
result=execute(request=request,task=task,authority=authority,actor_root=root,delegated=delegated,connection=('https://offline.invalid','synthetic','fixture'),cancel_event=event,emit=events.append)
|
||||
self.assertEqual(result['status'],'COMPLETED');self.assertEqual(result['answer'],raw['directResponse']['answer']);self.assertEqual(result['completionMethod'],'direct_conversation')
|
||||
self.assertEqual(result['protocol'],authority);self.assertEqual(result['protocolEvidence'],[]);self.assertEqual(result['queryEvidenceRefs'],[]);self.assertEqual(result['visuals'],[])
|
||||
self.assertTrue((root/'private/non-query-turns'/(request['turnId']+'.json')).exists())
|
||||
self.assertEqual(result['agentContext'],{key:value for key,value in request['context'].items() if key in ('releaseId','period','comparisonPeriod','filters')})
|
||||
delegated.call.assert_not_called();self.assertEqual(prior.read_bytes(),before)
|
||||
def test_greeting_keeps_the_model_reply_without_period_or_queries(self):self.invoke()
|
||||
def test_acknowledgement_keeps_the_existing_business_frame(self):self.invoke(context={'period':{'year':2026,'month':9},'filters':{'group':'G'}})
|
||||
def test_cancelled_conversation_does_not_publish(self):self.invoke(cancel=True)
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -4,6 +4,7 @@ import { Alert, App, Button, Form, Input, Modal, Select, Spin, Switch, Tag } fro
|
||||
import { SettingOutlined } from '@ant-design/icons';
|
||||
import { api } from './api';
|
||||
import { effectiveThinkingEffort, supportsThinkingEffort } from './analysisThinking';
|
||||
import { useDelayedIndicator } from './useDelayedBusy';
|
||||
|
||||
export type AnalysisModelProfile = { id: string; name: string; baseUrl: string; model: string; hasApiKey: boolean; thinkingEnabled: boolean; thinkingEffort: string };
|
||||
export type AnalysisModelSettings = { baseUrl: string; model: string; hasApiKey: boolean; revision: string; activeProfileId: string; thinkingEnabled: boolean; thinkingEffort: string; profiles: AnalysisModelProfile[] };
|
||||
@@ -19,6 +20,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
||||
useEffect(() => { if (!effortSupported) form.setFieldValue('thinkingEffort', 'auto'); }, [effortSupported, form]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const showLoading = useDelayedIndicator(loading, 150);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [testing, setTesting] = useState(false);
|
||||
const [settings, setSettings] = useState<AnalysisModelSettings>();
|
||||
@@ -26,10 +28,11 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
||||
const selectedProfile = settings?.profiles.find(profile => profile.id === profileId);
|
||||
const [notice, setNotice] = useState<{ type: 'success' | 'error'; text: string }>();
|
||||
const sequence = useRef(0);
|
||||
const submitLock = useRef(false);
|
||||
const close = () => { if (saving) return; sequence.current += 1; setOpen(false); form.resetFields(); setNotice(undefined); setTesting(false); };
|
||||
const load = async () => {
|
||||
const current = ++sequence.current;
|
||||
setOpen(true); setLoading(true); setSettings(undefined); setProfileId(undefined); setNotice(undefined); form.resetFields();
|
||||
setOpen(true); setLoading(true); setNotice(undefined);
|
||||
try {
|
||||
const value = await api.analysisSettings();
|
||||
if (sequence.current !== current) return;
|
||||
@@ -39,9 +42,10 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
||||
} finally { if (sequence.current === current) setLoading(false); }
|
||||
};
|
||||
const submit = async (test: boolean) => {
|
||||
if (!settings) return;
|
||||
if (!settings || submitLock.current) return;
|
||||
let values: AnalysisModelSettingsInput;
|
||||
try { values = await form.validateFields(); } catch { return; }
|
||||
submitLock.current = true;
|
||||
const current = sequence.current;
|
||||
setNotice(undefined); test ? setTesting(true) : setSaving(true);
|
||||
try {
|
||||
@@ -57,7 +61,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
||||
}
|
||||
} catch (error) {
|
||||
if (sequence.current === current && !onUnauthorized(error)) setNotice({ type: 'error', text: error instanceof Error ? error.message : '操作失败,请重试' });
|
||||
} finally { if (sequence.current === current) { setTesting(false); setSaving(false); } }
|
||||
} finally { submitLock.current = false; if (sequence.current === current) { setTesting(false); setSaving(false); } }
|
||||
};
|
||||
return <>
|
||||
<Button type="text" size="small" icon={<SettingOutlined />} onClick={() => void load()}>API 配置</Button>
|
||||
@@ -66,7 +70,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
||||
<Button loading={testing} disabled={loading || saving || !settings} onClick={() => void submit(true)}>测试连接</Button>
|
||||
<Button type="primary" loading={saving} disabled={loading || testing || !settings} onClick={() => void submit(false)}>保存并使用</Button>
|
||||
</>}>
|
||||
{loading ? <div style={{ padding: 32, textAlign: 'center' }}><Spin /></div> : <>
|
||||
{showLoading && !settings ? <div style={{ padding: 32, textAlign: 'center' }}><Spin /></div> : <>
|
||||
{settings && <div style={{ marginBottom: 20 }}>
|
||||
<div style={{ marginBottom: 8 }}>选择配置 <Tag color="blue">当前使用:{settings.profiles.find(profile => profile.id === settings.activeProfileId)?.name || settings.model}</Tag></div>
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
|
||||
@@ -21,7 +21,7 @@ export function AnalysisConclusion({ reading, visuals, renderVisuals }: {
|
||||
<div className="analysis-comparison-previous"><span>{comparison.previousLabel}</span><strong>{comparison.previous}</strong></div>
|
||||
<span className="analysis-comparison-arrow" aria-hidden="true">→</span>
|
||||
<div className="analysis-comparison-current"><span>{comparison.currentLabel}</span><strong>{comparison.current}</strong></div>
|
||||
<div className={`analysis-comparison-change ${/下降|降低/.test(comparison.direction) ? 'is-worse' : 'is-better'}`}><strong>{comparison.direction} {comparison.change}</strong><span>{comparison.unit}</span></div>
|
||||
<div className={`analysis-comparison-change ${/下降|降低/.test(comparison.direction) ? 'is-worse' : 'is-better'}`}><strong>{comparison.change}</strong><span>{comparison.unit} · {comparison.direction}</span></div>
|
||||
</div>
|
||||
</div>}
|
||||
{section.markdown && <AiMarkdown className="ai-answer" content={section.markdown} layout="sections" />}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { originalAnalysisBody } from './analysisOriginalBody';
|
||||
import { AnalysisOriginalContent } from './AnalysisOriginalContent';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Button } from 'antd';
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
@@ -103,6 +105,7 @@ export function AnalysisNarrative({ answer, visuals, visualState, question, turn
|
||||
reveal(); window.addEventListener('hashchange', reveal);
|
||||
return () => window.removeEventListener('hashchange', reveal);
|
||||
}, [model.evidence, prefix]);
|
||||
const original = originalAnalysisBody(turn);
|
||||
const primaryIds = new Set(primaryVisuals.map(visual => visual.id));
|
||||
const compact = (visual: AnalysisVisual) => !reading.hasAppendix && useCompactRateComparison(visual, question);
|
||||
const comparisons = model.sections.flatMap(section => section.visuals).filter(compact);
|
||||
@@ -130,7 +133,7 @@ export function AnalysisNarrative({ answer, visuals, visualState, question, turn
|
||||
<NarrativeEvidence model={model} prefix={prefix} />
|
||||
</>;
|
||||
return <div className={`analysis-narrative ${comparisons.length ? 'has-comparisons' : ''}`}>
|
||||
{reading.hasAppendix ? <AnalysisConclusion reading={reading} visuals={primaryVisuals} renderVisuals={figures => <AnalysisVisuals visuals={figures} visualState="ready" beforeExport={beforeExport} embedded hideEvidence combineStages={false} />} /> : fullContent}
|
||||
{original ? <AnalysisOriginalContent answer={original.answer} visuals={model.sections.flatMap(section => section.visuals)} renderVisuals={figures => <AnalysisVisuals visuals={figures} visualState="ready" beforeExport={beforeExport} embedded hideEvidence combineStages={false} />} /> : reading.hasAppendix ? <AnalysisConclusion reading={reading} visuals={primaryVisuals} renderVisuals={figures => <AnalysisVisuals visuals={figures} visualState="ready" beforeExport={beforeExport} embedded hideEvidence combineStages={false} />} /> : fullContent}
|
||||
{turn && drilldown && <AnalysisProductDrilldown turn={turn} selection={drilldown} onClose={() => setDrilldown(null)} />}
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
import { originalAnalysisSections } from './analysisOriginalBody';
|
||||
import type { AnalysisVisual } from './analysisVisualsModel';
|
||||
export function AnalysisOriginalContent({ answer, visuals, renderVisuals }: {
|
||||
answer: string; visuals: AnalysisVisual[]; renderVisuals: (visuals: AnalysisVisual[]) => ReactNode;
|
||||
}) {
|
||||
return <div className="analysis-original-document">{originalAnalysisSections(answer, visuals).map(section =>
|
||||
<section key={section.id} data-original-section={section.id}>
|
||||
{section.markdown.trim() && <AiMarkdown content={section.markdown} className="ai-answer" />}
|
||||
{!!section.visuals.length && renderVisuals(section.visuals)}
|
||||
</section>)}</div>;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Spin } from 'antd';
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { CheckCircleOutlined, CloseCircleOutlined, ClockCircleOutlined, RightOutlined } from '@ant-design/icons';
|
||||
import { analysisIsRunning, compactAnalysisTimeline, duplicatesFinalAnalysisAnswer } from './analysisConversationState';
|
||||
import { analysisIsRunning, compactAnalysisTimeline } from './analysisConversationState';
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
import { sanitizeAnalysisDisplayText } from './analysisDisplayText';
|
||||
import { AnalysisThinkingBlock } from './ModelThinkingPanel';
|
||||
@@ -45,32 +45,32 @@ export function AnalysisProcess({ turn, metadata }: { turn: Record<string, unkno
|
||||
const running = analysisIsRunning(turn.status || result.status);
|
||||
const raw = turn.timeline || result.timeline || plan.timeline;
|
||||
const timeline = compactAnalysisTimeline(Array.isArray(raw) ? raw.map(record) : []);
|
||||
const answer = String(result.answer || turn.answer || '');
|
||||
const rawSteps = turn.steps || result.steps || plan.steps;
|
||||
const steps = Array.isArray(rawSteps) ? rawSteps.map(record) : [];
|
||||
const fallback = steps.map((step, index) => ({ ...step, kind: 'tool', sequence: index, at: step.startedAt, hasResult: ['completed', 'failed'].includes(String(step.status)) }));
|
||||
const events = groupAdjacentThinking(orderedAnalysisProcess(turn, timeline.length ? timeline : fallback));
|
||||
const turnId = String(turn.id || turn.turnId || '');
|
||||
const [open, setOpen] = useState(false);
|
||||
const [open, setOpen] = useState(running);
|
||||
const previous = useRef({ turnId, running });
|
||||
const visibleOpen = previous.current.turnId === turnId && open;
|
||||
const visibleOpen = previous.current.turnId !== turnId ? running : previous.current.running && !running ? false : open;
|
||||
useEffect(() => {
|
||||
const changedTurn = previous.current.turnId !== turnId;
|
||||
const completed = previous.current.running && !running;
|
||||
if (changedTurn || completed) setOpen(false);
|
||||
if (changedTurn || !previous.current.running && running) setOpen(running);
|
||||
else if (completed) setOpen(false);
|
||||
previous.current = { turnId, running };
|
||||
}, [running, turnId]);
|
||||
const content = events.map(entry => {
|
||||
if (entry.kind === 'thinking') return <AnalysisThinkingBlock key={String(entry.key)} entry={entry as unknown as ModelThinking} running={running} />;
|
||||
const text = sanitizeAnalysisDisplayText(String(entry.text || ''));
|
||||
if (entry.kind === 'assistant') {
|
||||
if (!text.trim() || !running && entry.sequence === timeline.at(-1)?.sequence && timeline.at(-1)?.kind === 'assistant' && duplicatesFinalAnalysisAnswer(text, answer)) return null;
|
||||
if (!running || !text.trim()) return null;
|
||||
return <div className="analysis-answer analysis-event-note" key={String(entry.key)}><AiMarkdown content={text} className="ai-answer" /></div>;
|
||||
}
|
||||
const step = steps.find(item => item.toolCallId && item.toolCallId === entry.toolCallId);
|
||||
return <ToolCall key={String(entry.key)} entry={{ ...entry, ...(step?.recovered ? { recovered: true, text: step.outputSummary || '调整调用后已重试成功' } : {}) }} running={running} />;
|
||||
});
|
||||
if (!events.length) return <>{metadata}{running && <p className="analysis-chat-notice" role="status">{sanitizeAnalysisDisplayText(String(turn.progressMessage || plan.progressMessage || '正在准备分析…'))}</p>}</>;
|
||||
if (!events.length) return <>{metadata}</>;
|
||||
return <details className="analysis-process-history analysis-agent-process" open={visibleOpen} onToggle={event => setOpen(event.currentTarget.open)}>
|
||||
<summary aria-label={running ? '分析运行信息,展开分析过程' : '分析运行信息,展开已保存过程'}>{metadata || <span>{running ? '分析中' : '已完成'}</span>}<RightOutlined aria-hidden="true" /></summary>
|
||||
<div className="analysis-agent-stream" aria-label={running ? '实时分析对话' : '已保存的分析过程'}>{content}</div>
|
||||
|
||||
@@ -18,6 +18,7 @@ import { resolveAnalysisReportTitle, stripDuplicateFirstMarkdownH1 } from './ana
|
||||
import { useReportVisualImages, type ReportVisualImage } from './AnalysisReportVisuals';
|
||||
import { analysisMemberListFullyRead, analysisMemberListPeriod, parseAnalysisMemberList } from './analysisMembersModel';
|
||||
import { AnalysisRecordListReport, appendAnalysisRecordReportHtml } from './AnalysisRecordList';
|
||||
import { useDelayedIndicator } from './useDelayedBusy';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
const record = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||
@@ -219,6 +220,7 @@ function ReportExportDialog({ turn, reportMarkdown, reportHtml, native = false }
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const showExporting = useDelayedIndicator(exporting, 150);
|
||||
const [progress, setProgress] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [stamp, setStamp] = useState('');
|
||||
@@ -239,6 +241,7 @@ function ReportExportDialog({ turn, reportMarkdown, reportHtml, native = false }
|
||||
const currentExport = useRef({ open, turnId, snapshot, reportHtml, reportMarkdown });
|
||||
currentExport.current = { open, turnId, snapshot, reportHtml, reportMarkdown };
|
||||
const visualReport = useReportVisualImages(turn, open);
|
||||
const showVisualLoading = useDelayedIndicator(visualReport.loading, 150);
|
||||
const safeHtml = useMemo(() => {
|
||||
if (parseServerReadingSummary(reportTurn)) return '';
|
||||
if (!reportHtml?.trim()) return '';
|
||||
@@ -358,10 +361,10 @@ function ReportExportDialog({ turn, reportMarkdown, reportHtml, native = false }
|
||||
: <Button disabled={disabled} onClick={() => void saveHtml()}>下载 HTML</Button>}
|
||||
{prepared
|
||||
? <Button type="primary" disabled={disabled} onClick={() => void downloadPrepared(prepared, 'image')}>下载长图</Button>
|
||||
: <Button type="primary" loading={exporting} disabled={disabled} onClick={() => void prepareImages()}>下载长图</Button>}
|
||||
: <Button type="primary" loading={showExporting} disabled={disabled} onClick={() => void prepareImages()}>下载长图</Button>}
|
||||
</>}>
|
||||
{visualReport.loading && <p role="status">{visualReport.progress || '正在准备报告图表…'}</p>}
|
||||
{progress && <p className="analysis-report-export-status" role="status" aria-live="polite">{progress}</p>}
|
||||
{showVisualLoading && <p role="status">{visualReport.progress || '正在准备报告图表…'}</p>}
|
||||
{progress && (!exporting || showExporting) && <p className="analysis-report-export-status" role="status" aria-live="polite">{progress}</p>}
|
||||
{error && <Alert className="analysis-report-export-error" type="error" showIcon title={error} closable onClose={() => setError('')} />}
|
||||
{visualReport.failed && <Alert type="warning" showIcon title="部分图表未生成,报告保留相应数据表。" />}
|
||||
{visualReport.authorizationError && visualReport.authorizationError !== error && <Alert type="error" showIcon title={visualReport.authorizationError} />}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { originalAnalysisBody } from './analysisOriginalBody';
|
||||
import { AnalysisOriginalContent } from './AnalysisOriginalContent';
|
||||
import { useMemo } from 'react';
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
import { AnalysisConclusion } from './AnalysisConclusion';
|
||||
@@ -15,6 +17,7 @@ export function AnalysisReportNarrative({ turn, answer, images }: { turn: Row; a
|
||||
const { model, reading, primaryVisuals } = useMemo(() => buildAnalysisReadingModel(answer, visuals, String(turn.question || ''), turn), [answer, signature, turn]);
|
||||
const prefix = `report-${String(turn.id || turn.turnId || 'answer').replace(/[^a-zA-Z0-9_-]/g, '')}-`;
|
||||
const text = (content: string) => <AiMarkdown content={content} evidenceLabels={model.evidenceLabels} evidencePrefix={prefix} />;
|
||||
const original = originalAnalysisBody(turn);
|
||||
const primaryIds = new Set(primaryVisuals.map(visual => visual.id));
|
||||
const complete = <>
|
||||
{model.sections.filter(section => !primaryIds.size || section.narrative || section.tables.length || section.focusProducts?.length || section.visuals.some(visual => !primaryIds.has(visual.id))).map(section => <section key={section.id} id={`${prefix}${section.id}`} className={`analysis-narrative-section is-${section.kind}`} data-section-kind={section.kind}>
|
||||
@@ -30,7 +33,7 @@ export function AnalysisReportNarrative({ turn, answer, images }: { turn: Row; a
|
||||
<NarrativeEvidence model={model} prefix={prefix} />
|
||||
</>;
|
||||
return <div className="analysis-narrative report-narrative">
|
||||
{reading.hasAppendix ? <AnalysisConclusion reading={reading} visuals={primaryVisuals} renderVisuals={figures => figures.map(visual => <div key={visual.id}>
|
||||
{original ? <AnalysisOriginalContent answer={original.answer} visuals={visuals} renderVisuals={figures => figures.map(visual => <div key={visual.id}><ReportVisualFigure visual={visual} image={images.find(image => image.id === visual.id)} hideEvidence /></div>)} /> : reading.hasAppendix ? <AnalysisConclusion reading={reading} visuals={primaryVisuals} renderVisuals={figures => figures.map(visual => <div key={visual.id}>
|
||||
<ReportVisualFigure visual={visual} image={images.find(image => image.id === visual.id)} hideEvidence />
|
||||
</div>)} /> : complete}
|
||||
</div>;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Alert, Button, Select, Switch, Tag } from 'antd';
|
||||
import { api } from './api';
|
||||
import { usePageCache, useMaintenanceRefresh } from './pageCache';
|
||||
import { useDelayedBusy } from './useDelayedBusy';
|
||||
|
||||
const labels: Record<string, string> = { MONTH: '月报', QUARTER: '季报', YEAR: '年报' };
|
||||
export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen }: {
|
||||
@@ -10,15 +12,26 @@ export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen }
|
||||
const [plans, setPlans] = useState<Record<string, unknown>[]>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [reportsLoaded, setReportsLoaded] = useState(false);
|
||||
const [plansLoaded, setPlansLoaded] = useState(false);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const { active } = usePageCache();
|
||||
const read = useDelayedBusy();
|
||||
const actionInFlight = useRef(false);
|
||||
const [runDay, setRunDay] = useState(1);
|
||||
const load = async () => {
|
||||
try {
|
||||
const [history, savedPlans] = await Promise.all([api.analysisReports(), api.analysisReportPlans()]);
|
||||
setReports(history.items || []); setPlans(savedPlans.items || []);
|
||||
} catch (value) { setError(value instanceof Error ? value.message : '报告读取失败'); }
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
const load = useCallback(() => read.run(async () => {
|
||||
const [history, savedPlans] = await Promise.allSettled([api.analysisReports(), api.analysisReportPlans()]);
|
||||
const errors: string[] = [];
|
||||
if (history.status === 'fulfilled') { setReports(history.value.items || []); setReportsLoaded(true); }
|
||||
else errors.push(`报告列表:${history.reason instanceof Error ? history.reason.message : '读取失败'}`);
|
||||
if (savedPlans.status === 'fulfilled') { setPlans(savedPlans.value.items || []); setPlansLoaded(true); }
|
||||
else errors.push(`自动计划:${savedPlans.reason instanceof Error ? savedPlans.reason.message : '读取失败'}`);
|
||||
setError(errors.join(';'));
|
||||
}), [read.run]);
|
||||
useEffect(() => { if (active && expanded && (!reportsLoaded || !plansLoaded)) void load(); }, [active, expanded, reportsLoaded, plansLoaded, load]);
|
||||
useMaintenanceRefresh(() => { if (expanded) void load(); });
|
||||
const generate = async () => {
|
||||
if (actionInFlight.current) return; actionInFlight.current = true;
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
const response = await api.createAnalysisReport({ periodType, periodKey });
|
||||
@@ -27,9 +40,10 @@ export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen }
|
||||
if (typeof sessionId === 'string' && typeof turnId === 'string') onOpen(sessionId, turnId);
|
||||
else setError('报告已登记,正在准备分析任务,请稍后刷新列表。');
|
||||
} catch (value) { setError(value instanceof Error ? value.message : '报告生成失败'); }
|
||||
finally { setBusy(false); }
|
||||
finally { actionInFlight.current = false; setBusy(false); }
|
||||
};
|
||||
const toggle = async (type: string, enabled: boolean) => {
|
||||
if (actionInFlight.current) return; actionInFlight.current = true;
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
const found = plans.find(plan => plan.periodType === type || plan.reportType === type);
|
||||
@@ -38,24 +52,27 @@ export function AnalysisReportsPanel({ periodType, periodKey, disabled, onOpen }
|
||||
else await api.createAnalysisReportPlan(body);
|
||||
await load();
|
||||
} catch (value) { setError(value instanceof Error ? value.message : '报告计划保存失败'); }
|
||||
finally { setBusy(false); }
|
||||
finally { actionInFlight.current = false; setBusy(false); }
|
||||
};
|
||||
const saveDay = async () => {
|
||||
if (actionInFlight.current) return; actionInFlight.current = true;
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
await Promise.all(plans.map(plan => api.updateAnalysisReportPlan(String(plan.id), { runDay, runHour: 9 })));
|
||||
await load();
|
||||
} catch (value) { setError(value instanceof Error ? value.message : '执行日期保存失败'); }
|
||||
finally { setBusy(false); }
|
||||
finally { actionInFlight.current = false; setBusy(false); }
|
||||
};
|
||||
return <details className="analysis-reports"><summary>月报、季报与年报</summary>
|
||||
return <details className="analysis-reports" onToggle={event => setExpanded(event.currentTarget.open)}><summary>月报、季报与年报</summary>
|
||||
<p>报告使用统一指标与同一分析任务,包含期间比较、趋势和异常追查。自动计划在本机服务运行时执行。</p>
|
||||
{error && <Alert type="warning" showIcon message={error} />}
|
||||
{error && <Alert type="error" showIcon message="报告信息读取失败" description={reportsLoaded || plansLoaded ? `${error};成功读取的内容仍保留。` : error} action={!reportsLoaded || !plansLoaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
|
||||
{read.busy && !reportsLoaded && !plansLoaded && <div className="loading-panel">正在读取报告与自动计划…</div>}
|
||||
<div className="ai-actions"><span>{periodKey} · {labels[periodType]} · 总体范围</span><Button disabled={disabled || busy} loading={busy} onClick={() => void generate()}>生成本期{labels[periodType]}</Button><Button disabled={busy} onClick={() => void load()}>刷新报告</Button></div>
|
||||
<div className="analysis-report-plans"><span>自动生成上一完整周期:每个适用周期首月</span><Select aria-label="自动报告执行日" value={runDay} onChange={setRunDay} options={Array.from({ length: 28 }, (_, i) => ({ label: `${i + 1}日 09:00`, value: i + 1 }))} />
|
||||
{plansLoaded && <div className="analysis-report-plans"><span>自动生成上一完整周期:每个适用周期首月</span><Select aria-label="自动报告执行日" value={runDay} onChange={setRunDay} options={Array.from({ length: 28 }, (_, i) => ({ label: `${i + 1}日 09:00`, value: i + 1 }))} />
|
||||
{Object.entries(labels).map(([type, label]) => { const plan = plans.find(item => item.periodType === type || item.reportType === type); return <label key={type}>{label} <Switch aria-label={`自动${label}`} disabled={busy} checked={plan?.enabled === true} onChange={value => void toggle(type, value)} /></label>; })}
|
||||
<Button size="small" disabled={busy || !plans.length} onClick={() => void saveDay()}>保存执行日期</Button>
|
||||
</div>
|
||||
{reports.length > 0 && <ul>{reports.slice(0, 8).map(report => <li key={String(report.id)}><span>{String(report.periodKey)} {labels[String(report.periodType)] || ''}</span> <Tag>{String(report.status)}</Tag><Button type="link" disabled={disabled || !report.sessionId || !report.turnId} onClick={() => onOpen(String(report.sessionId), String(report.turnId))}>查看分析</Button></li>)}</ul>}
|
||||
</div>}
|
||||
{reportsLoaded && reports.length > 0 && <ul>{reports.slice(0, 8).map(report => <li key={String(report.id)}><span>{String(report.periodKey)} {labels[String(report.periodType)] || ''}</span> <Tag>{String(report.status)}</Tag><Button type="link" disabled={disabled || !report.sessionId || !report.turnId} onClick={() => onOpen(String(report.sessionId), String(report.turnId))}>查看分析</Button></li>)}</ul>}
|
||||
{reportsLoaded && !reports.length && <p className="completion-note">当前没有已生成的报告。</p>}
|
||||
</details>;
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
visualUnitLabel,
|
||||
} from './analysisVisualsModel';
|
||||
import type { AnalysisVisual } from './analysisVisualsModel';
|
||||
import { useDelayedIndicator } from './useDelayedBusy';
|
||||
import { analysisVisualCumulativeShares, analysisVisualShares, analysisVisualTypeLabel } from './analysisVisualPresentation';
|
||||
import './analysis-visuals.css';
|
||||
|
||||
@@ -126,9 +127,11 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna
|
||||
const [nearViewport, setNearViewport] = useState(false);
|
||||
const [chartReady, setChartReady] = useState(false);
|
||||
const [chartLoading, setChartLoading] = useState(false);
|
||||
const showChartLoading = useDelayedIndicator(chartLoading, 150);
|
||||
const [chartError, setChartError] = useState('');
|
||||
const [dataOpen, setDataOpen] = useState(false);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const showExporting = useDelayedIndicator(exporting, 150);
|
||||
const [exportError, setExportError] = useState('');
|
||||
const [themeRevision, setThemeRevision] = useState(0);
|
||||
const [renderAttempt, setRenderAttempt] = useState(0);
|
||||
@@ -312,9 +315,9 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna
|
||||
<Button size="small" icon={<TableOutlined />} onClick={openData}>查看数据</Button>
|
||||
<Dropdown
|
||||
trigger={['click']}
|
||||
menu={{ items: [{ key: 'png', icon: <DownloadOutlined />, label: exporting ? '正在导出…' : '下载 PNG', disabled: !visual.chartable || exporting, onClick: () => { void download(); } }] }}
|
||||
menu={{ items: [{ key: 'png', icon: <DownloadOutlined />, label: showExporting ? '正在导出…' : '下载 PNG', disabled: !visual.chartable || exporting, onClick: () => { void download(); } }] }}
|
||||
>
|
||||
<Button size="small" aria-label="更多图表操作" icon={exporting ? <span className="analysis-visual-spinner" aria-hidden="true" /> : <MoreOutlined />} />
|
||||
<Button size="small" aria-label="更多图表操作" icon={showExporting ? <span className="analysis-visual-spinner" aria-hidden="true" /> : <MoreOutlined />} />
|
||||
</Dropdown>
|
||||
</div>
|
||||
</header>
|
||||
@@ -337,7 +340,7 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna
|
||||
style={visual.type === 'heatmap' ? { minWidth: Math.max(380, visual.categories.length * 62 + 160) }
|
||||
: visual.type === 'pareto' ? { minWidth: Math.max(600, visual.categories.length * 90 + 180) } : undefined} />
|
||||
{!nearViewport && <div className="analysis-visual-placeholder">图表将在进入视口时加载</div>}
|
||||
{nearViewport && chartLoading && <div className="analysis-visual-placeholder" role="status">正在加载图表…</div>}
|
||||
{nearViewport && showChartLoading && <div className="analysis-visual-placeholder" role="status">正在加载图表…</div>}
|
||||
{chartError && <div className="analysis-visual-chart-error" role="status">{chartError}
|
||||
<Button size="small" loading={retrying || chartLoading} onKeyDown={event => event.stopPropagation()}
|
||||
onClick={event => { event.stopPropagation(); void retryChart(); }}>重试图表</Button>
|
||||
|
||||
@@ -171,7 +171,7 @@ export function M01Insights({ query, onUnauthorized }: { query: QueryParams; onU
|
||||
<div className="completion-panel-heading"><div><strong>目标与期间比较</strong><span>目标与比较结果均来自指标分析服务</span></div><Button icon={<ReloadOutlined />} loading={busy} onClick={() => { setCompare(null); setCompareError(''); void refreshAll(); }}>刷新比较</Button></div>
|
||||
<div className="completion-insight-grid">
|
||||
<div className="completion-insight-card">
|
||||
<div className="completion-card-heading"><strong>当前筛选综合率目标</strong><Tag color={configured ? 'green' : targetState === 'CONFLICT' ? 'red' : 'default'}>{targetState === 'CONFIGURED' ? '已配置' : targetState === 'UNCONFIGURED' ? '未配置' : targetState === 'CONFLICT' ? '配置冲突' : targetState}</Tag></div>
|
||||
<div className="completion-card-heading"><strong>当前筛选综合合格率目标</strong><Tag color={configured ? 'green' : targetState === 'CONFLICT' ? 'red' : 'default'}>{targetState === 'CONFIGURED' ? '已配置' : targetState === 'UNCONFIGURED' ? '未配置' : targetState === 'CONFLICT' ? '配置冲突' : targetState}</Tag></div>
|
||||
{targetError ? <Alert showIcon type="error" message="目标读取失败" description={targetError} /> : configured
|
||||
? <><div className="completion-target-value">{pct(configuredTarget)} <small>{text(targetValue.unit, '比例')}</small></div><p className="completion-note">当前目标已启用 · 匹配配置 {text(targetBody.matchingCount, '—')}</p></>
|
||||
: <><div className="completion-empty-value">当前筛选没有唯一的已启用目标</div>{targetState === 'CONFLICT' && <p className="completion-note">存在 {list(targetBody.alternatives).length} 项候选配置;请到“指标与规则”检查配置冲突。</p>}</>}
|
||||
|
||||
@@ -1,17 +1,29 @@
|
||||
import { readQueryLocation } from './queryLoadingScope';
|
||||
import { flushSync } from 'react-dom';
|
||||
import { createWorkspaceTransition, waitForWorkspaceContent } from './workspaceTransition';
|
||||
import { forwardRef, lazy, Suspense, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { Alert, Button, Spin } from 'antd';
|
||||
import { api } from './api';
|
||||
import { api, configureRequestScope, resetRequestScope } from './api';
|
||||
import { pageUsesResources } from './resourceInvalidation';
|
||||
import type { AuthUser, QueryParams } from './types';
|
||||
import type { PageKey } from './QualityWorkspace';
|
||||
import { PageCacheContext, WORKSPACE_INVALIDATED } from './pageCache';
|
||||
|
||||
const QueryPage = lazy(() => import('./QueryPage'));
|
||||
const StageProductPage = lazy(() => import('./StageProductPage'));
|
||||
const ManagementPages = lazy(() => import('./ManagementPages'));
|
||||
const loadQueryPage = () => import('./QueryPage');
|
||||
const loadStageProductPage = () => import('./StageProductPage');
|
||||
const loadManagementPages = () => import('./ManagementPages');
|
||||
const QueryPage = lazy(loadQueryPage);
|
||||
const StageProductPage = lazy(loadStageProductPage);
|
||||
const ManagementPages = lazy(loadManagementPages);
|
||||
|
||||
export function preloadWorkspacePage(page: PageKey): Promise<unknown> {
|
||||
return page === 'blackProduct' || page === 'brightProduct' ? loadStageProductPage()
|
||||
: QUERY_PAGES.includes(page) ? loadQueryPage() : loadManagementPages();
|
||||
}
|
||||
const QUERY_PAGES: PageKey[] = ['overall', 'department', 'group', 'product', 'blackProduct', 'brightProduct'];
|
||||
const retained = (_page: PageKey) => true;
|
||||
type ResultRef = { kind: 'TOP'; resultId: string; releaseId: string };
|
||||
type Entry = { initialSearch: string; search: string; key: number; scroll: number };
|
||||
type Entry = { initialSearch: string; search: string; key: number; scroll: number; revision?: number };
|
||||
export type WorkspaceNavigation = { navigate: (page: PageKey, query?: QueryParams, resultRef?: ResultRef) => void; syncLocation: () => void };
|
||||
function encode(value: unknown) {
|
||||
const bytes = new TextEncoder().encode(JSON.stringify(value));
|
||||
@@ -21,34 +33,64 @@ function encode(value: unknown) {
|
||||
export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
page: PageKey; user: AuthUser; onPageChange: (page: PageKey) => void; onUserChange: (user: AuthUser) => void; onUnauthorized: (error: unknown) => boolean;
|
||||
}>(function CachedWorkspacePages({ page, user, onPageChange, onUserChange, onUnauthorized }, ref) {
|
||||
const userRef = useRef(user);
|
||||
userRef.current = user;
|
||||
const entries = useRef(new Map<PageKey, Entry>([[page, { initialSearch: location.search, search: location.search, key: 0, scroll: 0 }]]));
|
||||
const requested = useRef(page);
|
||||
const current = useRef(page), generation = useRef(0), key = useRef(0);
|
||||
const revisions = useRef<{ authRevision: string; dataRevision: string } | null>(null);
|
||||
const revisions = useRef<{ authRevision: string; dataRevision: string; currentReleaseId: string | null } | null>(null);
|
||||
const validation = useRef<Promise<boolean> | null>(null);
|
||||
const [refreshKey, setRefreshKey] = useState(0), [, render] = useState(0);
|
||||
const [ready, setReady] = useState(false), [error, setError] = useState('');
|
||||
const [navigationBusy, setNavigationBusy] = useState(false);
|
||||
const alive = useRef(true);
|
||||
const validate = () => {
|
||||
const transitions = useRef<ReturnType<typeof createWorkspaceTransition> | null>(null);
|
||||
if (!transitions.current) transitions.current = createWorkspaceTransition(
|
||||
typeof document.startViewTransition === 'function' ? document.startViewTransition.bind(document) : undefined,
|
||||
() => window.matchMedia('(prefers-reduced-motion: reduce)').matches,
|
||||
busy => { if (alive.current) setNavigationBusy(busy); },
|
||||
);
|
||||
const validate = (warmVisibleOptions = false) => {
|
||||
if (validation.current) return validation.current;
|
||||
const epoch = generation.current;
|
||||
const request = (async () => {
|
||||
try {
|
||||
const state = await api.workspaceState();
|
||||
if (!alive.current || generation.current !== epoch) return false;
|
||||
if (revisions.current && state.authRevision !== revisions.current.authRevision) {
|
||||
configureRequestScope({ userId: userRef.current.id, ...state });
|
||||
if ((revisions.current && state.authRevision !== revisions.current.authRevision) || entries.current.size === 0) {
|
||||
// 已知授权变化时立即撤下旧结果,不能等待身份读取成功才清除。
|
||||
setReady(false);
|
||||
entries.current.clear();
|
||||
render(value => value + 1);
|
||||
const latest = await api.me();
|
||||
if (!alive.current || generation.current !== epoch) return false;
|
||||
// 权限改变时清除全部旧缓存,重建此刻正在查看的页面;校验不负责切换路由。
|
||||
transitions.current?.cancel(); requested.current = current.current;
|
||||
userRef.current = latest;
|
||||
configureRequestScope({ userId: latest.id, ...state });
|
||||
onUserChange(latest); entries.current.clear();
|
||||
entries.current.set(current.current, { initialSearch: location.search, search: location.search, key: ++key.current, scroll: 0 });
|
||||
render(value => value + 1);
|
||||
}
|
||||
if (revisions.current && state.dataRevision !== revisions.current.dataRevision) setRefreshKey(value => value + 1);
|
||||
revisions.current = state;
|
||||
render(value => value + 1);
|
||||
setError('');
|
||||
// The visible query needs these options; start their shared read before its code mounts.
|
||||
if (warmVisibleOptions && QUERY_PAGES.includes(requested.current)) {
|
||||
void api.options().catch(() => {});
|
||||
if (requested.current === 'blackProduct' || requested.current === 'brightProduct') {
|
||||
const explicitRelease = readQueryLocation(entries.current.get(requested.current)?.initialSearch || '').releaseId;
|
||||
void api.sourceColumnCatalog(explicitRelease || state.currentReleaseId || undefined).catch(() => {});
|
||||
}
|
||||
}
|
||||
setReady(true);
|
||||
return true;
|
||||
} catch (value) {
|
||||
if (alive.current && generation.current === epoch && value && typeof value === 'object' && 'status' in value && value.status === 403) {
|
||||
setReady(false); entries.current.clear(); resetRequestScope();
|
||||
}
|
||||
if (alive.current && generation.current === epoch && !onUnauthorized(value)) setError(value instanceof Error ? value.message : '页面状态校验失败,请重试');
|
||||
return false;
|
||||
}
|
||||
@@ -66,14 +108,27 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
const previous = entries.current.get(next);
|
||||
if (!previous || force) entries.current.set(next, { initialSearch: search, search, key: ++key.current, scroll: 0 });
|
||||
const entry = entries.current.get(next)!;
|
||||
if (!pop) history.pushState({}, '', `${location.pathname}${entry.search}`);
|
||||
current.current = next; onPageChange(next); render(value => value + 1);
|
||||
// 本地页面先响应点击,网络校验在后台进行;连续切换共享尚未结束的请求。
|
||||
void validate();
|
||||
requested.current = next;
|
||||
transitions.current!.run(async signal => {
|
||||
// 先核实权限与版本,再让已保留页面重新订阅,避免旧版本内容先闪出。
|
||||
if (!await validate(true) || signal.aborted) {
|
||||
if (!signal.aborted && requested.current === next) requested.current = current.current;
|
||||
return;
|
||||
}
|
||||
if (!alive.current || entries.current.get(next) !== entry) return;
|
||||
// 与浏览器快照同步提交页面及滚动位置,避免转场结束后再补一次定位。
|
||||
flushSync(() => {
|
||||
if (!pop) history.pushState({}, '', `${location.pathname}${entry.search}`);
|
||||
current.current = next; onPageChange(next); render(value => value + 1);
|
||||
});
|
||||
window.scrollTo(0, entry.scroll);
|
||||
await waitForWorkspaceContent(() => document.querySelector(`.page-view[data-page="${next}"]`), signal);
|
||||
if (!signal.aborted && current.current === next && entries.current.get(next) === entry) window.scrollTo(0, entry.scroll);
|
||||
});
|
||||
};
|
||||
const navigate = (next: PageKey, query?: QueryParams, resultRef?: ResultRef) => {
|
||||
if (next === 'imports') next = 'sources';
|
||||
if (next === current.current && !query && !resultRef) return;
|
||||
if (next === requested.current && !query && !resultRef) return;
|
||||
const params = new URLSearchParams({ page: next });
|
||||
if (query) params.set('context', encode({ query, ...(resultRef ? { resultRef } : {}) }));
|
||||
const cached = entries.current.get(next);
|
||||
@@ -86,10 +141,22 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
} }));
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
void validate();
|
||||
const invalidate = () => setRefreshKey(value => value + 1);
|
||||
configureRequestScope({ userId: userRef.current.id, authRevision: null, dataRevision: null, currentReleaseId: null });
|
||||
void validate(true);
|
||||
const invalidate = (event: Event) => {
|
||||
const resources = (event as CustomEvent<{ resources?: string[] }>).detail?.resources;
|
||||
for (const [name, entry] of entries.current) {
|
||||
if (pageUsesResources(name, resources)) entry.revision = (entry.revision || 0) + 1;
|
||||
}
|
||||
render(value => value + 1);
|
||||
void validate();
|
||||
};
|
||||
const foreground = () => { if (document.visibilityState === 'visible') void validate(); };
|
||||
window.addEventListener(WORKSPACE_INVALIDATED, invalidate);
|
||||
return () => { alive.current = false; generation.current++; validation.current = null; window.removeEventListener(WORKSPACE_INVALIDATED, invalidate); };
|
||||
window.addEventListener('quality-permission-recheck', foreground);
|
||||
window.addEventListener('focus', foreground);
|
||||
document.addEventListener('visibilitychange', foreground);
|
||||
return () => { alive.current = false; transitions.current?.cancel(); generation.current++; validation.current = null; resetRequestScope(); window.removeEventListener(WORKSPACE_INVALIDATED, invalidate); window.removeEventListener('quality-permission-recheck', foreground); window.removeEventListener('focus', foreground); document.removeEventListener('visibilitychange', foreground); };
|
||||
}, []);
|
||||
const activeEntryKey = entries.current.get(page)?.key;
|
||||
useLayoutEffect(() => {
|
||||
@@ -101,8 +168,8 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
if (!ready) return connectionNotice || <div className="loading-panel"><Spin />正在打开工作台…</div>;
|
||||
return <>{connectionNotice}{Array.from(entries.current.entries()).filter(([name]) => retained(name) || name === page).map(([name, entry]) => {
|
||||
const active = name === page;
|
||||
return <div key={`${name}-${entry.key}`} className="page-view" data-page={name} hidden={!active} style={!active ? { display: 'none' } : undefined}>
|
||||
<PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey, onLocationChange: search => { entry.search = search; } }}>
|
||||
return <div key={`${name}-${entry.key}`} className="page-view" data-page={name} hidden={!active} inert={active && navigationBusy} style={!active ? { display: 'none' } : undefined}>
|
||||
<PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey: refreshKey + (entry.revision || 0), currentReleaseId: revisions.current?.currentReleaseId, authRevision: revisions.current?.authRevision, dataRevision: revisions.current?.dataRevision, onLocationChange: search => { entry.search = search; } }}>
|
||||
<Suspense fallback={<div className="loading-panel"><Spin />正在打开页面…</div>}>
|
||||
{name === 'blackProduct' || name === 'brightProduct' ? <StageProductPage stage={name === 'blackProduct' ? 'black' : 'bright'} onUnauthorized={onUnauthorized} /> : QUERY_PAGES.includes(name) ? <QueryPage page={name} onUnauthorized={onUnauthorized} onNavigate={navigate} /> : <ManagementPages page={name} user={user} onUnauthorized={onUnauthorized} onNavigate={navigate} />}
|
||||
</Suspense>
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import * as echarts from 'echarts/core';
|
||||
import { BarChart } from 'echarts/charts';
|
||||
import { GridComponent, TooltipComponent } from 'echarts/components';
|
||||
import { SVGRenderer } from 'echarts/renderers';
|
||||
import type { DefectMetric, Stage } from './types';
|
||||
import { defectWeightRate } from './trendMetrics';
|
||||
import './defect-composition.css';
|
||||
|
||||
echarts.use([BarChart, GridComponent, TooltipComponent, SVGRenderer]);
|
||||
const weightText = (value: number | null | undefined) => typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString('en-US', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) : '—';
|
||||
const rateText = (value: number | null | undefined) => typeof value === 'number' && Number.isFinite(value) ? `${(value * 100).toFixed(2)}%` : '—';
|
||||
const escape = (value: string) => value.replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[char]!));
|
||||
|
||||
function categoryColors(color: string, surface: string, count: number): string[] {
|
||||
return Array.from({ length: count }, (_, index) => {
|
||||
const mix = index === 0 ? 0 : Math.min(.8, .3 + (index - 1) * .25);
|
||||
return `#${[1, 3, 5].map(offset => Math.round(parseInt(color.slice(offset, offset + 2), 16) * (1 - mix) + parseInt(surface.slice(offset, offset + 2), 16) * mix).toString(16).padStart(2, '0')).join('')}`;
|
||||
});
|
||||
}
|
||||
|
||||
export default function DefectComposition({ items, stage, totalWeight, onDetail }: {
|
||||
items: DefectMetric[];
|
||||
stage: Stage;
|
||||
totalWeight?: number | null;
|
||||
onDetail: () => void;
|
||||
}) {
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const latest = useRef({ items, stage, totalWeight, onDetail });
|
||||
latest.current = { items, stage, totalWeight, onDetail };
|
||||
const redraw = useRef<() => void>(() => undefined);
|
||||
const [colors, setColors] = useState<string[]>([]);
|
||||
const hasShares = items.some(item => typeof item.rate === 'number' && Number.isFinite(item.rate) && item.rate > 0 && item.rate <= 1);
|
||||
|
||||
useEffect(() => {
|
||||
const node = container.current;
|
||||
if (!node) return;
|
||||
let chart: ReturnType<typeof echarts.init> | undefined;
|
||||
redraw.current = () => {
|
||||
if (!node.clientWidth) return;
|
||||
const current = latest.current;
|
||||
const css = getComputedStyle(node);
|
||||
const ink = css.getPropertyValue('--ink').trim() || '#222C3C';
|
||||
const muted = css.getPropertyValue('--muted-ink').trim() || '#637187';
|
||||
const line = css.getPropertyValue('--line').trim() || '#DCE2EC';
|
||||
const surface = css.getPropertyValue('--surface').trim() || '#FFFFFF';
|
||||
const color = css.getPropertyValue(current.stage === 'black' ? '--defect-black' : '--defect-bright').trim() || (current.stage === 'black' ? '#718797' : '#607AE1');
|
||||
const palette = categoryColors(color, surface, current.items.length);
|
||||
if (current.stage === 'black' && document.documentElement.dataset.workspaceTheme !== 'dark') {
|
||||
// Match the selected blue-gray swatches; keep the existing dark-theme contrast treatment.
|
||||
for (const index of [1, 2]) {
|
||||
const tone = css.getPropertyValue(`--defect-black-${index + 1}`).trim();
|
||||
if (tone && index < palette.length) palette[index] = tone;
|
||||
}
|
||||
}
|
||||
setColors(old => old.join() === palette.join() ? old : palette);
|
||||
const fontFamily = css.getPropertyValue('--font-ui').trim() || css.fontFamily;
|
||||
const numericFamily = css.getPropertyValue('--font-numeric').trim() || 'Arial';
|
||||
const stageName = current.stage === 'black' ? '黑片' : '亮片';
|
||||
if (!chart) {
|
||||
chart = echarts.init(node, undefined, { renderer: 'svg' });
|
||||
chart.on('click', () => latest.current.onDetail());
|
||||
}
|
||||
const option: echarts.EChartsCoreOption = {
|
||||
animation: !window.matchMedia('(prefers-reduced-motion: reduce)').matches,
|
||||
animationDuration: 420,
|
||||
animationDurationUpdate: 520,
|
||||
textStyle: { color: ink, fontFamily, fontSize: 12 },
|
||||
grid: { top: 8, left: 20, right: 20, bottom: 28 },
|
||||
tooltip: {
|
||||
trigger: 'item', backgroundColor: surface, borderColor: line,
|
||||
textStyle: { color: ink, fontFamily, fontSize: 12 },
|
||||
formatter: (raw: unknown) => {
|
||||
const item = current.items[(raw as { seriesIndex: number }).seriesIndex];
|
||||
return item ? `${stageName} · ${escape(item.name)}<br/>重量:${weightText(item.weight)} kg<br/>占比:${rateText(item.rate)}<br/>废率:${rateText(defectWeightRate(item.weight, current.totalWeight))}` : '';
|
||||
},
|
||||
},
|
||||
xAxis: { type: 'value', min: 0, max: 100, interval: 25, axisLine: { show: true, lineStyle: { color: line } }, axisTick: { show: false }, splitLine: { show: false }, axisLabel: { fontFamily: numericFamily, fontSize: 11, color: muted, formatter: '{value}%' } },
|
||||
yAxis: { type: 'category', data: [''], show: false },
|
||||
series: current.items.map((item, index) => ({
|
||||
id: `composition-${current.stage}-${item.name}`, name: item.name, type: 'bar', stack: 'composition', barWidth: 28,
|
||||
data: [typeof item.rate === 'number' && Number.isFinite(item.rate) && item.rate >= 0 && item.rate <= 1 ? item.rate * 100 : null],
|
||||
itemStyle: { color: palette[index] },
|
||||
label: { show: typeof item.rate === 'number' && item.rate >= .15, position: 'inside', formatter: rateText(item.rate), color: index === 0 && document.documentElement.dataset.workspaceTheme !== 'dark' ? '#FFFFFF' : ink, fontFamily: numericFamily, fontSize: 13, fontWeight: 600 },
|
||||
emphasis: { itemStyle: { opacity: .85 } },
|
||||
})),
|
||||
};
|
||||
chart.setOption(option, { replaceMerge: ['series'] });
|
||||
};
|
||||
redraw.current();
|
||||
const resize = new ResizeObserver(() => {
|
||||
const { clientWidth: width, clientHeight: height } = node;
|
||||
if (width <= 0 || height <= 0) return;
|
||||
if (chart) chart.resize({ width, height, animation: { duration: 0 } }); else redraw.current();
|
||||
});
|
||||
resize.observe(node);
|
||||
const theme = new MutationObserver(() => redraw.current());
|
||||
theme.observe(document.documentElement, { attributes: true, attributeFilter: ['data-workspace-theme'] });
|
||||
return () => { resize.disconnect(); theme.disconnect(); chart?.dispose(); redraw.current = () => undefined; };
|
||||
}, []);
|
||||
|
||||
useEffect(() => { redraw.current(); }, [items, stage, totalWeight]);
|
||||
|
||||
return <div className="defect-composition">
|
||||
<div className="defect-composition-unit">占比 / %</div>
|
||||
<div className="defect-composition-plot" ref={container} role="img" aria-label={`${stage === 'black' ? '黑片' : '亮片'}分类报废占比,详细数值见下方表格`} style={{ visibility: hasShares ? undefined : 'hidden' }} />
|
||||
{!hasShares && <div className="defect-composition-empty">暂无可绘制的构成占比</div>}
|
||||
<table className="defect-composition-table"><thead><tr><th scope="col">不良分类</th><th scope="col">重量 / kg</th><th scope="col">占比</th><th scope="col">废率</th></tr></thead><tbody>
|
||||
{items.map((item, index) => <tr key={item.name} onClick={() => { if (window.getSelection()?.isCollapsed !== false) onDetail(); }}>
|
||||
<td><button type="button" className="defect-composition-category" aria-label={`查看${stage === 'black' ? '黑片' : '亮片'}${item.name}来源明细`}><i aria-hidden="true" style={{ backgroundColor: colors[index] }} />{item.name}</button></td>
|
||||
<td className="defect-composition-weight">{weightText(item.weight)}</td><td>{rateText(item.rate)}</td><td>{rateText(defectWeightRate(item.weight, totalWeight))}</td>
|
||||
</tr>)}
|
||||
</tbody></table>
|
||||
</div>;
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { usePageCache } from './pageCache';
|
||||
import { useDelayedIndicator } from './useDelayedBusy';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, Button, Select, Spin } from 'antd';
|
||||
import { DownOutlined, UpOutlined } from '@ant-design/icons';
|
||||
@@ -6,6 +8,7 @@ import type { FilterField } from './types';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
|
||||
function FieldSelect({ field, value, onChange, onUnauthorized }: { field: FilterField; value: string[]; onChange: (values: string[]) => void; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { active } = usePageCache();
|
||||
const [search, setSearch] = useState('');
|
||||
const [choices, setChoices] = useState<string[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -13,23 +16,25 @@ function FieldSelect({ field, value, onChange, onUnauthorized }: { field: Filter
|
||||
const [error, setError] = useState('');
|
||||
const [revision, setRevision] = useState(0);
|
||||
const generation = useRef(0);
|
||||
const showLoading = useDelayedIndicator(loading);
|
||||
useEffect(() => {
|
||||
const current = ++generation.current;
|
||||
if (!active) return;
|
||||
const current = ++generation.current, controller = new AbortController();
|
||||
setLoading(true); setChoices([]); setError('');
|
||||
const timer = window.setTimeout(() => {
|
||||
api.filterFieldOptions(field.key, search).then(result => {
|
||||
api.filterFieldOptions(field.key, search, controller.signal).then(result => {
|
||||
if (generation.current !== current) return;
|
||||
setChoices(result.values); setHasMore(result.hasMore);
|
||||
}).catch(e => { if (generation.current === current && !onUnauthorized(e)) setError(e.message || '选项加载失败'); })
|
||||
.finally(() => { if (generation.current === current) setLoading(false); });
|
||||
}, search ? 250 : 0);
|
||||
return () => { window.clearTimeout(timer); generation.current++; };
|
||||
}, [field.key, search, revision, onUnauthorized]);
|
||||
return () => { window.clearTimeout(timer); controller.abort(); generation.current++; };
|
||||
}, [active, field.key, search, revision, onUnauthorized]);
|
||||
return <label className="query-field query-extra-field"><span>{field.label}</span><Select mode="multiple" allowClear showSearch aria-label={field.label}
|
||||
{...readableSelectPopup} maxTagCount="responsive" value={value} loading={loading} filterOption={false} searchValue={search} onSearch={setSearch}
|
||||
{...readableSelectPopup} maxTagCount="responsive" value={value} loading={showLoading} filterOption={false} searchValue={search} onSearch={setSearch}
|
||||
onChange={values => { onChange(values); setSearch(''); }} placeholder="全部"
|
||||
options={[...new Set([...choices, ...value.filter(v => v !== '__EMPTY__')])].map(v => ({ label: v, value: v })).concat(field.allowEmpty ? [{ label: '空值', value: '__EMPTY__' }] : [])}
|
||||
notFoundContent={loading ? <Spin size="small" /> : error ? <Button size="small" onClick={() => setRevision(n => n + 1)}>加载失败,重试</Button> : '暂无匹配项'}
|
||||
notFoundContent={showLoading ? <Spin size="small" /> : error ? <Button size="small" onClick={() => setRevision(n => n + 1)}>加载失败,重试</Button> : '暂无匹配项'}
|
||||
popupRender={menu => <>{menu}{hasMore && <div className="query-options-hint">选项较多,请输入关键字查找</div>}{error && <div role="alert" className="query-options-hint">{error}</div>}</>}
|
||||
/></label>;
|
||||
}
|
||||
@@ -38,22 +43,25 @@ export function ExtraQueryFilters({ projectGroup, projectGroups, onProjectGroup,
|
||||
projectGroup: string[]; projectGroups?: string[]; onProjectGroup: (values: string[]) => void;
|
||||
value: Record<string, string[]>; onChange: (value: Record<string, string[]>) => void; onUnauthorized: (error: unknown) => boolean;
|
||||
}) {
|
||||
const { active } = usePageCache();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [fields, setFields] = useState<FilterField[]>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [revision, setRevision] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!active || !open) return;
|
||||
let alive = true;
|
||||
api.filterFields().then(result => { if (alive) { setFields(result); setError(''); } }).catch(e => { if (alive && !onUnauthorized(e)) setError(e.message || '筛选字段加载失败'); });
|
||||
return () => { alive = false; };
|
||||
}, [revision, onUnauthorized]);
|
||||
const controller = new AbortController();
|
||||
api.filterFields(false, controller.signal).then(result => { if (alive) { setFields(result); setError(''); } }).catch(e => { if (alive && !onUnauthorized(e)) setError(e.message || '筛选字段加载失败'); });
|
||||
return () => { alive = false; controller.abort(); };
|
||||
}, [active, open, revision, onUnauthorized]);
|
||||
const count = (projectGroup.length ? 1 : 0) + Object.values(value).filter(v => v.length).length;
|
||||
const summary = [projectGroup.length ? `项目组:${projectGroup.map(v => v === '__UNASSIGNED__' ? '未分类' : v).join('、')}` : '', ...Object.entries(value).filter(([, values]) => values.length).map(([key, values]) => `${fields.find(f => f.key === key)?.label || key}:${values.map(v => v === '__EMPTY__' ? '空值' : v).join('、')}`)].filter(Boolean).join(';');
|
||||
return <>
|
||||
<div className="query-more-toggle" title={summary || undefined}><Button type="text" size="small" icon={open ? <UpOutlined /> : <DownOutlined />} aria-expanded={open} onClick={() => setOpen(v => !v)}>更多筛选{count ? `(已选 ${count} 项)` : ''}</Button>
|
||||
{count > 0 && <Button type="link" size="small" onClick={() => { onProjectGroup([]); onChange({}); }}>清除</Button>}
|
||||
</div>
|
||||
{error && <Alert className="query-extra-error" type="error" showIcon message={error} action={<Button onClick={() => setRevision(n => n + 1)}>重试</Button>} />}
|
||||
{open && error && <Alert className="query-extra-error" type="error" showIcon message={error} action={<Button onClick={() => setRevision(n => n + 1)}>重试</Button>} />}
|
||||
{open && <div className="query-extra-fields">
|
||||
{projectGroups && <label className="query-field query-extra-field"><span>项目组</span><Select aria-label="项目组" mode="multiple" maxTagCount="responsive" allowClear showSearch optionFilterProp="label" {...readableSelectPopup} value={projectGroup} onChange={onProjectGroup} placeholder="全部" options={[...projectGroups.map(v => ({ label: v, value: v })), { label: '未分类', value: '__UNASSIGNED__' }]} /></label>}
|
||||
{fields.map(field => <FieldSelect key={field.key} field={field} value={value[field.key] || []} onUnauthorized={onUnauthorized} onChange={values => { const next = { ...value }; if (values.length) next[field.key] = values; else delete next[field.key]; onChange(next); }} />)}
|
||||
|
||||
+289
-139
File diff suppressed because one or more lines are too long
+322
-189
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,9 @@ import { PageCacheContext, usePageCache } from './pageCache';
|
||||
|
||||
export function ManagementSections({ items, initialKey, onSelect }: { items: { key: string; label: ReactNode; children: ReactNode }[]; initialKey?: string; onSelect?: (key: string) => void }) {
|
||||
const cache = usePageCache();
|
||||
const [selected, setSelected] = useState(initialKey ?? items[0]?.key);
|
||||
const initialSelected = initialKey && items.some(item => item.key === initialKey) ? initialKey : items[0]?.key;
|
||||
const [selected, setSelected] = useState(initialSelected);
|
||||
const activeKey = items.some(item => item.key === selected) ? selected : items[0]?.key;
|
||||
return <Tabs className="management-sections" activeKey={activeKey} destroyOnHidden={false} onChange={key => { setSelected(key); onSelect?.(key); window.scrollTo({ top: 0 }); }} items={items.map(item => ({ ...item, children: <PageCacheContext.Provider value={{ ...cache, active: cache.active && item.key === activeKey }}>{item.children}</PageCacheContext.Provider> }))} />;
|
||||
const [visited, setVisited] = useState(() => new Set(activeKey ? [activeKey] : []));
|
||||
return <Tabs className="management-sections" activeKey={activeKey} destroyOnHidden={false} onChange={key => { setSelected(key); setVisited(previous => new Set(previous).add(key)); onSelect?.(key); window.scrollTo({ top: 0 }); }} items={items.map(item => ({ ...item, children: <PageCacheContext.Provider value={{ ...cache, active: cache.active && item.key === activeKey }}>{visited.has(item.key) ? item.children : null}</PageCacheContext.Provider> }))} />;
|
||||
}
|
||||
|
||||
+185
-97
@@ -1,5 +1,5 @@
|
||||
import { configurationDateTime } from './configurationName';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Checkbox, Empty, Form, Input, InputNumber, Modal, Progress, Select, Spin, Steps, Tag } from 'antd';
|
||||
import { QualityTable as Table } from './QualityTable';
|
||||
import { ArrowRightOutlined, DeleteOutlined, FileExcelOutlined, ReloadOutlined, SwapOutlined, UndoOutlined, UploadOutlined } from '@ant-design/icons';
|
||||
@@ -7,7 +7,12 @@ import { api, collectionItems } from './api';
|
||||
import type { AuthUser, SourceItem } from './types';
|
||||
import type { DataField, DataStage, DataWorkflowOperation, DataWorkflowStatus, DeletionSource, MasterWorkbookKeyFormat, MasterWorkbookKind, MasterWorkbookPreview, SourceDeletionPreview, SourceUploadOptions, WorkbookPreview } from './NoCodeDataTypes';
|
||||
import { useDataWorkflowOperation } from './useDataWorkflowOperation';
|
||||
import { detectSourceWorkbook } from './sourceWorkbookDetection';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import { usePageCache } from './pageCache';
|
||||
import { useDelayedBusy, useDelayedIndicator } from './useDelayedBusy';
|
||||
import { useVisiblePolling } from './useVisiblePolling';
|
||||
import { runImportPollFollowup } from './importLifecycleGuards';
|
||||
import './no-code-data-workflow.css';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
@@ -55,6 +60,7 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
|
||||
const [activeId, setActiveId] = useState('');
|
||||
const [reading, setReading] = useState<{ done: number; total: number } | null>(null);
|
||||
const [busy, setBusy] = useState(false); const [error, setError] = useState('');
|
||||
const actionLock = useRef(false);
|
||||
const uploadOperation = useDataWorkflowOperation('source-import', () => { setDrafts([]); setActiveId(''); configured.current.clear(); consumed.current.clear(); onRefresh(); message.success('所选来源已统一导入,报表已更新'); });
|
||||
const recalcOperation = useDataWorkflowOperation('recalculate', value => { if (Array.isArray(value.sourceIds)) onDeleted(value.sourceIds.map(String)); onRefresh(); message.success('报表已更新'); });
|
||||
const active = drafts.find(item => item.id === activeId) || drafts[0];
|
||||
@@ -80,8 +86,9 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
|
||||
const reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); };
|
||||
const removeDraft = (id: string) => { setDrafts(previous => previous.filter(item => item.id !== id)); configured.current.delete(id); };
|
||||
const readFiles = async (files: File[]) => {
|
||||
if (!files.length || importBusy) return;
|
||||
if (files.length + drafts.length > 50) { setError('一次最多导入50个文件'); if (input.current) input.current.value = ''; return; }
|
||||
if (!files.length || importBusy || actionLock.current) return;
|
||||
actionLock.current = true;
|
||||
if (files.length + drafts.length > 50) { setError('一次最多导入50个文件'); actionLock.current = false; if (input.current) input.current.value = ''; return; }
|
||||
setBusy(true); setError(''); const failures: string[] = [];
|
||||
const known = new Set(drafts.map(item => `${item.file.name}:${item.file.size}:${item.file.lastModified}`));
|
||||
const selected = files.filter(file => { const key = `${file.name}:${file.size}:${file.lastModified}`; if (known.has(key)) return false; known.add(key); return true; });
|
||||
@@ -89,9 +96,8 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
|
||||
for (let index = 0; index < selected.length; index += 2) {
|
||||
const results = await Promise.all(selected.slice(index, index + 2).map(async file => {
|
||||
try {
|
||||
const result = await api.previewSourceWorkbook(file);
|
||||
const scores = (['black', 'bright'] as DataStage[]).map(value => { const required = (options.fields[value] || []).filter(field => field.required); const matched = matchFields(options.fields[value] || [], result.preview.headers); return { stage: value, score: required.length ? required.filter(field => matched[field.name]).length / required.length : 0 }; });
|
||||
const detected = scores.sort((a, b) => b.score - a.score)[0].stage;
|
||||
const uploaded = await api.previewSourceWorkbook(file);
|
||||
const { workbook: result, stage: detected } = await detectSourceWorkbook(uploaded, options.fields, api.sourceWorkbookPreview);
|
||||
const nextMonth = Number(file.name.match(/(?:^|\D)(0?[1-9]|1[0-2])月/)?.[1] || new Date().getMonth() + 1);
|
||||
const nextYear = Number(file.name.match(/(20\d{2})年/)?.[1] || new Date().getFullYear());
|
||||
return { id: crypto.randomUUID(), file, workbook: result, stage: detected, year: nextYear, month: nextMonth, sheetName: result.preview.sheetName, headerRow: result.preview.headerRow, fieldMap: matchFields(options.fields[detected] || [], result.preview.headers), mode: 'ADD' as const, targetId: '', scopeCode: options.scopes[0] || 'ALL' };
|
||||
@@ -102,19 +108,19 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
|
||||
setReading({ done: Math.min(index + 2, selected.length), total: selected.length });
|
||||
}
|
||||
if (failures.length) setError(`以下文件未加入导入列表,可重新选择:${failures.join(';')}`);
|
||||
setReading(null); setBusy(false); if (input.current) input.current.value = '';
|
||||
setReading(null); actionLock.current = false; setBusy(false); if (input.current) input.current.value = '';
|
||||
};
|
||||
const changePreview = async (nextSheet: string, nextHeader = headerRow, nextStage = stage, preferredMap?: Record<string, string>) => {
|
||||
if (!workbook) return; setBusy(true); setError('');
|
||||
if (!workbook || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try {
|
||||
const result = await api.sourceWorkbookPreview(workbook.uploadId, { sheetName: nextSheet, headerRow: nextHeader, stage: nextStage });
|
||||
setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow);
|
||||
const previous = preferredMap || fieldMap;
|
||||
setFieldMap({ ...matchFields(options.fields[nextStage] || [], result.preview.headers), ...Object.fromEntries(Object.entries(previous).filter(([, header]) => result.preview.headers.includes(header))) });
|
||||
} catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
} catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const importAndUpdate = async () => {
|
||||
if (!canImport || importBusy) return; setBusy(true); setError('');
|
||||
if (!canImport || importBusy || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try {
|
||||
const sourceIds: string[] = [];
|
||||
for (const draft of drafts) {
|
||||
@@ -128,12 +134,14 @@ function SimplifiedDataWorkflow({ options, workflowStatus, pendingDeletion, onDe
|
||||
consumed.current.add(uploadId); configured.current.set(draft.id, { signature, sourceId: result.source.id }); sourceIds.push(result.source.id);
|
||||
}
|
||||
await uploadOperation.start(() => api.importDataWorkflow({ sourceIds }));
|
||||
} catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
} catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const recalculate = async () => {
|
||||
if (actionLock.current) return; actionLock.current = true;
|
||||
setError('');
|
||||
try { await recalcOperation.start(() => pendingDeletion.ids.length ? api.deleteDataWorkflowSources({ sourceIds: pendingDeletion.ids, expectedCurrentReleaseId: pendingDeletion.releaseId }) : api.recalculateDataWorkflow()); }
|
||||
catch (value) { reportError(value); }
|
||||
finally { actionLock.current = false; }
|
||||
};
|
||||
return <div className="nc-simplified-intake">
|
||||
<section className="panel nc-simple-upload-panel">
|
||||
@@ -183,33 +191,46 @@ function ValidationNotice({ value }: { value: unknown }) {
|
||||
|
||||
export function DataWorkflowHub({ user, sources, currentReleaseId, pendingDeletion, onDeleted, onBusyChange, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; currentReleaseId: string | null; pendingDeletion: PendingSourceDeletion; onDeleted: (ids: string[]) => void; onBusyChange: (busy: boolean) => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||
const { message } = App.useApp();
|
||||
const { active } = usePageCache();
|
||||
const [mode, setMode] = useState<'ADD' | 'REPLACE' | 'REBUILD' | null>(null);
|
||||
const [options, setOptions] = useState<SourceUploadOptions | null>(null);
|
||||
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
||||
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
|
||||
const [workflowStatusError, setWorkflowStatusError] = useState('');
|
||||
const statusRead = useDelayedBusy();
|
||||
const optionsRead = useDelayedBusy();
|
||||
const candidatesRead = useDelayedBusy();
|
||||
const [optionError, setOptionError] = useState('');
|
||||
const [candidateError, setCandidateError] = useState('');
|
||||
const [candidates, setCandidates] = useState<Row[]>([]);
|
||||
const [candidatesLoaded, setCandidatesLoaded] = useState(false);
|
||||
const optionsAttempted = useRef(false);
|
||||
const candidatesAttempted = useRef(false);
|
||||
const [resumeId, setResumeId] = useState('');
|
||||
const canMaintain = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_MAINTAINER']);
|
||||
const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_PUBLISHER']);
|
||||
const loadOptions = async () => {
|
||||
const loadOptions = useCallback(() => optionsRead.run(async () => {
|
||||
try { setOptions(await api.sourceUploadOptions()); setOptionError(''); }
|
||||
catch (error) { if (!onUnauthorized(error)) setOptionError(failure(error)); }
|
||||
};
|
||||
const loadWorkflowStatus = async () => {
|
||||
try { setWorkflowStatus(await api.dataWorkflowStatus()); }
|
||||
catch (error) { if (!onUnauthorized(error)) setWorkflowStatus(null); }
|
||||
finally { setWorkflowStatusLoaded(true); }
|
||||
};
|
||||
const loadCandidates = async () => {
|
||||
try { const result = await api.releases(); setCandidates(collectionItems(result).filter(row => String(row.status).toUpperCase() === 'CANDIDATE')); }
|
||||
catch (error) { if (!onUnauthorized(error)) setOptionError(failure(error)); }
|
||||
};
|
||||
useEffect(() => { void loadOptions(); void loadCandidates(); void loadWorkflowStatus(); }, [currentReleaseId, sources]);
|
||||
}), [onUnauthorized, optionsRead.run]);
|
||||
const loadWorkflowStatus = useCallback(() => statusRead.run(async () => {
|
||||
try { setWorkflowStatus(await api.dataWorkflowStatus()); setWorkflowStatusLoaded(true); setWorkflowStatusError(''); }
|
||||
catch (error) { if (!onUnauthorized(error)) setWorkflowStatusError(failure(error)); }
|
||||
}), [onUnauthorized, statusRead.run]);
|
||||
const loadCandidates = useCallback(() => candidatesRead.run(async () => {
|
||||
try { const result = await api.releases(); setCandidates(collectionItems(result).filter(row => String(row.status).toUpperCase() === 'CANDIDATE')); setCandidatesLoaded(true); setCandidateError(''); }
|
||||
catch (error) { if (!onUnauthorized(error)) setCandidateError(failure(error)); }
|
||||
}), [candidatesRead.run, onUnauthorized]);
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
if (!options && !optionsAttempted.current) { optionsAttempted.current = true; void loadOptions(); }
|
||||
if (!candidatesLoaded && !candidatesAttempted.current) { candidatesAttempted.current = true; void loadCandidates(); }
|
||||
if (!workflowStatusLoaded && !workflowStatusError) void loadWorkflowStatus();
|
||||
}, [active, currentReleaseId, sources, options, candidatesLoaded, workflowStatusLoaded, workflowStatusError, loadOptions, loadCandidates, loadWorkflowStatus]);
|
||||
useEffect(() => { const candidate = new URLSearchParams(window.location.search).get('candidateReleaseId'); if (candidate) setResumeId(candidate); }, []);
|
||||
const opened = mode !== null || Boolean(resumeId);
|
||||
const open = (next: 'ADD' | 'REPLACE' | 'REBUILD') => { setMode(next); setResumeId(''); void loadOptions(); };
|
||||
if (!workflowStatusLoaded) return <section className="panel nc-operation-status"><div><strong>读取当前维护模式</strong><span>正在加载可执行操作</span></div><Spin /></section>;
|
||||
const open = (next: 'ADD' | 'REPLACE' | 'REBUILD') => { setMode(next); setResumeId(''); if (!options) { optionsAttempted.current = true; void loadOptions(); } };
|
||||
if (!workflowStatusLoaded) return <section className="panel nc-operation-status">{statusRead.busy ? <div><strong>读取当前维护模式</strong><span>正在加载可执行操作</span><Spin /></div> : workflowStatusError ? <Alert showIcon type="error" message="维护模式读取失败" description={workflowStatusError} action={<Button size="small" onClick={() => void loadWorkflowStatus()}>重试</Button>} /> : null}</section>;
|
||||
if (workflowStatus?.simplified === true && workflowStatus.mode === 'TEST' && options) return <SimplifiedDataWorkflow options={options} workflowStatus={workflowStatus} pendingDeletion={pendingDeletion} onDeleted={onDeleted} onBusyChange={onBusyChange} onUnauthorized={onUnauthorized} onRefresh={onRefresh} />;
|
||||
return <>
|
||||
<section className="nc-intake-start panel">
|
||||
@@ -217,39 +238,54 @@ export function DataWorkflowHub({ user, sources, currentReleaseId, pendingDeleti
|
||||
<div className="nc-primary-actions"><Button type="primary" size="large" icon={<UploadOutlined />} disabled={!canMaintain || !options} onClick={() => open('ADD')}>上传新数据</Button><Button size="large" icon={<SwapOutlined />} disabled={!canMaintain || !options || !options.targets.length} onClick={() => open('REPLACE')}>替换已有数据</Button></div>
|
||||
<div className="nc-intake-links"><Button type="link" disabled={!canMaintain || !options?.targets.length} onClick={() => open('REBUILD')}>按当前来源重新计算</Button><span>上传 → 选择年月 → 匹配列 → 校验 → 发布</span></div>
|
||||
</section>
|
||||
{optionError && <Alert type="error" showIcon message="数据操作信息读取失败" description={optionError} action={<Button size="small" onClick={() => { void loadOptions(); void loadCandidates(); }}>重试</Button>} />}
|
||||
{optionError && <Alert type="error" message="上传选项读取失败" showIcon description={options ? `${optionError};已成功读取的选项仍保留。` : optionError} action={<Button size="small" onClick={() => { optionsAttempted.current = true; void loadOptions(); }}>重试</Button>} />}
|
||||
{candidateError && <Alert type="error" message="候选数据读取失败" showIcon description={candidatesLoaded ? `${candidateError};上次成功读取的候选仍保留。` : candidateError} action={<Button size="small" onClick={() => { candidatesAttempted.current = true; void loadCandidates(); }}>重试</Button>} />}
|
||||
{!options && optionsRead.busy && <div className="completion-loading"><Spin />读取上传选项…</div>}
|
||||
{!candidatesLoaded && candidatesRead.busy && <div className="completion-loading"><Spin />读取候选数据…</div>}
|
||||
{!canMaintain && <Alert showIcon type="info" message={canPublish ? '当前账号可以核对和发布已有候选数据' : '上传和替换需要数据维护权限'} description="已授权的操作会按账号权限显示。" />}
|
||||
{candidates.length > 0 && <section className="nc-pending-strip panel"><div><strong>待完成的数据</strong><span>已保存的候选可继续校验、对账和发布。</span></div><Select {...readableSelectPopup} aria-label="选择待完成候选数据" placeholder="选择候选数据" value={resumeId || undefined} options={candidates.map(row => ({ value: String(row.id), label: `${txt(row.name || row.id)}${row.complete === false ? ' · 校验未通过' : ''}` }))} onChange={value => { setMode(null); setResumeId(value); }} /></section>}
|
||||
{candidatesLoaded && candidates.length > 0 && <section className="nc-pending-strip panel"><div><strong>待完成的数据</strong><span>已保存的候选可继续校验、对账和发布。</span></div><Select {...readableSelectPopup} aria-label="选择待完成候选数据" placeholder="选择候选数据" value={resumeId || undefined} options={candidates.map(row => ({ value: String(row.id), label: `${txt(row.name || row.id)}${row.complete === false ? ' · 校验未通过' : ''}` }))} onChange={value => { setMode(null); setResumeId(value); }} /></section>}
|
||||
{opened && options && <DataUploadWizard key={`${mode}:${resumeId}`} user={user} mode={mode || 'ADD'} options={options} sources={sources} resumeId={resumeId} onUnauthorized={onUnauthorized} onClose={() => { setMode(null); setResumeId(''); }} onComplete={() => { onRefresh(); void loadOptions(); void loadCandidates(); message.success('操作结果已刷新'); }} />}
|
||||
</>;
|
||||
}
|
||||
|
||||
export function SourceFilesPanel({ user, sources, loading, pendingIds, maintenanceBusy, onToggleDelete, onClearDeletes, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; loading: boolean; pendingIds: string[]; maintenanceBusy: boolean; onToggleDelete: (id: string) => void; onClearDeletes: () => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||
export function SourceFilesPanel({ user, sources, sourcesLoaded, loading, pendingIds, maintenanceBusy, onToggleDelete, onClearDeletes, onUnauthorized, onRefresh }: { user: AuthUser; sources: SourceItem[]; sourcesLoaded: boolean; loading: boolean; pendingIds: string[]; maintenanceBusy: boolean; onToggleDelete: (id: string) => void; onClearDeletes: () => void; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
|
||||
const { message } = App.useApp();
|
||||
const { active } = usePageCache();
|
||||
const [showDeleted, setShowDeleted] = useState(false);
|
||||
const [deleted, setDeleted] = useState<SourceDeletionPreview[]>([]);
|
||||
const [deletedLoaded, setDeletedLoaded] = useState(false);
|
||||
const deletedRead = useDelayedBusy();
|
||||
const [metadataError, setMetadataError] = useState('');
|
||||
const metadataAttempted = useRef(false);
|
||||
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
||||
const [currentSourceIds, setCurrentSourceIds] = useState<string[] | null>(null);
|
||||
const [deletedLoading, setDeletedLoading] = useState(false);
|
||||
const [deletedError, setDeletedError] = useState('');
|
||||
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
|
||||
const [selected, setSelected] = useState<{ id: string; restore: boolean } | null>(() => { const id = new URLSearchParams(window.location.search).get('sourceDeleteId'); return id ? { id, restore: false } : null; });
|
||||
const canOperate = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_MAINTAINER', 'DATA_PUBLISHER']);
|
||||
const loadDeleted = async () => {
|
||||
setDeletedLoading(true);
|
||||
try { const result = await api.deletedSources(); setDeleted(result.items); setDeletedError(''); }
|
||||
const loadDeleted = useCallback(() => deletedRead.run(async () => {
|
||||
try { const result = await api.deletedSources(); setDeleted(result.items); setDeletedLoaded(true); setDeletedError(''); }
|
||||
catch (value) { if (!onUnauthorized(value)) setDeletedError(failure(value)); }
|
||||
finally { setDeletedLoading(false); }
|
||||
};
|
||||
}), [deletedRead.run, onUnauthorized]);
|
||||
const sourceOperation = useDataWorkflowOperation('source-maintenance', value => {
|
||||
onRefresh(); if (showDeleted) void loadDeleted();
|
||||
message.success(String(value.operationType || '').toUpperCase().includes('RESTORE') ? '来源已恢复,报表已更新' : '来源已删除,报表已更新');
|
||||
});
|
||||
const loadMetadata = useCallback(async () => {
|
||||
const [status, options] = await Promise.allSettled([api.dataWorkflowStatus(), api.sourceUploadOptions()]);
|
||||
const errors: string[] = [];
|
||||
if (status.status === 'fulfilled') { setWorkflowStatus(status.value); setWorkflowStatusLoaded(true); }
|
||||
else if (!onUnauthorized(status.reason)) errors.push(`维护状态:${failure(status.reason)}`);
|
||||
if (options.status === 'fulfilled') setCurrentSourceIds(options.value.currentSourceIds || []);
|
||||
else if (!onUnauthorized(options.reason)) errors.push(`来源范围:${failure(options.reason)}`);
|
||||
setMetadataError(errors.join(';'));
|
||||
}, [onUnauthorized]);
|
||||
useEffect(() => {
|
||||
void api.dataWorkflowStatus().then(setWorkflowStatus).catch(() => setWorkflowStatus(null)).finally(() => setWorkflowStatusLoaded(true));
|
||||
void api.sourceUploadOptions().then(options => setCurrentSourceIds(options.currentSourceIds || [])).catch(() => setCurrentSourceIds(null));
|
||||
}, [sources]);
|
||||
useEffect(() => { if (showDeleted && canOperate) void loadDeleted(); }, [showDeleted, sources]);
|
||||
if (!active || metadataAttempted.current) return;
|
||||
metadataAttempted.current = true;
|
||||
void loadMetadata();
|
||||
}, [active, sources, loadMetadata]);
|
||||
useEffect(() => { if (active && showDeleted && canOperate && !deletedLoaded) void loadDeleted(); }, [active, showDeleted, canOperate, deletedLoaded, loadDeleted, sources]);
|
||||
const period = (source: DeletionSource) => source.year && source.month ? `${source.year}年${String(source.month).padStart(2, '0')}月` : '尚未确认';
|
||||
const close = () => { setSelected(null); const url = new URL(window.location.href); if (url.searchParams.has('sourceDeleteId')) { url.searchParams.delete('sourceDeleteId'); window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`); } };
|
||||
const simplified = workflowStatus?.simplified === true && workflowStatus.mode === 'TEST';
|
||||
@@ -262,9 +298,10 @@ export function SourceFilesPanel({ user, sources, loading, pendingIds, maintenan
|
||||
<div className="resource-toolbar"><strong>{showDeleted ? '已删除的来源文件' : '已接收的来源文件'}</strong><span>{showDeleted ? `${deleted.length} 个文件 · 原件和处理记录保留` : simplified ? `${sources.length} 个文件${pendingIds.length ? ` · ${pendingIds.length} 个待删除` : ''}` : `${sources.length} 个文件 · 上传或接收不等于已经发布`}</span>{canOperate && <Checkbox checked={showDeleted} onChange={event => setShowDeleted(event.target.checked)}>查看已删除来源</Checkbox>}</div>
|
||||
{simplified && <p className="nc-source-maintenance-note">删除先标记为待删除,可连续操作和撤销,点击上方“更新报表”后统一生效。原文件和处理记录保留。</p>}
|
||||
{simplified && pendingIds.length > 0 && <div className="nc-source-maintenance-note"><Button disabled={maintenanceBusy} onClick={onClearDeletes}>撤销全部待删除({pendingIds.length})</Button></div>}
|
||||
{deletedError && <Alert showIcon type="error" message="已删除来源读取失败" description={deletedError} action={<Button size="small" onClick={() => void loadDeleted()}>重试</Button>} />}
|
||||
{deletedError && <Alert showIcon type="error" message="已删除来源读取失败" description={deletedLoaded ? `${deletedError};上次成功读取的来源仍保留。` : deletedError} action={<Button size="small" onClick={() => void loadDeleted()}>重试</Button>} />}
|
||||
{metadataError && <Alert showIcon type="error" message="来源操作信息读取失败" description={workflowStatusLoaded || currentSourceIds !== null ? `${metadataError};已成功读取的状态仍保留。` : metadataError} action={<Button size="small" onClick={() => { metadataAttempted.current = true; setMetadataError(''); void loadMetadata(); }}>重试</Button>} />}
|
||||
{sourceOperation.operation && <WorkflowOperationFeedback operation={sourceOperation.operation} error={sourceOperation.error} busy={sourceOperation.busy} onResume={sourceOperation.resume} />}
|
||||
<Table<DeletionSource> size="small" bordered loading={showDeleted ? deletedLoading : loading} dataSource={showDeleted ? deleted.map(item => item.source) : sources} rowKey="id" pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 980 }} columns={[
|
||||
{(!showDeleted && sourcesLoaded) || (showDeleted && (deletedLoaded || deletedRead.busy)) ? <Table<DeletionSource> size="small" bordered loading={showDeleted ? deletedRead.busy : loading} dataSource={showDeleted ? deleted.map(item => item.source) : sources} rowKey="id" pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 980 }} columns={[
|
||||
{ title: '来源文件', dataIndex: 'sourceFile', key: 'sourceFile', width: 340, ellipsis: true },
|
||||
{ title: '阶段', dataIndex: 'stage', key: 'stage', align: 'center', width: 90, render: value => <Tag>{stageName(value)}</Tag> },
|
||||
{ title: '统计期间', key: 'period', align: 'center', width: 140, render: (_, row) => period(row) },
|
||||
@@ -276,22 +313,24 @@ export function SourceFilesPanel({ user, sources, loading, pendingIds, maintenan
|
||||
if (!workflowStatusLoaded || !canOperate || !permitted) return null;
|
||||
return <Button type="link" danger={!showDeleted} icon={showDeleted ? <UndoOutlined /> : <DeleteOutlined />} disabled={sourceOperation.busy || maintenanceBusy || loading} onClick={() => simplified ? showDeleted ? void runSourceOperation(row.id, true) : onToggleDelete(row.id) : setSelected({ id: row.id, restore: showDeleted })}>{simplified ? showDeleted ? '恢复并更新报表' : pendingIds.includes(row.id) ? '撤销删除' : '删除' : showDeleted ? '恢复' : '删除'}</Button>;
|
||||
} },
|
||||
]} locale={{ emptyText: showDeleted ? '没有已删除的来源。' : '尚无来源文件,点击“上传新数据”开始。' }} />
|
||||
]} locale={{ emptyText: showDeleted ? '没有已删除的来源。' : '尚无来源文件,点击“上传新数据”开始。' }} /> : null}
|
||||
</section>
|
||||
{selected && !simplified && <SourceDeletionDialog key={`${selected.id}:${selected.restore}`} user={user} sourceId={selected.id} restoring={selected.restore} sources={sources} onUnauthorized={onUnauthorized} onClose={close} onRefresh={() => { onRefresh(); if (showDeleted) void loadDeleted(); }} />}
|
||||
</>;
|
||||
}
|
||||
|
||||
function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthorized, onClose, onRefresh }: { user: AuthUser; sourceId: string; restoring: boolean; sources: SourceItem[]; onUnauthorized: (error: unknown) => boolean; onClose: () => void; onRefresh: () => void }) {
|
||||
const { message } = App.useApp();
|
||||
const { message } = App.useApp(); const { active } = usePageCache();
|
||||
const [preview, setPreview] = useState<SourceDeletionPreview | null>(null);
|
||||
const [busy, setBusy] = useState(true); const [error, setError] = useState(''); const [notice, setNotice] = useState('');
|
||||
const [reason, setReason] = useState(''); const [confirmed, setConfirmed] = useState(false); const [finished, setFinished] = useState(false);
|
||||
const [candidateId, setCandidateId] = useState(''); const [options, setOptions] = useState<SourceUploadOptions | null>(null);
|
||||
const requestKey = useRef(crypto.randomUUID()); const buildKey = useRef(crypto.randomUUID());
|
||||
const reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); };
|
||||
const load = async () => { setBusy(true); try { const result = await api.sourceDeletionPreview(sourceId); setPreview(result); setError(''); if (restoring && !result.hidden) { setFinished(true); setNotice('此来源已在日常清单中,无需重复恢复。'); } } catch (value) { reportError(value); } finally { setBusy(false); } };
|
||||
useEffect(() => { void load(); }, [sourceId]);
|
||||
const actionLock = useRef(false); const candidateLock = useRef(false);
|
||||
const showBusy = useDelayedIndicator(busy, 150);
|
||||
const reportError = useCallback((value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); }, [onUnauthorized]);
|
||||
const load = useCallback(async () => { if (!active || actionLock.current) return; setBusy(true); try { const result = await api.sourceDeletionPreview(sourceId); setPreview(result); setError(''); if (restoring && !result.hidden) { setFinished(true); setNotice('此来源已在日常清单中,无需重复恢复。'); } } catch (value) { reportError(value); } finally { setBusy(false); } }, [active, reportError, restoring, sourceId]);
|
||||
useEffect(() => { if (active) void load(); }, [active, load]);
|
||||
const request = preview?.changeRequest; const requestStatus = String(request?.status || '');
|
||||
const isRequested = preview?.nextAction === 'REVIEW_WITHDRAWAL'; const isApproved = preview?.nextAction === 'BUILD_WITHDRAWAL_CANDIDATE'; const isBuilt = preview?.nextAction === 'RECONCILE_CANDIDATE';
|
||||
const withdrawing = preview?.mode === 'WITHDRAW_CURRENT' || isRequested || isApproved || isBuilt;
|
||||
@@ -303,7 +342,7 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
|
||||
const actualRestore = Boolean((restoring || preview?.hidden) && !finished);
|
||||
const reasonLabel = actualRestore ? '恢复理由' : isRequested ? '审批说明' : '删除理由';
|
||||
const act = async (kind: 'delete' | 'restore' | 'approve' | 'reject' | 'build') => {
|
||||
if (!preview) return; setBusy(true); setError('');
|
||||
if (!active || !preview || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try {
|
||||
if (kind === 'delete') {
|
||||
const result = await api.deleteSource(sourceId, { expectedCurrentReleaseId: preview.currentReleaseId, expectedDeleteVersion: preview.deleteVersion, ...(preview.currentUsage ? { expectedRevisionId: preview.currentUsage.revisionId } : {}), reason: reason.trim(), idempotencyKey: requestKey.current });
|
||||
@@ -325,12 +364,12 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
|
||||
}
|
||||
setReason(''); setConfirmed(false); onRefresh();
|
||||
} catch (value) { reportError(value); }
|
||||
finally { setBusy(false); }
|
||||
finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const openCandidate = async (releaseId: string) => {
|
||||
setBusy(true); setError('');
|
||||
if (!active || candidateLock.current) return; candidateLock.current = true; setBusy(true); setError('');
|
||||
try { const support = await api.sourceUploadOptions(); setOptions(support); setCandidateId(releaseId); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
catch (value) { reportError(value); } finally { candidateLock.current = false; setBusy(false); }
|
||||
};
|
||||
const handoff = async () => {
|
||||
const url = new URL(window.location.href); url.searchParams.set('page', 'sources'); url.searchParams.set('sourceDeleteId', sourceId); url.searchParams.delete('candidateReleaseId');
|
||||
@@ -343,9 +382,9 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
|
||||
<Button icon={<ReloadOutlined />} disabled={busy} onClick={() => void load()}>刷新状态</Button>
|
||||
{actualRestore ? <Button type="primary" loading={busy} disabled={!canRestore || !confirmed || !reason.trim()} onClick={() => void act('restore')}>确认恢复来源</Button> : isRequested ? <>{canReview && <><Button danger disabled={busy || !reason.trim()} onClick={() => void act('reject')}>驳回申请</Button><Button type="primary" loading={busy} disabled={!confirmed || !reason.trim()} onClick={() => void act('approve')}>批准删除申请</Button></>}</> : isApproved ? <Button type="primary" loading={busy} disabled={!canBuild || !confirmed} onClick={() => void act('build')}>生成删除候选</Button> : isBuilt ? <Button type="primary" loading={busy} disabled={!request?.resultReleaseId} onClick={() => { if (request?.resultReleaseId) void openCandidate(request.resultReleaseId); }}>核对并发布删除候选</Button> : <Button type="primary" danger loading={busy} disabled={!canStart || !confirmed || !reason.trim()} onClick={() => void act('delete')}>{withdrawing ? '提交删除申请' : '确认删除来源'}</Button>}
|
||||
</>}</div></div>}>
|
||||
{error && <Alert type="error" showIcon message="操作未完成" description={error} />}
|
||||
{error && <Alert type="error" showIcon message="操作未完成" description={preview ? `${error};已成功读取的来源信息仍保留。` : error} action={!preview ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
|
||||
{notice && <Alert type={finished ? 'success' : 'info'} showIcon message={notice} />}
|
||||
<Spin spinning={busy}>{preview ? <>
|
||||
<Spin spinning={showBusy}>{preview ? <>
|
||||
<div className="nc-file-summary"><FileExcelOutlined /><strong>{preview.source.sourceFile}</strong><span>{preview.source.year && preview.source.month ? `${preview.source.year}年${preview.source.month}月` : '期间待确认'} · {stageName(preview.source.stage)}</span></div>
|
||||
{withdrawing && !actualRestore && <Steps className="nc-delete-steps" current={deletionStep} size="small" items={[{ title: '确认影响' }, { title: '审批申请' }, { title: '生成候选' }, { title: '对账与发布' }, { title: '移入已删除' }]} />}
|
||||
<div className="nc-review-facts nc-deletion-impact"><div><small>当前正式数据</small><strong>{preview.currentUsage ? '正在使用此来源' : '未使用此来源'}</strong></div><div><small>归档来源记录</small><strong>{preview.history.revisionCount} 个</strong></div><div><small>正式处理记录</small><strong>{preview.history.publishedReleaseCount} 个</strong></div><div><small>候选处理记录</small><strong>{preview.history.candidateReleaseCount} 个</strong></div></div>
|
||||
@@ -358,97 +397,145 @@ function SourceDeletionDialog({ user, sourceId, restoring, sources, onUnauthoriz
|
||||
</>}
|
||||
{waitingForColleague && !awaitingTask && <Alert type="info" showIcon message={isRequested ? '等待有审批权限的发布者继续' : isApproved ? '等待有权限的发布者生成候选' : actualRestore ? '此账号没有恢复权限' : '此账号没有本次删除操作权限'} description={<>{preview.blockedReason && <p>{preview.blockedReason}</p>}<span>可复制当前处理链接交接;对方打开后会看到相同来源、申请和下一步。</span><Button type="link" onClick={() => void handoff()}>复制处理链接</Button></>} />}
|
||||
{!finished && isBuilt && <Alert type="info" showIcon message="删除候选已保存,等待核对与发布" description="点击“核对并发布删除候选”继续查看差异;没有发布权限的账号可在候选窗口复制交接链接。" />}
|
||||
</> : !busy ? <Empty description="未读取到来源信息" /> : <div className="loading-panel">正在核对来源及影响…</div>}</Spin>
|
||||
</> : showBusy ? <div className="loading-panel">正在核对来源及影响…</div> : null}</Spin>
|
||||
</Modal>
|
||||
{candidateId && options && <DataUploadWizard key={`deletion:${candidateId}`} user={user} mode="ADD" purpose="WITHDRAW" handoffSourceId={sourceId} initialReason={request?.reason} options={options} sources={sources} resumeId={candidateId} onUnauthorized={onUnauthorized} onClose={() => { setCandidateId(''); void load(); }} onComplete={() => { setFinished(true); setNotice('删除候选已发布,该来源已从当前结果移除;原件和处理记录保留。'); onRefresh(); void load(); }} />}
|
||||
</>;
|
||||
}
|
||||
|
||||
function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason, options, sources, resumeId, onUnauthorized, onClose, onComplete }: { user: AuthUser; mode: 'ADD' | 'REPLACE' | 'REBUILD'; purpose?: 'WITHDRAW'; handoffSourceId?: string; initialReason?: string; options: SourceUploadOptions; sources: SourceItem[]; resumeId: string; onUnauthorized: (error: unknown) => boolean; onClose: () => void; onComplete: () => void }) {
|
||||
const { message } = App.useApp(); const input = useRef<HTMLInputElement>(null); const generation = useRef(0); const importKey = useRef(crypto.randomUUID()); const publishKey = useRef(crypto.randomUUID());
|
||||
const [pollAttempt, setPollAttempt] = useState(0);
|
||||
const [step, setStep] = useState(resumeId ? 4 : 0); const [busy, setBusy] = useState(false); const [error, setError] = useState('');
|
||||
const { message } = App.useApp(); const { active } = usePageCache(); const activeRef = useRef(active); activeRef.current = active; const input = useRef<HTMLInputElement>(null); const generation = useRef(0); const importKey = useRef(crypto.randomUUID()); const publishKey = useRef(crypto.randomUUID());
|
||||
const runStorageKey = `quality-import-run:${user.id}`;
|
||||
const [storedRunId] = useState(() => { try { return localStorage.getItem(runStorageKey) || ''; } catch { return ''; } });
|
||||
const [step, setStep] = useState(resumeId ? 4 : storedRunId ? 3 : 0); const [busy, setBusy] = useState(Boolean(storedRunId)); const [error, setError] = useState('');
|
||||
const [workbook, setWorkbook] = useState<WorkbookPreview | null>(null); const [stage, setStage] = useState<DataStage>('black');
|
||||
const [year, setYear] = useState(new Date().getFullYear()); const [month, setMonth] = useState(new Date().getMonth() + 1);
|
||||
const [scopeCode, setScopeCode] = useState(options.scopes[0] || 'ALL'); const [targetId, setTargetId] = useState('');
|
||||
const [sheetName, setSheetName] = useState(''); const [headerRow, setHeaderRow] = useState(1); const [fieldMap, setFieldMap] = useState<Record<string, string>>({});
|
||||
const [configuredSourceId, setConfiguredSourceId] = useState('');
|
||||
const [reason, setReason] = useState(initialReason || ''); const [run, setRun] = useState<Row | null>(null); const [release, setRelease] = useState<Row | null>(null);
|
||||
const [reason, setReason] = useState(initialReason || ''); const [run, setRun] = useState<Row | null>(() => storedRunId ? { id: storedRunId, status: 'RUNNING' } : null); const [release, setRelease] = useState<Row | null>(null);
|
||||
const [runTerminalId, setRunTerminalId] = useState('');
|
||||
const completionNotified = useRef(new Set<string>());
|
||||
const actionLock = useRef(false); const pollLock = useRef(false); const pollAgainAfterCurrent = useRef(false); const candidateReadLock = useRef(false);
|
||||
const runIdRef = useRef('');
|
||||
const [reconciliation, setReconciliation] = useState<Row | null>(null); const [issues, setIssues] = useState<Row[]>([]);
|
||||
const [differenceReason, setDifferenceReason] = useState(''); const [confirmDifferences, setConfirmDifferences] = useState(false); const [publishConfirmed, setPublishConfirmed] = useState(false); const [published, setPublished] = useState(false);
|
||||
const target = options.targets.find(item => item.documentId === targetId); const fields = options.fields[stage] || [];
|
||||
const headers = workbook?.preview.headers || []; const missingFields = fields.filter(field => field.required && !fieldMap[field.name]); const duplicateColumns = Object.values(fieldMap).length !== new Set(Object.values(fieldMap)).size;
|
||||
const canPublish = rolesAllow(user, ['SYSTEM_ADMIN', 'DATA_PUBLISHER']);
|
||||
const reportError = (value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); };
|
||||
const loadCandidate = async (id: string) => {
|
||||
const inspected = await api.governanceReleaseInspect(id); setRelease(asRow(inspected.release));
|
||||
const result = await api.governanceReleaseReconciliations(id); const list = collectionItems(result); const selected = list.find(item => String(item.id) === String(result.acceptanceId)) || list[0];
|
||||
setReconciliation(selected?.id ? await api.governanceReconciliation(String(selected.id)) : null);
|
||||
const reportError = useCallback((value: unknown) => { if (!onUnauthorized(value)) setError(failure(value)); }, [onUnauthorized]);
|
||||
const loadCandidate = async (id: string, isCurrent: () => boolean = () => activeRef.current) => {
|
||||
if (!activeRef.current || !isCurrent()) return false;
|
||||
const inspected = await api.governanceReleaseInspect(id);
|
||||
if (!activeRef.current || !isCurrent()) return false;
|
||||
setRelease(asRow(inspected.release));
|
||||
const result = await api.governanceReleaseReconciliations(id);
|
||||
if (!activeRef.current || !isCurrent()) return false;
|
||||
const list = collectionItems(result); const selected = list.find(item => String(item.id) === String(result.acceptanceId)) || list[0];
|
||||
const reconciliation = selected?.id ? await api.governanceReconciliation(String(selected.id)) : null;
|
||||
if (!activeRef.current || !isCurrent()) return false;
|
||||
setReconciliation(reconciliation);
|
||||
return true;
|
||||
};
|
||||
useEffect(() => { if (resumeId) { setBusy(true); loadCandidate(resumeId).catch(reportError).finally(() => setBusy(false)); } return () => { generation.current++; }; }, []);
|
||||
const runId = String(run?.id || '');
|
||||
useEffect(() => {
|
||||
if (!runId) return;
|
||||
let alive = true; let timer: ReturnType<typeof setTimeout>;
|
||||
const poll = async () => {
|
||||
try {
|
||||
const result = await api.importRun(runId); if (!alive) return; setRun(result.run);
|
||||
if (String(result.run.status) === 'COMPLETED') {
|
||||
const id = String(result.run.resultReleaseId || ''); if (!id) throw new Error('校验已完成,但没有返回候选数据');
|
||||
await loadCandidate(id); if (!alive) return; setStep(4); setBusy(false); onComplete();
|
||||
if (asRow(result.run.validation).complete === false) { const issueList = await api.importIssues(runId); if (alive) setIssues(collectionItems(issueList)); }
|
||||
} else if (['FAILED', 'CANCELLED'].includes(String(result.run.status))) {
|
||||
setBusy(false); const issueList = await api.importIssues(runId); if (alive) setIssues(collectionItems(issueList));
|
||||
} else timer = setTimeout(poll, 1400);
|
||||
} catch (value) { if (alive) { reportError(value); setBusy(false); } }
|
||||
};
|
||||
timer = setTimeout(poll, 700); return () => { alive = false; clearTimeout(timer); };
|
||||
}, [runId, pollAttempt]);
|
||||
if (!active || !resumeId || candidateReadLock.current) return;
|
||||
candidateReadLock.current = true; setBusy(true);
|
||||
loadCandidate(resumeId).catch(reportError).finally(() => { candidateReadLock.current = false; setBusy(false); });
|
||||
return () => { generation.current++; };
|
||||
}, [active, reportError, resumeId]);
|
||||
const runId = String(run?.id || '');
|
||||
runIdRef.current = runId;
|
||||
const pollRun = useCallback(async () => {
|
||||
if (!activeRef.current || !runId) return;
|
||||
if (pollLock.current) { pollAgainAfterCurrent.current = true; return; }
|
||||
pollLock.current = true;
|
||||
try {
|
||||
const result = await api.importRun(runId);
|
||||
const isCurrent = () => activeRef.current && runIdRef.current === runId;
|
||||
if (!isCurrent()) return;
|
||||
setRun(result.run); setError('');
|
||||
const status = String(result.run.status || '').toUpperCase();
|
||||
if (status === 'COMPLETED') {
|
||||
const id = String(result.run.resultReleaseId || ''); if (!id) throw new Error('校验已完成,但没有返回候选数据');
|
||||
const candidateRead = await runImportPollFollowup(runId, () => isCurrent(), () => loadCandidate(id, isCurrent));
|
||||
if (!candidateRead.started || !candidateRead.current || !candidateRead.value || !isCurrent()) return;
|
||||
setStep(4);
|
||||
if (asRow(result.run.validation).complete === false) {
|
||||
const issueRead = await runImportPollFollowup(runId, () => isCurrent(), () => api.importIssues(runId));
|
||||
if (!issueRead.started || !issueRead.current) return;
|
||||
setIssues(collectionItems(issueRead.value));
|
||||
}
|
||||
if (!completionNotified.current.has(runId)) { completionNotified.current.add(runId); onComplete(); }
|
||||
setRunTerminalId(runId); setBusy(false);
|
||||
try { localStorage.removeItem(runStorageKey); } catch { /* The server task remains in task history. */ }
|
||||
} else if (['FAILED', 'CANCELLED'].includes(status)) {
|
||||
const issueRead = await runImportPollFollowup(runId, () => isCurrent(), () => api.importIssues(runId));
|
||||
if (!issueRead.started || !issueRead.current) return;
|
||||
setIssues(collectionItems(issueRead.value)); setRunTerminalId(runId); setBusy(false);
|
||||
try { localStorage.removeItem(runStorageKey); } catch { /* The server task remains in task history. */ }
|
||||
}
|
||||
} catch (value) { if (activeRef.current && runIdRef.current === runId) { reportError(value); setBusy(false); } }
|
||||
finally {
|
||||
pollLock.current = false;
|
||||
if (pollAgainAfterCurrent.current && activeRef.current && runIdRef.current === runId) {
|
||||
pollAgainAfterCurrent.current = false;
|
||||
void pollRun();
|
||||
}
|
||||
}
|
||||
}, [loadCandidate, onComplete, reportError, runId, runStorageKey]);
|
||||
useVisiblePolling(pollRun, 2000, active && Boolean(runId) && runTerminalId !== runId, true);
|
||||
const readFile = async (file?: File) => {
|
||||
if (!file) return; setBusy(true); setError(''); const ownGeneration = generation.current;
|
||||
if (!file || actionLock.current) return; actionLock.current = true; setBusy(true); setError(''); const ownGeneration = generation.current;
|
||||
try { const result = await api.previewSourceWorkbook(file); if (ownGeneration !== generation.current) return; setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow); setFieldMap(matchFields(options.fields[stage] || [], result.preview.headers)); setStep(1); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); if (input.current) input.current.value = ''; }
|
||||
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); if (input.current) input.current.value = ''; }
|
||||
};
|
||||
const changePreview = async (nextSheet: string, nextHeader: number, nextStage = stage, preferredMap?: Record<string, string>) => {
|
||||
if (!workbook) return; setBusy(true); setError('');
|
||||
if (!workbook || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try { const result = await api.sourceWorkbookPreview(workbook.uploadId, { sheetName: nextSheet, headerRow: nextHeader, stage: nextStage }); setWorkbook(result); setSheetName(result.preview.sheetName); setHeaderRow(result.preview.headerRow); const chosen = preferredMap || fieldMap; setFieldMap({ ...matchFields(options.fields[nextStage] || [], result.preview.headers), ...Object.fromEntries(Object.entries(chosen).filter(([, header]) => result.preview.headers.includes(header))) }); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const chooseTarget = (id: string) => { const selected = options.targets.find(item => item.documentId === id); setTargetId(id); if (selected) { setStage(selected.stage); setYear(selected.year); setMonth(selected.month); setScopeCode(selected.scopeCode); setFieldMap(matchFields(options.fields[selected.stage] || [], headers)); } };
|
||||
const beginImport = async () => {
|
||||
if (!workbook || missingFields.length || (mode === 'REPLACE' && !target)) return;
|
||||
if (!active || !workbook || missingFields.length || (mode === 'REPLACE' && !target) || actionLock.current) return;
|
||||
actionLock.current = true;
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
const configured = configuredSourceId ? { source: { id: configuredSourceId } } : await api.configureSourceWorkbook({ uploadId: workbook.uploadId, stage, year, month, sheetName, headerRow, fieldMap, mode: mode === 'REPLACE' ? 'REPLACE' : 'ADD', expectedCurrentReleaseId: options.currentReleaseId, ...(target ? { targetDocumentId: target.documentId, targetRevisionId: target.revisionId } : {}), reason: reason.trim() || `新增${year}年${month}月${stageName(stage)}数据`, scopeCode });
|
||||
setConfiguredSourceId(configured.source.id);
|
||||
const created = asRow(await api.startImport({ sourceIds: [configured.source.id], expectedCurrentReleaseId: options.currentReleaseId, idempotencyKey: importKey.current })); const nextRun = asRow(created.run || created); setRun(nextRun);
|
||||
if (!nextRun.id) throw new Error('服务端未返回计算任务,已接收的来源可稍后重新校验');
|
||||
try { localStorage.setItem(runStorageKey, String(nextRun.id)); } catch { /* Server task history remains available if local storage is unavailable. */ }
|
||||
} catch (value) { reportError(value); setBusy(false); }
|
||||
finally { actionLock.current = false; }
|
||||
};
|
||||
const rebuild = async () => {
|
||||
if (!active || actionLock.current) return; actionLock.current = true;
|
||||
setBusy(true); setError(''); setStep(3);
|
||||
try {
|
||||
if (!options.currentReleaseId) throw new Error('当前没有可用于重新计算的来源');
|
||||
const inspected = await api.governanceReleaseInspect(options.currentReleaseId); const members = asRows(inspected.members);
|
||||
const ids = options.currentSourcesComplete && options.currentSourceIds?.length ? options.currentSourceIds : members.map(member => sources.find(source => source.sha256 === member.sha256 && source.stage === member.stage && source.year === Number(member.sourceYear) && source.month === Number(member.sourceMonth))?.id);
|
||||
if (!ids.length || ids.some(id => !id)) throw new Error('部分原始文件当前不可用于重算,请重新上传缺少的原始文件。');
|
||||
const created = asRow(await api.startImport({ sourceIds: ids as string[], expectedCurrentReleaseId: options.currentReleaseId, idempotencyKey: importKey.current })); setRun(asRow(created.run || created));
|
||||
const created = asRow(await api.startImport({ sourceIds: ids as string[], expectedCurrentReleaseId: options.currentReleaseId, idempotencyKey: importKey.current }));
|
||||
const nextRun = asRow(created.run || created); if (!nextRun.id) throw new Error('服务端未返回计算任务编号');
|
||||
setRun(nextRun); try { localStorage.setItem(runStorageKey, String(nextRun.id)); } catch { /* Server task history remains available if local storage is unavailable. */ }
|
||||
} catch (value) { reportError(value); setBusy(false); }
|
||||
finally { actionLock.current = false; }
|
||||
};
|
||||
const reconcile = async () => {
|
||||
if (!release?.id) return; setBusy(true); setError('');
|
||||
if (!active || !release?.id || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try { const created = await api.createGovernanceReconciliation(String(release.id), { ...(options.currentReleaseId ? { baselineReleaseId: options.currentReleaseId } : {}), dimensions: ['overall', 'department', 'group', 'product', 'projectGroup'] }); const detail = asRow(created.reconciliation || created); setReconciliation(detail.id ? await api.governanceReconciliation(String(detail.id)) : detail); setConfirmDifferences(false); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const confirm = async () => {
|
||||
if (!reconciliation?.id) return; setBusy(true); setError('');
|
||||
if (!active || !reconciliation?.id || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try { const evidence = asRow(reconciliation.result); const result = await api.confirmGovernanceReconciliation(String(reconciliation.id), { expectedRowVersion: Number(reconciliation.rowVersion || 0), expectedDifferenceHash: String(reconciliation.differenceHash), ...(evidence.transitionDifferenceHash ? { expectedTransitionDifferenceHash: String(evidence.transitionDifferenceHash) } : {}), reason: differenceReason.trim() }); setReconciliation(result); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const publish = async () => {
|
||||
if (!release?.id) return; setBusy(true); setError('');
|
||||
if (!active || !release?.id || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try { await api.publishRelease(String(release.id), { expectedCurrentReleaseId: release.expectedCurrentReleaseId === undefined ? options.currentReleaseId : release.expectedCurrentReleaseId as string | null, idempotencyKey: publishKey.current, reason: reason.trim() || differenceReason.trim() || '经来源校验与候选基线对账后发布' }); setPublished(true); onComplete(); }
|
||||
catch (value) { reportError(value); } finally { setBusy(false); }
|
||||
catch (value) { reportError(value); } finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const evidence = asRow(reconciliation?.result); const comparisons = asRows(evidence.periodComparisons); const reconciliationErrors = Array.isArray(evidence.errors) ? evidence.errors : [];
|
||||
const publishReady = release?.complete === true && reconciliation?.publishReady === true;
|
||||
@@ -456,13 +543,13 @@ function DataUploadWizard({ user, mode, purpose, handoffSourceId, initialReason,
|
||||
const close = () => { generation.current++; onClose(); };
|
||||
return <Modal className="management-modal nc-workflow-modal" open width={1120} title={published ? purpose === 'WITHDRAW' ? '来源删除已发布' : '数据已发布' : purpose === 'WITHDRAW' ? '核对并发布删除候选' : resumeId ? '继续处理候选数据' : mode === 'REPLACE' ? '替换已有数据' : mode === 'REBUILD' ? '按当前来源重新计算' : '上传新数据'} onCancel={close} maskClosable={!busy} footer={<div className="nc-modal-footer"><span>{runId ? '关闭后任务继续,可在“数据接入”的“导入记录”查看;完成后从候选继续。' : '确认发布前,当前查询结果保持不变。'}</span><div>{step > 0 && step < 4 && !runId && !configuredSourceId && !busy && <Button onClick={() => { setStep(step - 1); setError(''); }}>上一步</Button>}<Button onClick={close}>{published ? '完成' : busy ? '关闭并稍后查看' : '关闭'}</Button>{!published && step === 1 && <Button type="primary" disabled={mode === 'REPLACE' && !target} loading={busy} onClick={() => { setStep(2); void changePreview(sheetName, headerRow); }}>下一步:匹配表头</Button>}{!published && step === 2 && <Button type="primary" loading={busy} disabled={Boolean(missingFields.length) || duplicateColumns || !sheetName} onClick={() => { if (workbook && (workbook.preview.headerRow !== headerRow || workbook.preview.sheetName !== sheetName)) { void changePreview(sheetName, headerRow); return; } setStep(3); }}>下一步:预览验证</Button>}{!published && step === 3 && !runId && mode !== 'REBUILD' && <Button type="primary" loading={busy} disabled={mode === 'REPLACE' && !reason.trim()} onClick={() => void beginImport()}>确认导入并校验</Button>}</div></div>}>
|
||||
<Steps className="nc-steps" current={published ? 5 : step} size="small" items={steps.map(title => ({ title }))} />
|
||||
{error && <Alert showIcon type="error" message="本次操作未完成" description={error} />}
|
||||
{error && <Alert showIcon type="error" message="本次操作未完成" description={error} action={resumeId && step === 4 ? <Button size="small" disabled={!active || busy || candidateReadLock.current} onClick={() => { if (!activeRef.current || candidateReadLock.current) return; candidateReadLock.current = true; setBusy(true); loadCandidate(resumeId).catch(reportError).finally(() => { candidateReadLock.current = false; setBusy(false); }); }}>重试读取候选</Button> : runId ? <Button size="small" disabled={!active || busy || pollLock.current} onClick={() => { if (!activeRef.current || pollLock.current) return; setBusy(true); void pollRun(); }}>重新获取处理结果</Button> : undefined} />}
|
||||
{published ? <div className="nc-success"><FileExcelOutlined /><h2>{purpose === 'WITHDRAW' ? '该来源已从当前查询结果移除' : '当前查询数据已更新'}</h2><p>来源原件和本次对账记录均已保留。</p></div> : <>
|
||||
{step === 0 && (mode === 'REBUILD' ? <div className="nc-rebuild-confirm"><h3>使用当前数据所用的全部来源重新计算</h3><p>计算使用当前启用的基础数据、对应关系和规则。完成后先生成候选,核对差异后再发布。</p><div className="nc-target-list">{options.targets.map(item => <div key={item.documentId}><Tag>{stageName(item.stage)}</Tag><strong>{item.year}年{item.month}月</strong><span>{item.sourceFile}</span></div>)}</div><Button type="primary" loading={busy} disabled={!options.targets.length} onClick={() => void rebuild()}>开始重新计算</Button></div> : <div className="nc-file-drop"><FileExcelOutlined /><h3>选择要{mode === 'REPLACE' ? '替换' : '上传'}的 Excel 文件</h3><p>支持 .xlsx;保留你的文件名,接下来选择数据期间和表头。</p><input className="visually-hidden-file" ref={input} type="file" accept=".xlsx" onChange={event => void readFile(event.target.files?.[0])} aria-label="选择质量数据Excel文件" /><Button type="primary" icon={<UploadOutlined />} loading={busy} onClick={() => input.current?.click()}>选择 Excel 文件</Button></div>)}
|
||||
{workbook && step > 0 && step < 4 && <div className="nc-file-summary"><FileExcelOutlined /><strong>{workbook.sourceFile}</strong><span>{stageName(stage)} · {year}年{month}月</span></div>}
|
||||
{step === 1 && <Form layout="vertical"><div className="nc-form-grid">{mode === 'REPLACE' ? <Form.Item className="nc-full-width" label="选择当前数据中的替换目标" required><Select {...readableSelectPopup} aria-label="选择当前数据中的替换目标" showSearch optionFilterProp="label" value={targetId || undefined} placeholder="选择年月、阶段和原文件" options={options.targets.map(item => ({ value: item.documentId, label: `${item.year}年${item.month}月 · ${stageName(item.stage)} · ${item.sourceFile}` }))} onChange={chooseTarget} /></Form.Item> : <><Form.Item label="数据阶段" required><Select aria-label="数据阶段" value={stage} options={[{ value: 'black', label: '黑片' }, { value: 'bright', label: '亮片' }]} onChange={value => { setStage(value); setFieldMap(matchFields(options.fields[value] || [], headers)); }} /></Form.Item><Form.Item label="统计年份" required><InputNumber aria-label="统计年份" min={2000} max={2100} value={year} onChange={value => { if (value) setYear(value); }} /></Form.Item><Form.Item label="统计月份" required><Select aria-label="统计月份" value={month} options={Array.from({ length: 12 }, (_, index) => ({ value: index + 1, label: `${index + 1}月` }))} onChange={setMonth} /></Form.Item>{options.scopes.length > 1 && <Form.Item label="数据范围" required><Select aria-label="数据范围" value={scopeCode} options={options.scopes.map(value => ({ value, label: value === 'ALL' ? '全部范围' : value }))} onChange={setScopeCode} /></Form.Item>}</>}</div>{target && <div className="nc-replacement"><span>原文件</span><strong>{target.sourceFile}</strong><ArrowRightOutlined /><span>新文件</span><strong>{workbook?.sourceFile}</strong></div>}<Form.Item label={mode === 'REPLACE' ? '替换理由' : '本次说明'} required={mode === 'REPLACE'}><Input.TextArea aria-label={mode === 'REPLACE' ? '替换理由' : '本次说明'} value={reason} rows={2} maxLength={1000} placeholder={mode === 'REPLACE' ? '例如:补齐遗漏记录,使用更新后的完整月表' : '可填写本次数据说明'} onChange={event => setReason(event.target.value)} /></Form.Item></Form>}
|
||||
{step === 2 && workbook && <><div className="nc-form-grid"><Form.Item label="工作表" required><Select aria-label="数据工作表" value={sheetName} options={workbook.sheets.map(sheet => ({ value: sheet.sheetName, label: sheet.sheetName }))} onChange={value => void changePreview(value, headerRow)} /></Form.Item><Form.Item label="表头在第几行" required><InputNumber aria-label="表头所在行" min={1} max={100} value={headerRow} onChange={value => { if (value) setHeaderRow(value); }} onBlur={() => { if (headerRow !== workbook.preview.headerRow) void changePreview(sheetName, headerRow); }} onPressEnter={() => void changePreview(sheetName, headerRow)} /></Form.Item></div><div className="nc-section-title"><h3>业务字段对应 Excel 中哪一列</h3><span>{duplicateColumns ? '同一 Excel 列不能对应多个业务字段' : missingFields.length ? `还需选择 ${missingFields.length} 个必填字段` : '必填字段已全部匹配'}</span></div><Spin spinning={busy}><ColumnMatching fields={fields} headers={headers} value={fieldMap} onChange={setFieldMap} /></Spin><h3>原表前几行</h3><SampleTable headers={headers} rows={workbook.preview.sampleRows.map(row => row.values)} /></>}
|
||||
{step === 3 && <>{!runId && workbook && <><div className="nc-review-facts"><div><small>统计期间</small><strong>{year}年{month}月 · {stageName(stage)}</strong></div><div><small>工作表与表头</small><strong>{sheetName} · 第{headerRow}行</strong></div><div><small>已匹配字段</small><strong>{Object.keys(fieldMap).length} 项</strong></div></div>{target && <Alert type="warning" showIcon message="即将使用新文件替换该期间的完整数据" description={`原文件:${target.sourceFile};新文件:${workbook.sourceFile}。本次先生成候选,最后发布后才更新查询结果。`} />}<SampleTable headers={Object.keys(fieldMap)} rows={workbook.preview.sampleRows.map(row => Object.fromEntries(Object.entries(fieldMap).map(([field, header]) => [field, row.values[header]])))} /><p className="nc-note">确认后由系统校验文件内容、数据范围及对应关系,并计算候选结果。</p></>}{(runId || (busy && mode === 'REBUILD')) && <div className="nc-processing"><Spin spinning={busy} /><h3>{statusLabel[String(run?.status)] || '正在创建计算任务'}</h3><Progress percent={Number(run?.total) > 0 ? Math.min(100, Math.round(Number(run?.processed || 0) / Number(run?.total) * 100)) : 0} status={run?.status === 'FAILED' ? 'exception' : 'active'} /><p>已处理 {txt(run?.processed || 0)} / {txt(run?.total)} 行</p>{run?.errorMessage ? <Alert type="error" showIcon message={txt(run.errorMessage)} /> : null}{!busy && runId && !['FAILED', 'CANCELLED'].includes(String(run?.status)) && <Button onClick={() => { setBusy(true); setPollAttempt(previous => previous + 1); }}>重新获取处理结果</Button>}</div>}<ValidationNotice value={run?.validation} /></>}
|
||||
{step === 3 && <>{!runId && workbook && <><div className="nc-review-facts"><div><small>统计期间</small><strong>{year}年{month}月 · {stageName(stage)}</strong></div><div><small>工作表与表头</small><strong>{sheetName} · 第{headerRow}行</strong></div><div><small>已匹配字段</small><strong>{Object.keys(fieldMap).length} 项</strong></div></div>{target && <Alert type="warning" showIcon message="即将使用新文件替换该期间的完整数据" description={`原文件:${target.sourceFile};新文件:${workbook.sourceFile}。本次先生成候选,最后发布后才更新查询结果。`} />}<SampleTable headers={Object.keys(fieldMap)} rows={workbook.preview.sampleRows.map(row => Object.fromEntries(Object.entries(fieldMap).map(([field, header]) => [field, row.values[header]])))} /><p className="nc-note">确认后由系统校验文件内容、数据范围及对应关系,并计算候选结果。</p></>}{(runId || (busy && mode === 'REBUILD')) && <div className="nc-processing"><Spin spinning={busy} /><h3>{statusLabel[String(run?.status)] || '正在创建计算任务'}</h3><Progress percent={Number(run?.total) > 0 ? Math.min(100, Math.round(Number(run?.processed || 0) / Number(run?.total) * 100)) : 0} status={run?.status === 'FAILED' ? 'exception' : 'active'} /><p>已处理 {txt(run?.processed || 0)} / {txt(run?.total)} 行</p>{run?.errorMessage ? <Alert type="error" showIcon message={txt(run.errorMessage)} /> : null}{!busy && runId && !['FAILED', 'CANCELLED'].includes(String(run?.status)) && <Button disabled={!active || pollLock.current} onClick={() => { if (!activeRef.current || pollLock.current) return; setBusy(true); void pollRun(); }}>重新获取处理结果</Button>}</div>}<ValidationNotice value={run?.validation} /></>}
|
||||
{step === 4 && <Spin spinning={busy}><div className="nc-review-facts"><div><small>候选数据</small><strong>待核对</strong></div><div><small>来源校验</small><strong>{release?.complete === true ? '通过' : '尚未通过'}</strong></div><div><small>基线对账</small><strong>{statusLabel[String(reconciliation?.status)] || '待执行'}</strong></div></div><ValidationNotice value={release?.validation || run?.validation} />{reconciliationErrors.length > 0 && <Alert showIcon type="error" message="对账存在阻断事项" description={reconciliationErrors.map(txt).join(';')} />}<div className="nc-section-title"><h3>与当前数据的差异</h3><Button icon={<ReloadOutlined />} loading={busy} disabled={!release?.id} onClick={() => void reconcile()}>{reconciliation ? '重新对账' : '执行基线对账'}</Button></div>{comparisons.length > 0 ? <Table size="small" bordered dataSource={comparisons} rowKey={(row, index) => `${row.dimension}:${row.key}:${index}`} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 900 }} columns={[{ title: '期间', width: 130, render: (_, row) => { const period = asRow(row.period); return `${txt(period.year)}年${period.month ? `${txt(period.month)}月` : period.quarter ? `第${txt(period.quarter)}季度` : '全年'}`; } }, { title: '维度 / 对象', width: 200, render: (_, row) => `${({ overall: '总体', department: '产业部', group: '业务分组', product: '产品', projectGroup: '项目组' } as Record<string, string>)[String(row.dimension)] || txt(row.dimension)} / ${txt(row.key)}` }, { title: '原综合率', width: 120, render: (_, row) => ratio(asRow(row.before).compositeRate) }, { title: '新综合率', width: 120, render: (_, row) => ratio(asRow(row.after).compositeRate) }, { title: '差异', render: (_, row) => asRows(row.differences).map(item => `${metricLabel(item.path)}:${txt(item.before)} → ${txt(item.after)}`).join(';') || '一致' }]} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={reconciliation ? '本次没有可展示的期间比较;以对账结论为准' : '执行对账后在这里查看期间和指标差异'} />}{reconciliation?.status === 'REVIEW_REQUIRED' && <div className="nc-difference-confirm"><Alert type="warning" showIcon message={`发现 ${txt(evidence.differenceCount)} 项差异,需要发布者确认`} />{canPublish ? <><Input.TextArea aria-label="业务差异确认理由" rows={2} value={differenceReason} maxLength={1000} placeholder="填写差异原因及确认依据" onChange={event => setDifferenceReason(event.target.value)} /><Checkbox checked={confirmDifferences} onChange={event => setConfirmDifferences(event.target.checked)}>我已核对上方差异,并确认新数据正确</Checkbox><Button type="primary" disabled={!confirmDifferences || !differenceReason.trim() || busy} onClick={() => void confirm()}>确认差异并验收</Button></> : <p>候选已保存,请交由有数据发布权限的同事完成差异确认。</p>}</div>}{canPublish ? <div className="nc-publish-confirm"><Checkbox disabled={!publishReady} checked={publishConfirmed} onChange={event => setPublishConfirmed(event.target.checked)}>{purpose === 'WITHDRAW' ? '我确认发布此删除候选,从当前查询结果移除已批准的来源' : '我确认将此候选发布为当前查询数据'}{target ? `,替换${target.year}年${target.month}月${stageName(target.stage)}` : ''}</Checkbox><Button size="large" type="primary" disabled={!publishReady || !publishConfirmed || busy} onClick={() => void publish()}>确认发布</Button>{!publishReady && <span>来源校验和基线对账通过后可发布。</span>}</div> : <Alert showIcon type="info" message="候选数据已保存,等待有权限的同事发布" description={<><span>当前账号没有数据发布权限。可复制处理链接交接,正式查询数据尚未更新。</span><Button type="link" onClick={() => { const link = new URL(window.location.href); link.searchParams.set('page', 'sources'); if (handoffSourceId) { link.searchParams.set('sourceDeleteId', handoffSourceId); link.searchParams.delete('candidateReleaseId'); } else { link.searchParams.set('candidateReleaseId', String(release?.id || '')); link.searchParams.delete('sourceDeleteId'); } void navigator.clipboard.writeText(link.toString()).then(() => message.success('处理链接已复制')).catch(reportError); }}>复制处理链接</Button></>} />}</Spin>}
|
||||
{issues.length > 0 && <><h3>需要处理的来源行</h3><Table size="small" bordered dataSource={issues} rowKey={(row, index) => String(row.id || index)} pagination={{ pageSize: 15 }} columns={[{ title: '工作表', dataIndex: 'sheet', width: 120 }, { title: '行号', dataIndex: 'rowNumber', width: 80 }, { title: '字段', dataIndex: 'field', width: 130 }, { title: '问题说明', dataIndex: 'message' }]} /></>}
|
||||
</>}
|
||||
@@ -487,6 +574,7 @@ export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, s
|
||||
const [mode, setMode] = useState<'MERGE' | 'REPLACE'>('MERGE'); const [columns, setColumns] = useState<Record<string, string>>({});
|
||||
const [name, setName] = useState(''); const [reason, setReason] = useState(''); const [confirmed, setConfirmed] = useState(false);
|
||||
const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [result, setResult] = useState<Row | null>(null);
|
||||
const actionLock = useRef(false);
|
||||
const [preparedDefinition, setPreparedDefinition] = useState<Row | null>(null);
|
||||
const [preparedReleaseId, setPreparedReleaseId] = useState<string | null>(null);
|
||||
const workflowOperation = useDataWorkflowOperation('mapping-workbook-import', () => { onComplete(); message.success('基础数据已保存,报表已更新'); });
|
||||
@@ -523,7 +611,7 @@ export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, s
|
||||
setColumns(autoMatch(nextSheet?.headers || [], nextKind, format, suggestedTables, nextSheet?.name || sheetName));
|
||||
};
|
||||
const readFile = async (file?: File) => {
|
||||
if (!file) return; setBusy(true); setError('');
|
||||
if (!file || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try {
|
||||
const response = await api.previewMasterWorkbook(file); setPreview(response);
|
||||
const nextKind = response.standardBundleAvailable ? 'standardBundle' : (selectedKind === 'standardBundle' ? kind === 'masterData' ? 'departments' : 'categoryLookup' : selectedKind);
|
||||
@@ -535,10 +623,10 @@ export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, s
|
||||
setName(simplified ? configurationDateTime(new Date()) : `${nextKind === 'standardBundle' ? '整本基础数据' : kindLabel(nextKind)}·${file.name.replace(/\.xlsx$/i, '')}`.slice(0, 120));
|
||||
setResult(null); setConfirmed(false);
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(failure(value)); }
|
||||
finally { setBusy(false); if (fileInput.current) fileInput.current.value = ''; }
|
||||
finally { actionLock.current = false; setBusy(false); if (fileInput.current) fileInput.current.value = ''; }
|
||||
};
|
||||
const submit = async () => {
|
||||
if (!preview || !base || !sheet) return; setBusy(true); setError('');
|
||||
if (!preview || !base || !sheet || actionLock.current) return; actionLock.current = true; setBusy(true); setError('');
|
||||
try {
|
||||
if (simplified && preparedDefinition) {
|
||||
await workflowOperation.start(() => api.applyDataWorkflow({ kind: 'mapping', name: name.trim(), definition: preparedDefinition, description: '测试阶段基础数据导入', expectedCurrentReleaseId: preparedReleaseId }));
|
||||
@@ -563,7 +651,7 @@ export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, s
|
||||
}
|
||||
setResult(response); onComplete();
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(failure(value)); }
|
||||
finally { setBusy(false); }
|
||||
finally { actionLock.current = false; setBusy(false); }
|
||||
};
|
||||
const canSubmit = Boolean(base && name.trim() && (simplified || (reason.trim() && confirmed)) && (bundle ? preview?.standardBundleAvailable && suggestedTables.length : sheet && activeColumns.every(column => !column.required || columns[column.key])));
|
||||
return <>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Descriptions, Form, Input, Modal, Tabs } from 'antd';
|
||||
import { api } from './api';
|
||||
import type { AuthUser } from './types';
|
||||
@@ -20,6 +20,7 @@ export default function PersonalAccount({ user, tab, onClose, onUserChange, onUn
|
||||
const [form] = Form.useForm<PasswordValues>();
|
||||
const [activeTab, setActiveTab] = useState<AccountTab>('profile');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const savingRef = useRef(false);
|
||||
const [error, setError] = useState('');
|
||||
const forced = user.forcePasswordChange === true;
|
||||
const open = tab !== null || forced;
|
||||
@@ -29,6 +30,8 @@ export default function PersonalAccount({ user, tab, onClose, onUserChange, onUn
|
||||
}, [open, tab, forced, form]);
|
||||
|
||||
const save = async (values: PasswordValues) => {
|
||||
if (savingRef.current) return;
|
||||
savingRef.current = true;
|
||||
setBusy(true); setError('');
|
||||
try {
|
||||
await api.changePassword(values.currentPassword, values.newPassword);
|
||||
@@ -38,7 +41,7 @@ export default function PersonalAccount({ user, tab, onClose, onUserChange, onUn
|
||||
message.success('密码已修改,下次登录请使用新密码');
|
||||
} catch (failure) {
|
||||
if (!onUnauthorized(failure)) setError(failure instanceof Error ? failure.message : '修改失败,请重试');
|
||||
} finally { setBusy(false); }
|
||||
} finally { savingRef.current = false; setBusy(false); }
|
||||
};
|
||||
|
||||
return <Modal className="personal-account-modal" open={open} title="个人账户" width={520} footer={null}
|
||||
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
CheckOutlined,
|
||||
DatabaseOutlined,
|
||||
DownOutlined,
|
||||
DeploymentUnitOutlined,
|
||||
KeyOutlined,
|
||||
LineChartOutlined,
|
||||
LoadingOutlined,
|
||||
@@ -35,12 +34,12 @@ import { workspaceThemes, type WorkspaceThemeId } from './ui-themes';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import PersonalAccount, { type AccountTab } from './PersonalAccount';
|
||||
|
||||
import { CachedWorkspacePages, type WorkspaceNavigation } from './CachedWorkspacePages';
|
||||
import { CachedWorkspacePages, preloadWorkspacePage, type WorkspaceNavigation } from './CachedWorkspacePages';
|
||||
|
||||
export type PageKey = 'overall' | 'department' | 'group' | 'product' | 'blackProduct' | 'brightProduct' | 'basis' | 'analysis' | 'sources' | 'imports' | 'rules' | 'mappings' | 'masterData' | 'tasks' | 'access';
|
||||
|
||||
const pageNames: Record<PageKey, string> = {
|
||||
overall: '总体汇总', department: '产业部汇总', group: '产业部-业务分组', product: '产品汇总', blackProduct: '黑片汇总', brightProduct: '亮片汇总',
|
||||
overall: '总体合格率', department: '产业部', group: '产业部-业务分组', product: '产品汇总', blackProduct: '黑片汇总', brightProduct: '亮片汇总',
|
||||
basis: '数据与计算依据', analysis: '智能分析', sources: '数据接入', imports: '导入与校验',
|
||||
rules: '计算规则', mappings: '对应关系', masterData: '基础数据', tasks: '任务与监控', access: '权限与审计',
|
||||
};
|
||||
@@ -65,9 +64,8 @@ const navGroups = [
|
||||
{
|
||||
label: '质量查询',
|
||||
items: [
|
||||
['overall', '总体汇总', AppstoreOutlined],
|
||||
['department', '产业部汇总', ApartmentOutlined],
|
||||
['group', '产业部-业务分组', DeploymentUnitOutlined],
|
||||
['overall', '总体合格率', AppstoreOutlined],
|
||||
['department', '产业部', ApartmentOutlined],
|
||||
['product', '产品汇总', DatabaseOutlined],
|
||||
['blackProduct', '黑片汇总', DatabaseOutlined],
|
||||
['brightProduct', '亮片汇总', DatabaseOutlined],
|
||||
@@ -140,6 +138,8 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
// Fetch only the selected page's code while identity validation runs; data stays gated.
|
||||
void preloadWorkspacePage(pageFromLocation()).catch(() => {});
|
||||
(async () => {
|
||||
try {
|
||||
await api.refreshCsrf();
|
||||
@@ -195,11 +195,10 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
|
||||
return (
|
||||
<div className={`app-shell${sidebarCollapsed ? ' sidebar-collapsed' : ''}`}>
|
||||
<aside className="sidebar" id="workspace-sidebar">
|
||||
<button className="brand" onClick={() => navigate('overall')} aria-label="回到总体汇总">
|
||||
<button className="brand" onClick={() => navigate('overall')} aria-label="回到总体合格率">
|
||||
<span className="brand-mark" aria-hidden="true"><i /><i /><i /></span>
|
||||
<span className="brand-copy">质量数据分析平台</span>
|
||||
</button>
|
||||
<div className="workspace-caption">分析工作台</div>
|
||||
<nav className="side-navigation" aria-label="主导航">
|
||||
{navGroups.map(group => (
|
||||
<div className="nav-group" key={group.label}>
|
||||
|
||||
+291
-255
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,57 @@
|
||||
import type { ReactNode, Ref } from 'react';
|
||||
import { Button, Input, Segmented, Select, Spin } from 'antd';
|
||||
import { DownloadOutlined, SearchOutlined } from '@ant-design/icons';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
|
||||
type Granularity = 'month' | 'quarter' | 'year';
|
||||
type TrendMode = 'production' | 'defects' | 'data';
|
||||
type DefectDisplay = 'weight' | 'rate';
|
||||
|
||||
export function QueryTrendPanel({ panelRef, id, mode, onMode, granularity, onGranularity, defectDisplay, onDefectDisplay, fullFields, onFullFields, object, onObject, objects, scopeName, stageSwitch, children }: {
|
||||
panelRef?: Ref<HTMLElement>; id?: string; mode: TrendMode; onMode: (value: TrendMode) => void;
|
||||
granularity: Granularity; onGranularity: (value: Granularity) => void;
|
||||
defectDisplay: DefectDisplay; onDefectDisplay: (value: DefectDisplay) => void;
|
||||
fullFields: boolean; onFullFields: (value: boolean) => void;
|
||||
object?: string; onObject: (value?: string) => void; objects: Array<{ label: string; value: string }>;
|
||||
scopeName: string; stageSwitch?: ReactNode; children: ReactNode;
|
||||
}) {
|
||||
const periodName = granularity === 'month' ? '月度' : granularity === 'quarter' ? '季度' : '年度';
|
||||
return <section className="panel section-panel trend-panel" ref={panelRef} id={id}>
|
||||
<div className="section-heading-row trend-heading-row">
|
||||
<div className="section-heading"><h2>{periodName}变化趋势</h2></div>
|
||||
<Segmented value={mode} options={[{ label: '合格率与产量', value: 'production' }, { label: '不良率', value: 'defects' }, { label: `${periodName}数据`, value: 'data' }]} onChange={onMode} aria-label="趋势视图" />
|
||||
</div>
|
||||
<div className="trend-controls">
|
||||
{mode === 'data' && <Segmented value={defectDisplay} options={[{ label: '不良重量', value: 'weight' }, { label: '不良率', value: 'rate' }]} onChange={onDefectDisplay} aria-label="趋势不良显示方式" />}
|
||||
{mode === 'data' && <Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整指标', value: 'full' }]} onChange={value => onFullFields(value === 'full')} aria-label="趋势字段显示" />}
|
||||
<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={granularity} options={[{ label: '按月', value: 'month' }, { label: '按季度', value: 'quarter' }, { label: '按年度', value: 'year' }]} onChange={onGranularity} aria-label="趋势粒度" /></label>
|
||||
<label className="query-field trend-object"><span>趋势对象</span><Select {...readableSelectPopup} allowClear placeholder={`当前${scopeName}筛选`} value={object || undefined} options={objects} onChange={onObject} aria-label="趋势对象" /></label>
|
||||
{mode !== 'data' && stageSwitch}
|
||||
</div>
|
||||
{children}
|
||||
</section>;
|
||||
}
|
||||
|
||||
export function QueryTablePanel({ heading, busy, search, onSearchChange, onSearch, productView = true, searchPlaceholder, searchDisabled = false, searchUnavailable = false, fullFields, onFullFields, defectDisplay, onDefectDisplay, returnControls, exporting, exportDisabled, onExport, children }: {
|
||||
heading: ReactNode; busy?: boolean; search: string; onSearchChange: (value: string) => void; onSearch: () => void;
|
||||
productView?: boolean; searchPlaceholder?: string; searchDisabled?: boolean; searchUnavailable?: boolean;
|
||||
fullFields: boolean; onFullFields: (value: boolean) => void; defectDisplay: DefectDisplay; onDefectDisplay: (value: DefectDisplay) => void;
|
||||
returnControls?: ReactNode; exporting: boolean; exportDisabled: boolean; onExport: () => void; children: ReactNode;
|
||||
}) {
|
||||
return <section className="panel section-panel table-panel">
|
||||
<div className="section-heading-row">
|
||||
{heading}
|
||||
<div className="table-tools">
|
||||
{busy && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}
|
||||
<Input allowClear={!searchDisabled} disabled={searchDisabled} maxLength={productView ? 256 : undefined} prefix={<SearchOutlined />} placeholder={searchPlaceholder || (productView ? '输入关键词或完整产品名称' : '搜索汇总对象')} value={search} onChange={event => onSearchChange(event.target.value)} onPressEnter={onSearch} aria-label={productView ? '搜索产品名称并同步筛选指标和趋势' : '搜索汇总对象'} />
|
||||
<Button type="primary" disabled={searchDisabled || searchUnavailable} onClick={onSearch} aria-label="开始搜索">搜索</Button>
|
||||
<Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整字段', value: 'full' }]} onChange={value => onFullFields(value === 'full')} aria-label="字段显示" />
|
||||
<Segmented value={defectDisplay} options={[{ label: '不良重量', value: 'weight' }, { label: '不良率', value: 'rate' }]} onChange={onDefectDisplay} aria-label="不良显示方式" />
|
||||
{returnControls}
|
||||
<Button type="primary" className="query-export-button" icon={<DownloadOutlined />} aria-label="Excel导出" loading={exporting} disabled={exportDisabled} onClick={onExport}>Excel导出</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mobile-scroll-hint">横向滑动查看完整指标</div>
|
||||
{children}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||
|
||||
export function useRetainedResult<T>(current: T | null | undefined): T | null {
|
||||
const previous = useRef<T | null>(null);
|
||||
useLayoutEffect(() => { if (current != null) previous.current = current; }, [current]);
|
||||
return current ?? previous.current;
|
||||
}
|
||||
|
||||
function numericText(text: string) {
|
||||
const match = text.match(/^(-?[\d,]+(?:\.\d+)?)(%| kg)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number(match[1].replaceAll(',', ''));
|
||||
return Number.isFinite(value) ? { value, decimals: match[1].split('.')[1]?.length || 0, unit: match[2] || '' } : null;
|
||||
}
|
||||
|
||||
export function interpolateMetricText(from: string, to: string, progress: number): string {
|
||||
const start = numericText(from), target = numericText(to);
|
||||
if (!start || !target || start.unit !== target.unit || progress >= 1) return to;
|
||||
const value = start.value + (target.value - start.value) * Math.max(0, progress);
|
||||
return value.toLocaleString('en-US', { minimumFractionDigits: target.decimals, maximumFractionDigits: target.decimals }) + target.unit;
|
||||
}
|
||||
|
||||
export function useAnimatedMetricText(value: string): string {
|
||||
const [display, setDisplay] = useState(value);
|
||||
const shown = useRef(value);
|
||||
useLayoutEffect(() => {
|
||||
const from = shown.current;
|
||||
const commit = (text: string) => { shown.current = text; setDisplay(text); };
|
||||
if (from === value) return;
|
||||
const startValue = numericText(from), targetValue = numericText(value);
|
||||
if (!startValue || !targetValue || startValue.unit !== targetValue.unit || window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
|
||||
commit(value); return;
|
||||
}
|
||||
const start = performance.now();
|
||||
let frame = 0;
|
||||
const update = (now: number) => {
|
||||
const progress = Math.min(1, (now - start) / 520);
|
||||
commit(interpolateMetricText(from, value, 1 - (1 - progress) ** 3));
|
||||
if (progress < 1) frame = requestAnimationFrame(update);
|
||||
};
|
||||
frame = requestAnimationFrame(update);
|
||||
// 连续点击时从此刻的显示值继续,不回到上一次请求的起点。
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [value]);
|
||||
return display;
|
||||
}
|
||||
|
||||
export function AnimatedMetricText({ value }: { value: string }) {
|
||||
return <span className="animated-metric-text">{useAnimatedMetricText(value)}</span>;
|
||||
}
|
||||
|
||||
export function SmoothTableFrame({ children, busy, blocked }: { children: ReactNode; busy: boolean; blocked: boolean }) {
|
||||
const content = useRef<HTMLDivElement>(null);
|
||||
const [height, setHeight] = useState<number>();
|
||||
useLayoutEffect(() => {
|
||||
const node = content.current;
|
||||
if (!node) return;
|
||||
const measure = () => { if (node.offsetHeight > 0) setHeight(node.offsetHeight); };
|
||||
measure();
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(node);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
useLayoutEffect(() => { if (content.current && content.current.offsetHeight > 0) setHeight(content.current.offsetHeight); }, [children]);
|
||||
return <div className="smooth-table-frame" style={{ height }}>
|
||||
<div ref={content} className="query-table-content" aria-busy={busy} inert={blocked}>{children}</div>
|
||||
</div>;
|
||||
}
|
||||
+106
-43
@@ -1,84 +1,123 @@
|
||||
import { loadedQueryScope, queryForLocation } from './queryLoadingScope';
|
||||
import { SmoothTableFrame, useRetainedResult } from './QueryResultMotion';
|
||||
import { queryScrapWeight } from './queryMetricValues';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Empty, Input, Modal, Segmented, Select, Spin } from 'antd';
|
||||
import { DownloadOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
|
||||
import { Alert, App, Button, Empty, Modal, Segmented, Select, Spin } from 'antd';
|
||||
import { ArrowLeftOutlined, DownOutlined, UpOutlined } from '@ant-design/icons';
|
||||
import { api, decodeQueryValueList, encodeQueryValueList } from './api';
|
||||
import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHeading, RecordsDrawer, TrendChart, fullYearTrend, queryFromLocation } from './QueryPage';
|
||||
import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHeading, RecordsDrawer, TrendChart, TrendTable, fullYearTrend, queryFromLocation } from './QueryPage';
|
||||
import { StageSourceFilters } from './StageSourceFilters';
|
||||
import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery';
|
||||
import { usePageCache } from './pageCache';
|
||||
import { previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
|
||||
import { useDelayedIndicator } from './useDelayedBusy';
|
||||
import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import { readableMetricFormula } from './publicDataDisplay';
|
||||
import type { MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage } from './types';
|
||||
import { defaultFullMetricFields } from './metricColumnPlan';
|
||||
import type { MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage, TrendResponse } from './types';
|
||||
import { QueryTrendPanel, QueryTablePanel } from './QueryPanels';
|
||||
import { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection';
|
||||
import './stage-product.css';
|
||||
|
||||
const weight=(v:number|null|undefined)=>typeof v==='number'?v.toLocaleString('zh-CN',{maximumFractionDigits:2}):'—';
|
||||
const rate=(v:number|null|undefined)=>typeof v==='number'?`${(v*100).toFixed(2)}%`:'—';
|
||||
export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onUnauthorized:(error:unknown)=>boolean}) {
|
||||
const {message}=App.useApp();const {active,initialSearch,refreshKey,onLocationChange}=usePageCache();
|
||||
const {message}=App.useApp();const {active,initialSearch,refreshKey,onLocationChange,currentReleaseId}=usePageCache();
|
||||
const [initial]=useState(()=>queryFromLocation(initialSearch));const defaults=previousCompleteMonth();
|
||||
const automaticPeriod=useRef(!initial.year&&!initial.month&&!initial.quarter);
|
||||
const [period,setPeriod]=useState<PeriodKind>(initial.quarter?'quarter':initial.month?'month':initial.year?'year':'month');
|
||||
const [year,setYear]=useState(initial.year||defaults.year);const [month,setMonth]=useState(initial.month||defaults.month);const [quarter,setQuarter]=useState(initial.quarter||previousCompleteQuarter().quarter);
|
||||
const [department,setDepartment]=useState(()=>decodeQueryValueList(initial.department));const [group,setGroup]=useState(()=>decodeQueryValueList(initial.group));const [product,setProduct]=useState(()=>decodeQueryValueList(initial.product));const [projectGroup,setProjectGroup]=useState(()=>decodeQueryValueList(initial.projectGroup));
|
||||
const [sourceFilters,setSourceFilters]=useState<SourceColumnFilter[]>(initial.columnFilters||[]);const [search,setSearch]=useState(initial.productSearch||'');const includeUnassigned=true;
|
||||
const [sourceFilters,setSourceFilters]=useState<SourceColumnFilter[]>(initial.columnFilters||[]);const [search,setSearch]=useState(initial.productSearch||'');const [appliedSearch,setAppliedSearch]=useState(initial.productSearch||'');const includeUnassigned=true;
|
||||
const [moreFiltersOpen,setMoreFiltersOpen]=useState(false);
|
||||
const [options,setOptions]=useState<OptionsResponse|null>(null);const [catalog,setCatalog]=useState<{releaseId:string;sourceFields:SourceColumnField[]}|null>(null);const [supportError,setSupportError]=useState('');const [supportLoading,setSupportLoading]=useState(true);
|
||||
const [applied,setApplied]=useState<QueryParams|null>(null);const [revision,setRevision]=useState(0);const [response,setResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [loading,setLoading]=useState(false);const [failure,setFailure]=useState<{key:string;message:string}|null>(null);
|
||||
const [defectDisplay,setDefectDisplay]=useState<'weight'|'rate'>('weight');
|
||||
const [fullFields,setFullFields]=useState(true);const [rateBasis,setRateBasis]=useState<'original'|'withoutHeadquartersScrap'>('original');const [basisOpen,setBasisOpen]=useState(false);const [trendMode,setTrendMode]=useState<'production'|'defects'|'data'>('production');
|
||||
const [trendFullFields,setTrendFullFields]=useState(()=>defaultFullMetricFields(stage==='black'?'blackProduct':'brightProduct'));
|
||||
const [drilledProduct,setDrilledProduct]=useState('');const drillParentSearch=useRef('');
|
||||
const [trendGranularity,setTrendGranularity]=useState<'month'|'quarter'|'year'>('month');
|
||||
const [trendResponse,setTrendResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [trendError,setTrendError]=useState('');const [trendLoading,setTrendLoading]=useState(false);
|
||||
const [trendResponse,setTrendResponse]=useState<{key:string;value:TrendResponse;query:QueryParams}|null>(null);const [trendRevision,setTrendRevision]=useState(0);const [trendError,setTrendError]=useState('');const [trendLoading,setTrendLoading]=useState(false);
|
||||
const [recordVisible,setRecordVisible]=useState(false);const [records,setRecords]=useState<{row:MetricRow|null;query:QueryParams}|null>(null);const exporter=useRef<{exportExcel:()=>Promise<void>}>(null);const [exporting,setExporting]=useState(false);
|
||||
const label=stage==='black'?'黑片':'亮片';
|
||||
const supportGeneration=useRef(0);const supportController=useRef<AbortController|null>(null);
|
||||
const loadSupport=useCallback(async()=>{
|
||||
const generation=++supportGeneration.current;supportController.current?.abort();const controller=new AbortController();supportController.current=controller;
|
||||
setSupportLoading(true);setSupportError('');
|
||||
try{const [choices,source]=await Promise.all([api.options(),api.sourceColumnCatalog()]);setOptions(choices);setCatalog(source);}
|
||||
catch(error){if(!onUnauthorized(error))setSupportError(error instanceof Error?error.message:'查询条件读取失败');}
|
||||
finally{setSupportLoading(false);}
|
||||
},[onUnauthorized]);
|
||||
useEffect(()=>{if(active)void loadSupport();},[active,refreshKey,loadSupport]);
|
||||
try{const [choices,source]=await Promise.all([api.options(controller.signal),api.sourceColumnCatalog(initial.releaseId||currentReleaseId||undefined,controller.signal)]);if(generation!==supportGeneration.current)return;if(automaticPeriod.current){const available=defaultQueryMonth(choices);setYear(available.year);setMonth(available.month);automaticPeriod.current=false;}setOptions(choices);setCatalog(source);}
|
||||
catch(error){if(generation===supportGeneration.current&&!onUnauthorized(error))setSupportError(error instanceof Error?error.message:'查询条件读取失败');}
|
||||
finally{if(generation===supportGeneration.current)setSupportLoading(false);}
|
||||
},[onUnauthorized,initial.releaseId,currentReleaseId]);
|
||||
useEffect(()=>{if(active)void loadSupport();return()=>{supportGeneration.current++;supportController.current?.abort();};},[active,refreshKey,loadSupport]);
|
||||
const fields=useMemo(()=>catalog?.sourceFields.filter(field=>field.type==='source_value'&&field.stages.includes(stage))||[],[catalog,stage]);
|
||||
const draft=useMemo(()=>stageProductQuery({year,...(period==='month'?{month}:period==='quarter'?{quarter}:{}),department:encodeQueryValueList(department),group:encodeQueryValueList(group),product:encodeQueryValueList(product),projectGroup:encodeQueryValueList(projectGroup),productSearch:search.trim()||undefined,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,sourceFilters),[year,period,month,quarter,department,group,product,projectGroup,search,includeUnassigned,catalog,stage,sourceFilters]);
|
||||
// A new release resets the data binding; hidden cached pages never issue queries.
|
||||
useEffect(()=>{if(catalog)setApplied(draft);},[catalog]);
|
||||
const exactProductSearch=useMemo(()=>(options?.products||[]).find(name=>name.trim().toLocaleLowerCase()===appliedSearch.trim().toLocaleLowerCase())||'', [options,appliedSearch]);
|
||||
const queryProducts=useMemo(()=>drilledProduct?[drilledProduct]:exactProductSearch?product.length&&!product.includes(exactProductSearch)?['__codex_no_product_search_match__']:[exactProductSearch]:product,[drilledProduct,exactProductSearch,product]);
|
||||
useEffect(()=>{setDrilledProduct('');},[year,department,group,product,projectGroup,sourceFilters]);
|
||||
const draft=useMemo(()=>stageProductQuery({year,...(period==='month'?{month}:period==='quarter'?{quarter}:{}),department:encodeQueryValueList(department),group:encodeQueryValueList(group),product:encodeQueryValueList(queryProducts),projectGroup:encodeQueryValueList(projectGroup),productSearch:drilledProduct?undefined:appliedSearch.trim()||undefined,includeUnassigned,view:'product',trendGranularity:'month',releaseId:initial.releaseId||currentReleaseId||catalog?.releaseId},stage,sourceFilters),[year,period,month,quarter,department,group,queryProducts,drilledProduct,projectGroup,appliedSearch,includeUnassigned,catalog,stage,sourceFilters,initial.releaseId,currentReleaseId]);
|
||||
// Apply organizational/source filters directly, like the other query pages. Product text search keeps its explicit submit.
|
||||
useEffect(()=>{if(active&&catalog&&!supportLoading&&!supportError)setApplied(previous=>JSON.stringify(previous)===JSON.stringify(draft)?previous:draft);},[active,catalog,draft,supportLoading,supportError]);
|
||||
const queryKey=JSON.stringify({query:applied,revision});const current=response?.key===queryKey?response.value:null;const error=failure?.key===queryKey?failure.message:'';
|
||||
useEffect(()=>{
|
||||
if(!active||!applied||supportError)return;const controller=new AbortController();setLoading(true);setFailure(null);
|
||||
void api.metrics(applied,controller.signal).then(value=>{if(!controller.signal.aborted)setResponse({key:queryKey,value});}).catch(e=>{if(!controller.signal.aborted&&!onUnauthorized(e))setFailure({key:queryKey,message:e instanceof Error?e.message:'查询失败'});}).finally(()=>{if(!controller.signal.aborted)setLoading(false);});
|
||||
return()=>controller.abort();
|
||||
},[active,queryKey,onUnauthorized,supportError]);
|
||||
useEffect(()=>{if(!active||!applied)return;const bytes=new TextEncoder().encode(JSON.stringify({query:applied}));const encoded=btoa(Array.from(bytes,b=>String.fromCharCode(b)).join('')).replace(/=/g,'').replace(/\+/g,'-').replace(/\//g,'_');const url=`?page=${stage==='black'?'blackProduct':'brightProduct'}&context=${encoded}`;window.history.replaceState({},'',`${location.pathname}${url}`);onLocationChange(url);},[active,applied,stage]);
|
||||
useEffect(()=>{if(!active||!applied)return;const bytes=new TextEncoder().encode(JSON.stringify({query:queryForLocation(applied,initial.releaseId)}));const encoded=btoa(Array.from(bytes,b=>String.fromCharCode(b)).join('')).replace(/=/g,'').replace(/\+/g,'-').replace(/\//g,'_');const url=`?page=${stage==='black'?'blackProduct':'brightProduct'}&context=${encoded}`;window.history.replaceState({},'',`${location.pathname}${url}`);onLocationChange(url);},[active,applied,stage]);
|
||||
const trendQuery=useMemo(()=>applied?{...applied,month:undefined,quarter:undefined,...(trendGranularity==='year'?{year:undefined}:{}),trendGranularity}:null,[applied,trendGranularity]);
|
||||
const trendKey=JSON.stringify({query:trendQuery,revision});
|
||||
useEffect(()=>{if(!active||!current||!trendQuery)return;const controller=new AbortController();setTrendLoading(true);setTrendError('');void api.metrics(trendQuery,controller.signal).then(value=>{if(!controller.signal.aborted)setTrendResponse({key:trendKey,value});}).catch(error=>{if(!controller.signal.aborted&&!onUnauthorized(error))setTrendError(error instanceof Error?error.message:'趋势读取失败');}).finally(()=>{if(!controller.signal.aborted)setTrendLoading(false);});return()=>controller.abort();},[active,trendKey,!!current,onUnauthorized]);
|
||||
useEffect(()=>{if(!active||!trendQuery||supportError)return;const controller=new AbortController();setTrendLoading(true);setTrendError('');void api.trend(trendQuery,controller.signal).then(value=>{if(!controller.signal.aborted)setTrendResponse({key:trendKey,value,query:trendQuery});}).catch(error=>{if(!controller.signal.aborted&&!onUnauthorized(error))setTrendError(error instanceof Error?error.message:'趋势读取失败');}).finally(()=>{if(!controller.signal.aborted)setTrendLoading(false);});return()=>controller.abort();},[active,trendKey,trendRevision,onUnauthorized,supportError]);
|
||||
const visibleTrend=useMemo(()=>fullYearTrend(trendResponse?.key===trendKey?trendResponse.value.trend:[],applied?.year||year,trendGranularity),[trendResponse,trendKey,applied?.year,year,trendGranularity]);
|
||||
const selectTrendPeriod=(value:number|string)=>{if(!applied)return;const text=String(value);if(trendGranularity==='year'){const selectedYear=Number(text);if(Number.isFinite(selectedYear)){setYear(selectedYear);setPeriod('year');setApplied({...applied,year:selectedYear,month:undefined,quarter:undefined});}}else if(trendGranularity==='quarter'){const selectedQuarter=Number(text.replace(/^.*Q/,''));if(selectedQuarter>=1&&selectedQuarter<=4){setQuarter(selectedQuarter);setPeriod('quarter');setApplied({...applied,quarter:selectedQuarter,month:undefined});}}else{const selectedMonth=Number(text.slice(-2));if(selectedMonth>=1&&selectedMonth<=12){setMonth(selectedMonth);setPeriod('month');setApplied({...applied,month:selectedMonth,quarter:undefined});}}setRevision(v=>v+1);};
|
||||
const dirty=!!applied&&JSON.stringify(draft)!==JSON.stringify(applied);const submit=()=>{setApplied(draft);setRevision(v=>v+1);};
|
||||
const displayedTrend=useRetainedResult(trendResponse?.key===trendKey?visibleTrend:null)||visibleTrend;
|
||||
const selectedTrendPeriod=trendGranularity==='month'&&applied?.month
|
||||
? `${applied.year}-${String(applied.month).padStart(2,'0')}`
|
||||
: trendGranularity==='quarter'&&applied?.quarter ? `${applied.year}-Q${applied.quarter}` : undefined;
|
||||
const selectTrendPeriod=(value:number|string)=>{automaticPeriod.current=false;const next=nextTrendPeriod(value,{period,year,month,quarter});setYear(next.year);setMonth(next.month);setQuarter(next.quarter);setPeriod(next.period);};
|
||||
const dirty=!!applied&&JSON.stringify(draft)!==JSON.stringify(applied);
|
||||
const queryBusy=supportLoading||loading||(!error&&!supportError&&(dirty||!current));
|
||||
const queryFailed=!!(error||supportError);
|
||||
const submit=()=>{automaticPeriod.current=false;setAppliedSearch(search.trim());setDrilledProduct('');setRevision(v=>v+1);};
|
||||
const setTrendObject=(value?:string)=>{const selected=value||'';setDrilledProduct('');setSearch(selected);setAppliedSearch(selected);};
|
||||
const returnToProducts=()=>{setDrilledProduct('');setSearch(drillParentSearch.current);setAppliedSearch(drillParentSearch.current);setTrendMode('production');};
|
||||
const reset=()=>{automaticPeriod.current=false;const previous=defaultQueryMonth(options);setYear(previous.year);setMonth(previous.month);setQuarter(previousCompleteQuarter().quarter);setPeriod('month');setTrendGranularity('month');setDepartment([]);setGroup([]);setProduct([]);setProjectGroup([]);setSourceFilters([]);setSearch('');setAppliedSearch('');setDrilledProduct('');setApplied(stageProductQuery({year:previous.year,month:previous.month,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,[]));setRevision(v=>v+1);};
|
||||
const groups=(options?.groups||[]).filter(name=>!department.length||department.includes(options?.groupDepartments?.[name]||''));
|
||||
const paths=options?.organizationPaths||[];const products=department.length||group.length?[...new Set(paths.filter(path=>(!department.length||department.includes(path.department||''))&&(!group.length||group.includes(path.group||''))).map(path=>path.product).filter((v):v is string=>!!v))]:options?.products||[];
|
||||
const select=(name:string,value:string[],choices:string[],change:(v:string[])=>void)=><label className="query-field query-primary-field"><span>{name}</span><Select {...readableSelectPopup} mode="multiple" allowClear showSearch optionFilterProp="label" aria-label={name} placeholder="全部" maxTagCount="responsive" value={value} options={[...new Set([...choices,...value])].map(v=>({label:v==='__UNASSIGNED__'?'未分类':v,value:v}))} onChange={change}/></label>;
|
||||
const sortedRows=useMemo(()=>sortStageRowsByTotalWeight(current?.rows||[],stage),[current,stage]);
|
||||
const summary=current?.summary[stage];const stageRate=stage==='bright'&&rateBasis==='withoutHeadquartersScrap'?summary?.rateWithoutHeadquartersScrap:summary?.rate;
|
||||
const trendOptions=useMemo(()=>[...products.map(value=>({label:value,value})),...(drilledProduct==='__UNASSIGNED__'?[{label:'未分类',value:drilledProduct}]:[])],[products,drilledProduct]);
|
||||
const trendObject=drilledProduct||exactProductSearch;
|
||||
const drilledLabel=drilledProduct==='__UNASSIGNED__'?'未分类':drilledProduct;
|
||||
const select=(name:string,value:string[],choices:string[],change:(v:string[])=>void,extra=false)=><label className={`query-field ${extra?'query-extra-field':'query-primary-field'}`}><span>{name}</span><Select {...readableSelectPopup} mode="multiple" allowClear showSearch optionFilterProp="label" aria-label={name} placeholder="全部" maxTagCount="responsive" value={value} options={[...new Set([...choices,...value])].map(v=>({label:v==='__UNASSIGNED__'?'未分类':v,value:v}))} onChange={change}/></label>;
|
||||
const moreFilterCount=(projectGroup.length?1:0)+sourceFilters.length;
|
||||
const moreFilterSummary=[projectGroup.length?`项目组:${projectGroup.map(v=>v==='__UNASSIGNED__'?'未分类':v).join('、')}`:'',...sourceFilters.map(rule=>fields.find(field=>field.key===rule.field)?.label||rule.field)].filter(Boolean).join(';');
|
||||
const displayed = useRetainedResult(current && applied ? { data: current, query: applied } : null);
|
||||
const sortedRows=useMemo(()=>sortStageRowsByTotalWeight(displayed?.data.rows||[],stage),[displayed?.data,stage]);
|
||||
const trendRefreshing=!trendError&&(trendLoading||trendResponse?.key!==trendKey);
|
||||
const showTrendLoading=useDelayedIndicator(trendRefreshing);
|
||||
const tableReady=!!current&&(!drilledProduct||(trendResponse?.key===trendKey&&!trendLoading&&!trendError));
|
||||
const table=useRetainedResult(tableReady&&applied?{rows:drilledProduct?visibleTrend:sortedRows,query:applied,drilledProduct,period:drilledProduct?'year' as const:applied.month?'month' as const:applied.quarter?'quarter' as const:'year' as const}:null);
|
||||
const summary=displayed?.data.summary[stage];const stageRate=stage==='bright'&&rateBasis==='withoutHeadquartersScrap'?summary?.rateWithoutHeadquartersScrap:summary?.rate;
|
||||
const openDetail=(row:MetricRow|null,_stage:Stage,selectedMonth?:number)=>{if(!applied||!current?.release)return;setRecordVisible(true);setRecords({row,query:{...applied,releaseId:current.release.id,...(row&&selectedMonth==null?{product:row.product||'__UNASSIGNED__'}:{}),...(selectedMonth?{month:selectedMonth,quarter:undefined}: {})}});};
|
||||
const runExport=async()=>{setExporting(true);try{await exporter.current?.exportExcel();}catch(e){message.error(e instanceof Error?e.message:'导出失败');}finally{setExporting(false);}};
|
||||
const formulaKey=stage==='black'?'blackRate':rateBasis==='original'?'brightRate':'brightRateWithoutHeadquartersScrap';
|
||||
return <div className="query-page stage-product-page">
|
||||
{supportError&&<Alert showIcon type="error" message="查询条件读取失败" description={supportError} action={<Button onClick={()=>void loadSupport()}>重试</Button>}/>}
|
||||
<section className="query-toolbar panel" aria-label={`${label}汇总条件`}>
|
||||
<Segmented aria-label="统计周期" value={period} options={[{label:'年度',value:'year'},{label:'季度',value:'quarter'},{label:'月度',value:'month'}]} onChange={v=>setPeriod(v as PeriodKind)}/>
|
||||
<label className="query-field query-period-field"><span>年份</span><Select aria-label="年份" value={year} onChange={setYear} options={(options?.years?.length?options.years:[year]).map(v=>({label:`${v}年`,value:v}))}/></label>
|
||||
{period==='month'&&<label className="query-field query-period-field"><span>月份</span><Select aria-label="月份" value={month} onChange={setMonth} options={Array.from({length:12},(_,i)=>({label:`${i+1}月`,value:i+1}))}/></label>}
|
||||
{period==='quarter'&&<label className="query-field query-period-field"><span>季度</span><Select aria-label="季度" value={quarter} onChange={setQuarter} options={[1,2,3,4].map(v=>({label:`第${v}季度`,value:v}))}/></label>}
|
||||
<Segmented aria-label="统计周期" value={period} options={[{label:'年度',value:'year'},{label:'季度',value:'quarter'},{label:'月度',value:'month'}]} onChange={v=>{automaticPeriod.current=false;setPeriod(v as PeriodKind);}}/>
|
||||
<label className="query-field query-period-field query-period-year"><span>年份</span><Select aria-label="年份" value={year} onChange={v=>{automaticPeriod.current=false;setYear(v);}} options={(options?.years?.length?options.years:[year]).map(v=>({label:`${v}年`,value:v}))}/></label>
|
||||
{period==='month'&&<label className="query-field query-period-field query-period-month"><span>月份</span><Select aria-label="月份" value={month} onChange={v=>{automaticPeriod.current=false;setMonth(v);}} options={Array.from({length:12},(_,i)=>({label:`${String(i+1).padStart(2,'0')}月`,value:i+1}))}/></label>}
|
||||
{period==='quarter'&&<label className="query-field query-period-field query-period-quarter"><span>季度</span><Select aria-label="季度" value={quarter} onChange={v=>{automaticPeriod.current=false;setQuarter(v);}} options={[1,2,3,4].map(v=>({label:`第${v}季度`,value:v}))}/></label>}
|
||||
{select('产业部',department,options?.departments||[],values=>{setDepartment(values);setGroup([]);setProduct([]);})}
|
||||
{select('业务分组',group,groups,values=>{setGroup(values);setProduct([]);})}
|
||||
{select('产品',product,products,setProduct)}
|
||||
{options?.projectGroupStatus==='READY'&&select('项目组',projectGroup,options.projectGroups||[],setProjectGroup)}
|
||||
{catalog&&<StageSourceFilters part="picker" stage={stage} fields={fields} query={draft} value={sourceFilters} onChange={setSourceFilters} onUnauthorized={onUnauthorized}/>}
|
||||
<div className="query-toolbar-tail"><Button type="text" icon={<ReloadOutlined/>} loading={supportLoading} onClick={()=>void loadSupport()}>刷新</Button><Button type="primary" icon={<SearchOutlined/>} disabled={supportLoading||!!supportError||!catalog} loading={loading} onClick={submit}>查询</Button></div>
|
||||
{catalog&&<StageSourceFilters part="rows" stage={stage} fields={fields} query={draft} value={sourceFilters} onChange={setSourceFilters} onUnauthorized={onUnauthorized}/>}
|
||||
{dirty&&<div className="stage-query-pending">筛选条件已修改,点击“查询”更新统计结果</div>}
|
||||
<div className="query-more-toggle" title={moreFilterSummary||undefined}>
|
||||
<Button type="text" size="small" icon={moreFiltersOpen?<UpOutlined/>:<DownOutlined/>} aria-expanded={moreFiltersOpen} aria-controls={`stage-more-filters-${stage}`} onClick={()=>setMoreFiltersOpen(open=>!open)}>更多筛选{moreFilterCount?`(已选 ${moreFilterCount} 项)`:''}</Button>
|
||||
{moreFilterCount>0&&<Button type="link" size="small" onClick={()=>{setProjectGroup([]);setSourceFilters([]);}}>清除</Button>}
|
||||
</div>
|
||||
<div className="query-toolbar-tail"><span className={`query-status ${queryBusy?'busy':queryFailed?'failed':''}`}><i/>{queryBusy?'正在查询':queryFailed?'查询失败':'查询完成'}</span><Button type="default" onClick={reset}>重置</Button></div>
|
||||
{moreFiltersOpen&&<div className="query-extra-fields" id={`stage-more-filters-${stage}`}>
|
||||
{options?.projectGroupStatus==='READY'&&select('项目组',projectGroup,options.projectGroups||[],setProjectGroup,true)}
|
||||
{catalog&&<StageSourceFilters stage={stage} fields={fields} query={draft} value={sourceFilters} onChange={setSourceFilters} onUnauthorized={onUnauthorized}/>}
|
||||
</div>}
|
||||
</section>
|
||||
{error&&<Alert showIcon type="error" message="查询失败" description={error} action={<Button onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>}
|
||||
{error&&<Alert showIcon type="error" message={response?"更新失败,当前显示上次结果":"查询失败"} description={error} action={<Button onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>}
|
||||
<section className="metric-strip stage-metric-strip" aria-label="质量指标" aria-busy={loading} inert={!current}>
|
||||
{stage==='bright'&&<div className="rate-basis-control"><Segmented size="small" aria-label="合格率口径" value={rateBasis} options={[{label:'原口径',value:'original'},{label:'去本部报废',value:'withoutHeadquartersScrap'}]} onChange={v=>setRateBasis(v as typeof rateBasis)}/></div>}
|
||||
<MetricCard primary stage={stage} label={`${label}合格率`} value={rate(stageRate)} onClick={()=>setBasisOpen(true)}/>
|
||||
@@ -86,18 +125,42 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
<MetricCard label="报废重量" value={`${weight(queryScrapWeight(summary,stage,rateBasis))} kg`} onClick={()=>openDetail(null,stage)}/>
|
||||
<MetricCard label="总重量" value={`${weight(summary?.totalWeight)} kg`} onClick={()=>openDetail(null,stage)}/>
|
||||
</section>
|
||||
<div className="query-quality-summary"><span>{current?`来源覆盖 ${current.coverage.sourceMonths.filter(m=>(stage==='black'?m.blackRows:m.brightRows)>0).length} 个月 · 参与计算 ${current.coverage.includedRows.toLocaleString()} 行`:loading?'正在查询…':'暂无统计结果'}</span><Button type="link" disabled={!current} onClick={()=>setBasisOpen(true)}>计算口径</Button></div>
|
||||
<section className="panel section-panel table-panel"><div className="section-heading-row"><SectionHeading title={`${label}汇总`} subtitle="重量 / kg 合格率 / %"/><div className="table-tools"><Input aria-label="搜索产品名称" placeholder="输入产品名称关键词" allowClear value={search} onChange={e=>setSearch(e.target.value)} onPressEnter={submit}/><Button onClick={submit} disabled={!catalog||!!supportError}>搜索</Button><Segmented value={fullFields?'full':'key'} aria-label="字段显示" options={[{label:'关键指标',value:'key'},{label:'完整字段',value:'full'}]} onChange={v=>setFullFields(v==='full')}/><Segmented value={defectDisplay} aria-label="不良显示方式" options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={v=>setDefectDisplay(v as typeof defectDisplay)}/><Button icon={<DownloadOutlined/>} aria-label="Excel导出" loading={exporting} disabled={!current||loading} onClick={()=>void runExport()}>Excel导出</Button></div></div>
|
||||
<Spin spinning={loading}><MetricTable ref={exporter} exportFilename={`${label}产品汇总-${year}`} rows={sortedRows} view="product" period={period} month={month} quarter={quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={row=>{setProduct([row.product||'__UNASSIGNED__']);setSearch('');setApplied({...applied!,product:row.product||'__UNASSIGNED__',productSearch:undefined});setRevision(v=>v+1);}}/></Spin>
|
||||
</section>
|
||||
<div className="analysis-stack"><section className="panel section-panel trend-panel"><div className="section-heading-row trend-heading-row"><SectionHeading title={`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}变化趋势`} subtitle={`${year} 年 · 当前${label}筛选`}/><Segmented value={trendMode} aria-label="趋势视图" options={[{label:'合格率与产量',value:'production'},{label:'不良率',value:'defects'},{label:`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}数据`,value:'data'}]} onChange={v=>setTrendMode(v as typeof trendMode)}/></div><div className="trend-controls">{trendMode==='data'&&<Segmented value={defectDisplay} aria-label="趋势不良显示方式" options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={v=>setDefectDisplay(v as typeof defectDisplay)}/>}<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={trendGranularity} options={[{label:'按月',value:'month'},{label:'按季度',value:'quarter'},{label:'按年度',value:'year'}]} onChange={setTrendGranularity} aria-label="趋势粒度"/></label></div>{trendError&&<Alert type="warning" message="趋势读取失败" description={trendError}/>}<Spin spinning={trendLoading}><div className="trend-chart-shell" aria-busy={trendLoading}>{trendMode==='data'?<MetricTable exportFilename={`${label}月度趋势-${year}`} rows={visibleTrend} view="overall" layoutView="product" period="year" month={month} quarter={quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={()=>{}}/>:<TrendChart rows={visibleTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} onMonth={selectTrendPeriod}/>}</div></Spin><div className="chart-footnote"><span>指标由来源分量汇总,使用当前生效公式。</span><span>点击期间筛选</span></div></section>
|
||||
<section className="panel section-panel defects-panel">
|
||||
<div className="section-heading-row"><SectionHeading title="不良具体构成" subtitle={`${label} · 占比为分类报废内占比;废率为该类重量 ÷ 总重量`}/></div>
|
||||
<section className="defect-stage-column" aria-label={`${label}不良构成`}>
|
||||
<div className="analysis-stack">
|
||||
<QueryTrendPanel mode={trendMode} onMode={setTrendMode} granularity={trendGranularity} onGranularity={setTrendGranularity}
|
||||
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} fullFields={trendFullFields} onFullFields={setTrendFullFields}
|
||||
object={trendObject} onObject={setTrendObject} objects={trendOptions} scopeName="产品">
|
||||
{trendError&&<Alert type="warning" showIcon message={trendResponse?"趋势更新失败,当前显示上次结果":"趋势读取失败"} description={trendResponse?`${trendError};当前范围:${loadedQueryScope(trendResponse.query,decodeQueryValueList)}`:trendError} action={<Button onClick={()=>setTrendRevision(v=>v+1)}>重试</Button>}/>}
|
||||
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing||!!trendError}>
|
||||
{trendMode==='data'
|
||||
? <TrendTable rows={displayedTrend} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} fullFields={trendFullFields} onMonth={selectTrendPeriod}/>
|
||||
: <TrendChart rows={displayedTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod}/>}
|
||||
{showTrendLoading&&<span className="trend-refresh-indicator"><Spin size="small"/>{trendResponse?`正在更新 · 当前显示上次筛选的${loadedQueryScope(trendResponse.query,decodeQueryValueList)}`:'正在读取趋势'}</span>}
|
||||
</div>
|
||||
</QueryTrendPanel>
|
||||
<QueryTablePanel heading={<SectionHeading title={table?.drilledProduct?'产品月度质量数据':`${label}产品质量汇总`} subtitle={table?.drilledProduct?`${table.query.year} 年 · ${table.drilledProduct==='__UNASSIGNED__'?'未分类':table.drilledProduct} · 重量 / kg 合格率 / %`:'重量 / kg 合格率 / %'}/>}
|
||||
busy={queryBusy||!tableReady} search={drilledLabel||search} onSearchChange={setSearch} onSearch={submit} searchDisabled={!!drilledProduct} searchUnavailable={!catalog||!!supportError}
|
||||
fullFields={fullFields} onFullFields={setFullFields} defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay}
|
||||
returnControls={drilledProduct&&<Button className="query-return-button" icon={<ArrowLeftOutlined/>} onClick={returnToProducts}>返回上一级</Button>}
|
||||
exporting={exporting} exportDisabled={!current||loading||!tableReady||!table?.rows.length} onExport={()=>void runExport()}>
|
||||
<SmoothTableFrame busy={queryBusy||!tableReady} blocked={queryBusy||!tableReady}>
|
||||
<MetricTable ref={exporter} exportFilename={`${table?.drilledProduct||label}产品汇总-${table?.query.year||year}-${fullFields?'完整字段':'关键指标'}`}
|
||||
paginationScope={JSON.stringify({query:table?.query,drilledProduct:table?.drilledProduct})}
|
||||
rows={table?.rows||[]} view={table?.drilledProduct?'overall':'product'} layoutView="product" pageSizeOverride={table?.drilledProduct?12:undefined}
|
||||
period={table?.period||period} month={table?.query.month||month} quarter={table?.query.quarter||quarter}
|
||||
fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)}
|
||||
emptyText={queryBusy?'正在更新数据…':error?'查询失败,暂无可展示结果':'当前条件下暂无数据'}
|
||||
onDrilldown={row=>{if(drilledProduct)return;const selected=row.product||'__UNASSIGNED__';drillParentSearch.current=appliedSearch;setDrilledProduct(selected);setTrendGranularity('month');setTrendMode('production');}}/>
|
||||
</SmoothTableFrame>
|
||||
</QueryTablePanel>
|
||||
<section className="panel section-panel defects-panel" aria-busy={loading||!current}>
|
||||
<div className="section-heading-row"><SectionHeading title="不良具体构成"/></div>
|
||||
<div className="stage-defect-comparison">
|
||||
<section className="defect-stage-column" inert={!current||loading} aria-label={`${label}不良构成`}>
|
||||
<h3 className={`defect-stage-title ${stage}`}><i/>{label}</h3>
|
||||
{current?.defects[stage]?.length ? <DefectBreakdown items={current.defects[stage]} stage={stage} totalWeight={summary?.totalWeight} maximum={Math.max(0,...current.defects[stage].map(item=>item.weight||0))} onDetail={()=>openDetail(null,stage)}/> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={loading?'正在查询不良数据…':'当前条件下暂无不良分类数据'}/>}
|
||||
{displayed?.data.defects[stage]?.length ? <DefectBreakdown items={displayed.data.defects[stage]} stage={stage} totalWeight={summary?.totalWeight} maximum={Math.max(0,...displayed.data.defects[stage].map(item=>item.weight||0))} onDetail={()=>openDetail(null,stage)}/> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={loading?'正在查询不良数据…':'当前条件下暂无不良分类数据'}/>}
|
||||
</section>
|
||||
{current&&applied&&<DefectParetoPanel releaseId={current.release?.id} query={applied} onlyStage={stage} externalScrapWeight={stage==='black'?current.defects.black.find(item=>item.name==='外废')?.weight:undefined} onUnauthorized={onUnauthorized}/>}
|
||||
{displayed&&<DefectParetoPanel releaseId={displayed.data.release?.id} query={displayed.query} pending={!current||loading} refreshKey={revision} onlyStage={stage} externalScrapWeight={stage==='black'?displayed.data.defects.black.find(item=>item.name==='外废')?.weight:undefined} onUnauthorized={onUnauthorized}/>}
|
||||
</div>
|
||||
</section></div>
|
||||
<Modal open={basisOpen} title={`${label}计算口径`} onCancel={()=>setBasisOpen(false)} footer={<Button onClick={()=>setBasisOpen(false)}>关闭</Button>}><p>{readableMetricFormula((current?.context.metricFormulaDescriptions as Record<string,unknown>|undefined)?.[formulaKey])}</p></Modal>
|
||||
{records&&<RecordsDrawer key={JSON.stringify(records)} open={recordVisible} row={records.row} query={records.query} stage={stage} lockedStage onStage={()=>{}} onClose={()=>setRecordVisible(false)} onUnauthorized={onUnauthorized}/>}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { usePageCache } from './pageCache';
|
||||
import { useDelayedIndicator } from './useDelayedBusy';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, Button, Select, Spin } from 'antd';
|
||||
import { CloseOutlined } from '@ant-design/icons';
|
||||
@@ -7,8 +9,11 @@ import { readableSelectPopup } from './readableSelectPopup';
|
||||
|
||||
function SourceValues({field,stage,query,value,onChange,onUnauthorized}:{field:SourceColumnField;stage:Stage;query:QueryParams;value:string[];onChange:(value:string[])=>void;onUnauthorized:(error:unknown)=>boolean}) {
|
||||
const [search,setSearch]=useState('');const [choices,setChoices]=useState<string[]>([]);const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [more,setMore]=useState(false);const [revision,setRevision]=useState(0);
|
||||
const {active}=usePageCache();
|
||||
const showBusy=useDelayedIndicator(busy);
|
||||
const contextKey=JSON.stringify(query);const current=useRef(0);
|
||||
useEffect(()=>{
|
||||
if(!active)return;
|
||||
const generation=++current.current,controller=new AbortController();setBusy(true);setError('');setChoices([]);
|
||||
const timer=window.setTimeout(()=>{
|
||||
const {year,month,quarter,department,group,product,projectGroup,includeUnassigned,columnFilters,releaseId}=query;
|
||||
@@ -18,8 +23,8 @@ function SourceValues({field,stage,query,value,onChange,onUnauthorized}:{field:S
|
||||
.finally(()=>{if(current.current===generation)setBusy(false);});
|
||||
},search?300:0);
|
||||
return()=>{window.clearTimeout(timer);controller.abort();current.current++;};
|
||||
},[field.key,stage,contextKey,search,revision,onUnauthorized]);
|
||||
return <Select {...readableSelectPopup} mode="multiple" allowClear showSearch aria-label={`${field.label}筛选值`} placeholder="选择筛选值" value={value} searchValue={search} filterOption={false} onSearch={setSearch} loading={busy} maxTagCount="responsive" onChange={values=>{onChange(values);setSearch('');}} options={[...new Set([...choices,...value])].map(v=>({label:v,value:v}))} notFoundContent={busy?<Spin size="small"/>:error?<Button size="small" onClick={()=>setRevision(v=>v+1)}>读取失败,重试</Button>:'暂无匹配值'} popupRender={menu=><>{menu}{more&&<div className="query-options-hint">输入关键词搜索更多值</div>}{error&&<div role="alert" className="query-options-hint">{error}</div>}</>}/>;
|
||||
},[active,field.key,stage,contextKey,search,revision,onUnauthorized]);
|
||||
return <Select {...readableSelectPopup} mode="multiple" allowClear showSearch aria-label={`${field.label}筛选值`} placeholder="选择筛选值" value={value} searchValue={search} filterOption={false} onSearch={setSearch} loading={showBusy} maxTagCount="responsive" onChange={values=>{onChange(values);setSearch('');}} options={[...new Set([...choices,...value])].map(v=>({label:v,value:v}))} notFoundContent={showBusy?<Spin size="small"/>:error?<Button size="small" onClick={()=>setRevision(v=>v+1)}>读取失败,重试</Button>:'暂无匹配值'} popupRender={menu=><>{menu}{more&&<div className="query-options-hint">输入关键词搜索更多值</div>}{error&&<div role="alert" className="query-options-hint">{error}</div>}</>}/>;
|
||||
}
|
||||
export function StageSourceFilters({stage,fields,query,value,onChange,onUnauthorized,part='both'}:{part?:'both'|'picker'|'rows';stage:Stage;fields:SourceColumnField[];query:QueryParams;value:SourceColumnFilter[];onChange:(value:SourceColumnFilter[])=>void;onUnauthorized:(error:unknown)=>boolean}) {
|
||||
const selected=value.map(rule=>rule.field);const patch=(key:string,change:Partial<SourceColumnFilter>)=>onChange(value.map(rule=>rule.field===key?{...rule,...change}:rule));
|
||||
|
||||
@@ -10,6 +10,8 @@ import type { AuthUser } from './types';
|
||||
import { BackupOperationsPanel, OperationsMonitorPanel } from './GovernanceCompletion';
|
||||
import { configurationDateTime } from './configurationName';
|
||||
import { backupSummary, isActive, isFailed, monitorLabel, orderedTasks, taskFailure, taskPercent, type MonitorRow } from './taskMonitorModel';
|
||||
import { useDelayedBusy } from './useDelayedBusy';
|
||||
import { useVisiblePolling } from './useVisiblePolling';
|
||||
|
||||
export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthorized:(error:unknown)=>boolean}) {
|
||||
const {message}=App.useApp();
|
||||
@@ -18,29 +20,35 @@ export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthor
|
||||
const [items,setItems]=useState<MonitorRow[]>([]);
|
||||
const [backup,setBackup]=useState<MonitorRow>({});
|
||||
const [taskError,setTaskError]=useState(''); const [backupError,setBackupError]=useState('');
|
||||
const [loading,setLoading]=useState(true);
|
||||
const loaded = useRef(false);
|
||||
const [tasksLoaded,setTasksLoaded]=useState(false); const [backupLoaded,setBackupLoaded]=useState(false);
|
||||
const [section,setSection] = useState('tasks');
|
||||
const taskBusy = useDelayedBusy(); const backupBusy = useDelayedBusy();
|
||||
const loading = sectionLoading();
|
||||
const [filter,setFilter]=useState('all'); const [selected,setSelected]=useState<MonitorRow|null>(null);
|
||||
const actionInFlight = useRef(false);
|
||||
const canManage=user.roles.some(role=>['SYSTEM_ADMIN','SYSTEM_OPERATOR'].includes(role));
|
||||
const load=useCallback(async()=>{
|
||||
setLoading(true);
|
||||
await Promise.all([
|
||||
api.taskOverview().then(value=>{setItems(value.items);setTaskError('');}).catch(error=>{if(!onUnauthorized(error))setTaskError(error instanceof Error?error.message:'任务读取失败');}),
|
||||
api.latestBackup().then(value=>{setBackup(value);setBackupError('');}).catch(error=>{if(!onUnauthorized(error))setBackupError(error instanceof Error?error.message:'备份状态读取失败');}),
|
||||
]);setLoading(false);
|
||||
},[onUnauthorized]);
|
||||
useEffect(()=>{if(!loaded.current){loaded.current=true;void load();}},[load]);
|
||||
function sectionLoading() { return section === 'tasks' ? taskBusy.busy : backupBusy.busy; }
|
||||
const loadTasks=useCallback(()=>taskBusy.run(async()=>{
|
||||
try { const value=await api.taskOverview();setItems(value.items);setTaskError('');setTasksLoaded(true); }
|
||||
catch(error){ if(!onUnauthorized(error))setTaskError(error instanceof Error?error.message:'任务读取失败'); }
|
||||
}),[onUnauthorized,taskBusy.run]);
|
||||
const loadBackup=useCallback(()=>backupBusy.run(async()=>{
|
||||
try { const value=await api.latestBackup();setBackup(value);setBackupError('');setBackupLoaded(true); }
|
||||
catch(error){ if(!onUnauthorized(error))setBackupError(error instanceof Error?error.message:'备份状态读取失败'); }
|
||||
}),[onUnauthorized,backupBusy.run]);
|
||||
const load=useCallback(()=>section==='tasks'?loadTasks():loadBackup(),[section,loadTasks,loadBackup]);
|
||||
useEffect(()=>{if(!active)return;if(section==='tasks'&&!tasksLoaded)void loadTasks();if(section==='latestBackup'&&!backupLoaded)void loadBackup();},[active,section,tasksLoaded,backupLoaded,loadTasks,loadBackup]);
|
||||
useMaintenanceRefresh(load);
|
||||
useEffect(()=>{if(!active || !['tasks','latestBackup'].includes(section))return;const timer=window.setInterval(()=>{if(document.visibilityState==='visible')void load();},15000);return()=>window.clearInterval(timer);},[load,active,section]);
|
||||
useVisiblePolling(load,15000,active&&['tasks','latestBackup'].includes(section));
|
||||
const runAction=async(row:MonitorRow,action:'retry'|'cancel')=>{
|
||||
if(actionInFlight.current)return; actionInFlight.current=true;
|
||||
setBusy(true);
|
||||
try {
|
||||
if(action==='retry') {const releases=await api.releases();await api.retryTask(String(row.id),{idempotencyKey:crypto.randomUUID(),expectedCurrentReleaseId:releases.currentReleaseId??null});}
|
||||
else await api.cancelTask(String(row.id),{expectedStatus:String(row.status)});
|
||||
message.success(action==='retry'?'已提交重试,请查看最新任务状态':'已取消排队任务');setSelected(null);await load();
|
||||
} catch(error){if(!onUnauthorized(error))message.error(error instanceof Error?error.message:'任务操作失败');}
|
||||
finally{setBusy(false);}
|
||||
finally{actionInFlight.current=false;setBusy(false);}
|
||||
};
|
||||
const latest=(backup.latest || {}) as MonitorRow;
|
||||
const columns:ColumnsType<MonitorRow>=[
|
||||
@@ -54,13 +62,14 @@ export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthor
|
||||
<ManagementSections onSelect={setSection} items={[
|
||||
{ key:'tasks', label:'任务进度', children: <> <section className="panel section-panel">
|
||||
<div className="completion-panel-heading"><strong>任务进度</strong><div className="completion-actions"><Select aria-label="筛选任务" value={filter} onChange={setFilter} options={[{value:'all',label:'全部任务'},{value:'active',label:'进行中'},{value:'failed',label:'失败 / 未完成'},{value:'completed',label:'已完成'}]}/><Button icon={<ReloadOutlined/>} loading={loading} onClick={()=>void load()}>刷新</Button></div></div>
|
||||
{taskError&&<Alert showIcon type="error" message="任务暂不可用" description={taskError}/>}
|
||||
{loading&&!items.length?<Spin/>:!taskError&&<Table size="small" bordered columns={columns} dataSource={orderedTasks(items,filter)} rowKey={row=>`${row.sourceKind}-${row.id}`} pagination={{pageSize:15,showSizeChanger:false}} scroll={{x:1000}} locale={{emptyText:<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无符合条件的任务"/>}}/>}
|
||||
{taskError&&<Alert showIcon type="error" message="任务暂不可用" description={tasksLoaded?`${taskError};以下为上次成功读取的结果。`:taskError} action={!tasksLoaded?<Button size="small" onClick={()=>void loadTasks()}>重试</Button>:undefined}/>}
|
||||
{loading&&!tasksLoaded?<Spin/>:tasksLoaded&&<Table size="small" bordered columns={columns} dataSource={orderedTasks(items,filter)} rowKey={row=>`${row.sourceKind}-${row.id}`} pagination={{pageSize:15,showSizeChanger:false}} scroll={{x:1000}} locale={{emptyText:<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无符合条件的任务"/>}}/>}
|
||||
<p className="completion-note">每类最多显示 50 条记录,进行中及失败任务优先。智能分析仅显示本人任务。</p>
|
||||
</section>
|
||||
</> },
|
||||
{ key:'latestBackup', label:'最近备份', children: <> <section className="panel section-panel"><div className="completion-panel-heading"><strong>最近备份状态</strong></div>
|
||||
{backupError?<Alert showIcon type="error" message="备份状态暂不可用" description={backupError}/>:loading&&!latest.createdAt?<Spin/>:<div className="governance-monitor-grid"><div><small>最近备份</small><strong>{backupSummary(latest)}</strong></div><div><small>备份时间</small><strong>{configurationDateTime(latest.createdAt)||'—'}</strong></div><div><small>恢复验证时间</small><strong>{configurationDateTime(latest.restoreVerifiedAt)||'—'}</strong></div><div><small>自动备份</small><strong>{backup.planActive===true?'已启用':'未启用'}</strong></div></div>}
|
||||
{backupError&&<Alert showIcon type="error" message="备份状态暂不可用" description={backupLoaded?`${backupError};以下为上次成功读取的结果。`:backupError} action={!backupLoaded?<Button size="small" onClick={()=>void loadBackup()}>重试</Button>:undefined}/>}
|
||||
{loading&&!backupLoaded?<Spin/>:backupLoaded&&<div className="governance-monitor-grid"><div><small>最近备份</small><strong>{backupSummary(latest)}</strong></div><div><small>备份时间</small><strong>{configurationDateTime(latest.createdAt)||'—'}</strong></div><div><small>恢复验证时间</small><strong>{configurationDateTime(latest.restoreVerifiedAt)||'—'}</strong></div><div><small>自动备份</small><strong>{backup.planActive===true?'已启用':'未启用'}</strong></div></div>}
|
||||
</section>
|
||||
</> },
|
||||
...(canManage ? [{ key:'monitor', label:'运行监控与告警', children:<OperationsMonitorPanel user={user} onUnauthorized={onUnauthorized}/> },{ key:'backups', label:'备份管理', children:<BackupOperationsPanel user={user} onUnauthorized={onUnauthorized}/> }] : []),
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
.management-page.analysis-simple-page{gap:12px}
|
||||
.analysis-simple-page .analysis-region-loading{display:flex;align-items:center;justify-content:center;gap:10px;min-height:120px;color:var(--muted-ink,#738198)}
|
||||
.analysis-simple-page .analysis-conversation>.analysis-region-loading{flex:1}
|
||||
.analysis-simple-page .analysis-workspace{height:calc(var(--dynamic-viewport-height) - 105px);min-height:540px;grid-template-columns:205px minmax(0,1fr)}
|
||||
.page-heading.page-actions-only{min-height:0;margin:0;justify-content:flex-end}
|
||||
.analysis-composer-buttons{display:flex;align-items:center;gap:8px}
|
||||
@@ -141,15 +143,15 @@
|
||||
.analysis-process-history{margin:0;min-width:0;color:var(--muted-ink,#63758b)}
|
||||
.analysis-process-history>summary{display:flex;align-items:center;gap:8px;width:fit-content;min-height:24px;cursor:pointer;list-style:none;font-size:var(--font-control)}
|
||||
.analysis-process-history>summary::-webkit-details-marker{display:none}
|
||||
.analysis-process-history>summary .anticon{font-size:var(--font-note);transition:transform .16s ease}
|
||||
.analysis-process-history[open]>summary .anticon{transform:rotate(90deg)}
|
||||
.analysis-process-history>summary>.anticon{font-size:var(--font-note);transition:transform .16s ease}
|
||||
.analysis-process-history[open]>summary>.anticon{transform:rotate(90deg)}
|
||||
.analysis-process-history>summary:focus-visible{outline:2px solid var(--primary-color,#607ae1);outline-offset:3px}
|
||||
.analysis-process-history-body{padding:8px 0;max-height:360px;overflow:auto;overscroll-behavior:contain}
|
||||
.analysis-queued-followup{display:flex;align-items:center;gap:8px;color:var(--muted-ink,#63758b);font-size:var(--font-control);min-width:0}
|
||||
.analysis-queued-followup>span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.analysis-queued-followup .ant-btn{flex:none;font-size:var(--font-control)}
|
||||
@media(max-width:700px){.analysis-simple-page .ai-actions{align-items:flex-start;gap:8px;flex-wrap:wrap}.analysis-composer-buttons{margin-left:auto;gap:5px}}
|
||||
@media(prefers-reduced-motion:reduce){.analysis-process-history>summary .anticon{transition:none}}
|
||||
@media(prefers-reduced-motion:reduce){.analysis-process-history>summary>.anticon{transition:none}}
|
||||
|
||||
@keyframes analysis-event-appear{from{opacity:.4;transform:translateY(2px)}to{opacity:1;transform:none}}
|
||||
.analysis-agent-stream>*{animation:analysis-event-appear .14s ease-out}
|
||||
@@ -171,3 +173,7 @@
|
||||
.analysis-clarification-actions{display:flex;justify-content:flex-end;margin-top:10px}
|
||||
.analysis-clarification fieldset:disabled .analysis-clarification-option{cursor:default;opacity:.65}
|
||||
.analysis-clarification-option:focus-within{outline:2px solid var(--primary-color,#607ae1);outline-offset:2px}
|
||||
|
||||
.analysis-runtime-clock{display:inline-flex;align-items:center;gap:5px}
|
||||
.analysis-turn-metadata .analysis-runtime-spinner{font-size:12px}
|
||||
@media(prefers-reduced-motion:reduce){.analysis-runtime-spinner,.analysis-runtime-spinner svg{animation:none!important}}
|
||||
|
||||
@@ -16,7 +16,11 @@ export function checkedConclusionComparison(sentence: string): ConclusionCompari
|
||||
const value = sentence.replace(/\*\*/g, '').trim();
|
||||
const match = value.match(/^([^。;\n]{1,50}?)(综合合格率|黑片合格率|亮片合格率|合格率)(?:为|是|[::])?\s*(\d+(?:\.\d+)?%)\s*[,,]\s*(?:较|相比|对比|比)\s*([^,,。;\n]{1,30}?)的?\s*(\d+(?:\.\d+)?%)\s*(下降|上升|提高|降低)\s*(\d+(?:\.\d+)?)(个百分点|pp)[。.]?$/);
|
||||
if (!match || [match[3], match[5]].some(rate => Number.parseFloat(rate) > 100)) return null;
|
||||
return { metric: match[2], currentLabel: match[1], current: match[3], previousLabel: match[4].replace(/的$/, ''), previous: match[5], direction: match[6], change: match[7], unit: match[8], original: value };
|
||||
const currentRate = Number.parseFloat(match[3]), previousRate = Number.parseFloat(match[5]);
|
||||
const isDecrease = /下降|降低/.test(match[6]);
|
||||
if (currentRate !== previousRate && (currentRate < previousRate) !== isDecrease) return null;
|
||||
const change = `${isDecrease ? '-' : '+'}${match[7]}`;
|
||||
return { metric: match[2], currentLabel: match[1], current: match[3], previousLabel: match[4].replace(/的$/, ''), previous: match[5], direction: match[6], change, unit: match[8], original: value };
|
||||
}
|
||||
|
||||
function topicMatches(title: string, visual: AnalysisVisual): boolean {
|
||||
|
||||
@@ -102,6 +102,20 @@ export function partialAnalysisNotice(reason: unknown, result: Record<string, un
|
||||
return '本轮分析未完整结束,已保存现有结果。可以重试或继续追问。';
|
||||
}
|
||||
|
||||
/** An ended turn without a visible answer still needs an explanation beside retry. */
|
||||
export function emptyAnalysisNotice(turn: Record<string, unknown>, displayedAnswer: string): string {
|
||||
const result = turn.result && typeof turn.result === 'object' && !Array.isArray(turn.result)
|
||||
? turn.result as Record<string, unknown> : turn;
|
||||
const status = String(turn.status || result.status || '').toUpperCase();
|
||||
if (displayedAnswer.trim() || !['PARTIAL', 'FAILED', 'CANCELLED', 'COMPLETED'].includes(status)) return '';
|
||||
if ([result.memberList, turn.memberList, result.recordList, turn.recordList].some(value => value !== undefined && value !== null)
|
||||
|| [result.reportMarkdown, turn.reportMarkdown, result.reportHtml, turn.reportHtml].some(value => typeof value === 'string' && value.trim())) return '';
|
||||
if (status === 'CANCELLED') return '分析已停止,尚未生成回答。';
|
||||
if (status === 'COMPLETED') return '此记录没有可显示的回答,请新建会话重试。';
|
||||
const quality = result.answerQuality && typeof result.answerQuality === 'object' ? result.answerQuality as Record<string, unknown> : {};
|
||||
return quality.dataComplete === true ? '数据查询已完成,但未生成分析正文。请重新分析。' : '本轮未生成可显示的回答,请重新分析。';
|
||||
}
|
||||
|
||||
/** Old answers keep their original wording; surface their explicitly recorded scope limitation. */
|
||||
export function hasUnreconciledEvidence(turn: Record<string, unknown>): boolean {
|
||||
const record = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
@@ -136,3 +150,16 @@ export function partialAnswerIsOnlyProgress(turn: Record<string, unknown>): bool
|
||||
if (lastAssistant < 0 || String(record(entries[lastAssistant]).text || '').trim() !== answer) return false;
|
||||
return entries.slice(lastAssistant + 1).some(item => ['tool_start', 'tool_result'].includes(String(record(item).kind)));
|
||||
}
|
||||
|
||||
/** Tool event names describe a step, never the lifecycle of the whole turn. */
|
||||
export function analysisStreamStatus(previous: unknown, event: string, reported: unknown): string {
|
||||
const prior = String(previous || '').toUpperCase();
|
||||
const terminal = new Set(['COMPLETED', 'PARTIAL', 'FAILED', 'CANCELLED', 'NEEDS_CLARIFICATION']);
|
||||
if (terminal.has(prior)) return prior;
|
||||
const name = event.toUpperCase().replaceAll('.', '_').replaceAll('-', '_');
|
||||
const status = String(reported || '').toUpperCase();
|
||||
if (/^(?:TURN_)?(COMPLETED|PARTIAL|FAILED|CANCELLED|NEEDS_CLARIFICATION)$/.test(name)) return name.replace(/^TURN_/, '');
|
||||
if (!name.startsWith('TOOL_') && (analysisIsRunning(status) || terminal.has(status))) return status;
|
||||
if (name.startsWith('TOOL_') || name === 'ANSWER') return 'RUNNING';
|
||||
return analysisIsRunning(prior) ? prior : 'RUNNING';
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { analysisTextEvidenceRefs } from './analysisEvidenceRefs.ts';
|
||||
import type { AnalysisVisual } from './analysisVisualsModel.ts';
|
||||
type Row = Record<string, unknown>;
|
||||
const object = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||
const text = (value: unknown) => typeof value === 'string' ? value : '';
|
||||
export interface OriginalAnalysisBody { answer: string; source: 'saved' | 'timeline' | 'unavailable' }
|
||||
|
||||
/** Older native turns saved a replacement report; their final assistant remains in the authorized timeline. */
|
||||
export function originalAnalysisBody(turn?: Row): OriginalAnalysisBody | null {
|
||||
if (!turn) return null;
|
||||
const result = turn.result && typeof turn.result === 'object' ? object(turn.result) : turn;
|
||||
const plan = object(turn.plan || result.plan);
|
||||
if (![turn.executionMode, result.executionMode, plan.executionMode].includes('native_agent')) return null;
|
||||
const saved = text(result.answer);
|
||||
// Explicitly empty/redacted answers must not be replenished from an older transcript.
|
||||
if (!saved.trim()) return { answer: '', source: 'unavailable' };
|
||||
const lead = text(object(result.readingSummary).lead);
|
||||
const replaced = /已取得本轮统计结果,答案整理尚未完整完成|已取得本轮统计结果,部分解释尚未完成|现有证据不足以支持本轮完整分析,已保留可核验统计结果/.test(lead || saved.slice(0, 160));
|
||||
if (!replaced) return { answer: saved, source: 'saved' };
|
||||
const raw = turn.timeline || result.timeline || plan.timeline;
|
||||
const timeline = Array.isArray(raw) ? raw.map(object) : [];
|
||||
let lastTool = -1;
|
||||
timeline.forEach((entry, index) => { if (/^tool(?:_|$)/.test(text(entry.kind))) lastTool = index; });
|
||||
const parts = timeline.slice(lastTool + 1).filter(entry => entry.kind === 'assistant' && text(entry.text).trim()).map(entry => text(entry.text));
|
||||
// Historical public timeline entries were capped at 8000 characters without a truncation flag.
|
||||
if (parts.some(part => part.length >= 8000)) return { answer: '', source: 'unavailable' };
|
||||
return parts.length ? { answer: parts.join('\n\n'), source: 'timeline' } : { answer: '', source: 'unavailable' };
|
||||
}
|
||||
|
||||
export interface OriginalAnalysisSection { id: string; markdown: string; visuals: AnalysisVisual[] }
|
||||
/** Keep every Markdown line in order; images are additions after the associated chapter. */
|
||||
export function originalAnalysisSections(answer: string, visuals: AnalysisVisual[]): OriginalAnalysisSection[] {
|
||||
const sections: Array<OriginalAnalysisSection & { title: string; lines: string[] }> = [];
|
||||
let current = { id: 'original-1', markdown: '', visuals: [] as AnalysisVisual[], title: '', lines: [] as string[] };
|
||||
sections.push(current);
|
||||
let fenced = false;
|
||||
for (const line of answer.split('\n')) {
|
||||
if (/^\s*```/.test(line)) fenced = !fenced;
|
||||
const heading = !fenced ? line.match(/^#{1,6}\s+(.+?)\s*#*\s*$/) : null;
|
||||
if (heading && current.lines.length) {
|
||||
current = { id: `original-${sections.length + 1}`, markdown: '', visuals: [], title: heading[1], lines: [] };
|
||||
sections.push(current);
|
||||
} else if (heading) current.title = heading[1];
|
||||
current.lines.push(line);
|
||||
}
|
||||
sections.forEach(section => { section.markdown = section.lines.join('\n'); });
|
||||
const relevant = (title: string, visual: AnalysisVisual): number => {
|
||||
const stage = visual.stage || (visual.metric.startsWith('black_') ? 'black' : visual.metric.startsWith('bright_') ? 'bright' : undefined);
|
||||
if (stage === 'black' && /亮片/.test(title) && !/黑片/.test(title)
|
||||
|| stage === 'bright' && /黑片/.test(title) && !/亮片/.test(title)) return 0;
|
||||
|
||||
if (visual.dimension === 'product') return /规格|产品/.test(title) ? 4 : 0;
|
||||
if (visual.dimension === 'department' || visual.dimension === 'group') return /组织|产业部|分组|区域/.test(title) ? 4 : 0;
|
||||
if (visual.dimension === 'defect' || visual.metric.startsWith('source_defect')) return /缺陷|缺角|隐裂|源字段/.test(title) ? 4 : 0;
|
||||
if (/category/.test(visual.sectionKey || '')) return /报废大类|报废类别|正式报废/.test(title) ? 4 : 0;
|
||||
if (visual.type === 'line' || visual.type === 'area') return /趋势|逐月|月度/.test(title) ? 4 : 0;
|
||||
return /总体|阶段/.test(title) || stage === 'black' && /黑片/.test(title) || stage === 'bright' && /亮片/.test(title) ? 4 : /结论/.test(title) ? 2 : 0;
|
||||
};
|
||||
for (const visual of visuals) {
|
||||
const candidates = sections.map(section => {
|
||||
const refs = analysisTextEvidenceRefs(section.markdown);
|
||||
const topic = relevant(section.title, visual);
|
||||
return { section, score: topic ? topic + (visual.evidenceRefs.some(ref => refs.includes(ref)) ? 10 : 0) : 0 };
|
||||
}).filter(item => item.score > 0).sort((a, b) => b.score - a.score);
|
||||
if (candidates.length) candidates[0].section.visuals.push(visual);
|
||||
else sections.push({ id: `original-chart-${sections.length + 1}`, title: '', lines: [], markdown: '', visuals: [visual] });
|
||||
}
|
||||
return sections.filter(section => section.markdown.trim() || section.visuals.length).map(({ id, markdown, visuals }) => ({ id, markdown, visuals }));
|
||||
}
|
||||
@@ -7,6 +7,12 @@ export function analysisSnapshotResult(turn: Row): Row {
|
||||
return turn.result && typeof turn.result === 'object' && !Array.isArray(turn.result) ? object(turn.result) : turn;
|
||||
}
|
||||
|
||||
function originalTranscript(turn: Row): unknown {
|
||||
const result = analysisSnapshotResult(turn), plan = object(turn.plan || result.plan);
|
||||
if (![turn.executionMode, result.executionMode, plan.executionMode].includes('native_agent')) return null;
|
||||
return turn.timeline || result.timeline || plan.timeline || [];
|
||||
}
|
||||
|
||||
function canonical(value: unknown): string {
|
||||
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
|
||||
if (value && typeof value === 'object') {
|
||||
@@ -19,16 +25,17 @@ export function reportSnapshotIdentity(turn: Row): string {
|
||||
const result = analysisSnapshotResult(turn);
|
||||
const value = (key: string, fallback: unknown) => ['readingSummary', 'queryEvidenceRefs'].includes(key)
|
||||
? result[key] ?? fallback : result[key] ?? turn[key] ?? fallback;
|
||||
return canonical({ answer: value('answer', ''), visuals: value('visuals', []),
|
||||
return canonical({ originalTranscript: originalTranscript(turn), answer: value('answer', ''), visuals: value('visuals', []),
|
||||
results: value('results', []), reportMarkdown: value('reportMarkdown', ''),
|
||||
reportHtml: value('reportHtml', ''), memberList: value('memberList', null),
|
||||
recordList: value('recordList', null), readingSummary: value('readingSummary', null), queryEvidenceRefs: value('queryEvidenceRefs', []), question: turn.question || '' });
|
||||
}
|
||||
|
||||
export function reportSnapshotDifferences(left: Row, right: Row): string[] {
|
||||
const fields = ['answer', 'visuals', 'results', 'reportMarkdown', 'reportHtml', 'memberList', 'recordList', 'readingSummary', 'queryEvidenceRefs', 'question'];
|
||||
const fields = ['answer', 'visuals', 'results', 'reportMarkdown', 'reportHtml', 'memberList', 'recordList', 'readingSummary', 'queryEvidenceRefs', 'question', 'originalTranscript'];
|
||||
return fields.filter(key => {
|
||||
const value = (turn: Row) => {
|
||||
if (key === 'originalTranscript') return originalTranscript(turn);
|
||||
const result = analysisSnapshotResult(turn);
|
||||
return key === 'question' ? turn.question || '' : ['readingSummary', 'queryEvidenceRefs'].includes(key)
|
||||
? result[key] ?? (key === 'readingSummary' ? null : []) : result[key] ?? turn[key] ?? (key === 'memberList' || key === 'recordList' || key === 'readingSummary' ? null : key === 'visuals' || key === 'results' || key === 'queryEvidenceRefs' ? [] : '');
|
||||
@@ -47,7 +54,7 @@ export async function authorizeAnalysisSnapshot(turn: Row): Promise<void> {
|
||||
}
|
||||
const differences = reportSnapshotDifferences(current, turn);
|
||||
if (differences.length) {
|
||||
const labels: Record<string, string> = { answer: '回答', visuals: '图表', results: '查询结果', reportMarkdown: '报告正文', reportHtml: '报告 HTML', memberList: '成员清单', recordList: '原始记录', readingSummary: '核心结论', queryEvidenceRefs: '数据依据', question: '问题' };
|
||||
const labels: Record<string, string> = { answer: '回答', visuals: '图表', results: '查询结果', reportMarkdown: '报告正文', reportHtml: '报告 HTML', memberList: '成员清单', recordList: '原始记录', readingSummary: '核心结论', queryEvidenceRefs: '数据依据', question: '问题', originalTranscript: '原始正文' };
|
||||
throw new Error(`分析结果或访问权限已变化(${differences.map(key => labels[key] || key).join('、')}),请重新打开这条分析后再导出。`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,9 @@ export function canRecoverAnalysisVisuals(turn: Row): boolean {
|
||||
const planned=Array.isArray(task.queryPlan)&&task.queryPlan.some(raw=>{
|
||||
const node=object(raw);return ['ranking','trend','defects'].includes(String(node.purpose))&&node.visualPreference!=='none';
|
||||
});
|
||||
const requested=task.trendRequired===true||task.visualPreference==='required'||Boolean(task.visualType)||planned;
|
||||
const gaps=object(result.executionCoverage).visualGaps;
|
||||
const nativeGap=task.executionMode==='native_agent'&&(['failed','unavailable'].includes(state)||Array.isArray(gaps)&&gaps.length>0);
|
||||
const requested=task.trendRequired===true||task.visualPreference==='required'||Boolean(task.visualType)||planned||nativeGap;
|
||||
return plan.protocolVersion===1&&['metrics','analysis'].includes(String(task.kind))
|
||||
&&['COMPLETED','PARTIAL'].includes(status)&&task.visualPreference!=='none'&&requested
|
||||
&&object(result.visualRecovery).complete!==true&&(state!=='ready'||status==='PARTIAL');
|
||||
|
||||
@@ -121,6 +121,15 @@ function hasOnlyKeys(value: Record<string, unknown>, allowed: Set<string>): bool
|
||||
return Object.keys(value).every(key => allowed.has(key));
|
||||
}
|
||||
|
||||
function canonicalLegacyRateDropNote(note: string | undefined): string {
|
||||
const details = (note || '')
|
||||
.replace(/^(?:条形末端显示具体变化:)?[^;。]*?(?:正值|负值)[^;。]*[;。]\s*/, '')
|
||||
.replace(/^[;;,,。.\s]+/, '')
|
||||
.trim();
|
||||
const basis = '正值表示本期合格率上升,负值表示下降;变化值为本期减比较期。';
|
||||
return details ? `${basis} ${details}` : basis;
|
||||
}
|
||||
|
||||
/** 解析前仅复制普通 JSON 数据,阻止 getter、toJSON、原型和函数进入渲染链路。 */
|
||||
function copyJsonData(value: unknown, seen = new Set<object>(), budget = { nodes: 0 }, depth = 0): unknown {
|
||||
if (depth > 32 || ++budget.nodes > 100_000) throw new Error('unsafe JSON data');
|
||||
@@ -272,7 +281,7 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
|
||||
const comparisonPeriod = value.comparisonPeriod === undefined ? undefined : safeContext(value.comparisonPeriod);
|
||||
const evidenceRefs = safeTextList(value.evidenceRefs, 100);
|
||||
const requiredFields = safeTextList(value.requiredFields, 100);
|
||||
const note = value.note === undefined ? undefined : boundedText(value.note, 500);
|
||||
const rawNote = value.note === undefined ? undefined : boundedText(value.note, 500);
|
||||
const stage = value.stage === undefined ? undefined : value.stage;
|
||||
const sectionKey = value.sectionKey === undefined ? undefined : value.sectionKey;
|
||||
const dimension = value.dimension === undefined ? undefined : value.dimension;
|
||||
@@ -292,6 +301,12 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
|
||||
...(coverage.denominator === undefined ? {} : { denominator: Number(coverage.denominator) }),
|
||||
}
|
||||
: null;
|
||||
// v1 saved rate-drop charts used positive values for declines. New charts
|
||||
// carry "本期减比较期" in the existing bounded note field. This survives the
|
||||
// backend's strict v1 field allowlist; unmarked snapshots are legacy values.
|
||||
const normalizeLegacyRateDrop = metric === 'rate_drop_pp' && unit === 'pp'
|
||||
&& !(rawNote || '').includes('本期减比较期');
|
||||
const note = normalizeLegacyRateDrop ? canonicalLegacyRateDropNote(rawNote || undefined) : rawNote;
|
||||
|
||||
const categories = Array.isArray(value.categories) && value.categories.length > 0 && value.categories.length <= MAX_VISUAL_CATEGORIES
|
||||
? value.categories.map(category => {
|
||||
@@ -325,7 +340,7 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
|
||||
return null;
|
||||
}
|
||||
if (unit === 'ratio' && (item < 0 || (!allowsAboveOneRatio(metric || '') && item > 1))) invalidValueCells.push(`${seriesIndex}:${valueIndex}`);
|
||||
return item;
|
||||
return normalizeLegacyRateDrop ? -item : item;
|
||||
});
|
||||
series.push({ key, label, values });
|
||||
}
|
||||
@@ -335,7 +350,7 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
|
||||
const valid = !!id && !!type && !!title && subtitle !== null && UNIT_VALUES.has(unit as AnalysisVisualUnit)
|
||||
&& !!metric && !!originTurnId && !!scope && isValidAnalysisPeriodContext(scope)
|
||||
&& !!period && isValidAnalysisPeriodContext(period) && (value.comparisonPeriod === undefined || !!comparisonPeriod && isValidAnalysisPeriodContext(comparisonPeriod))
|
||||
&& !!evidenceRefs && !!requiredFields && (value.note === undefined || note !== null)
|
||||
&& !!evidenceRefs && !!requiredFields && (value.note === undefined || rawNote !== null)
|
||||
&& (stage === undefined || stage === 'black' || stage === 'bright')
|
||||
&& (sectionKey === undefined || SECTION_KEYS.has(sectionKey as AnalysisVisualSectionKey))
|
||||
&& (dimension === undefined || DIMENSIONS.has(dimension as AnalysisVisualDimension))
|
||||
@@ -877,7 +892,8 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
}),
|
||||
itemStyle: { color: colors[seriesIndex % colors.length] },
|
||||
connectNulls: false,
|
||||
smooth: false,
|
||||
smooth: ['line', 'area'].includes(visual.type) ? 0.15 : false,
|
||||
smoothMonotone: 'x',
|
||||
...(['bar', 'column'].includes(visual.type) ? {
|
||||
barMaxWidth: combinedDefects ? 18 : 32,
|
||||
...(combinedDefects ? { stack: 'combined-defect-stage', barWidth: 18 } : {}),
|
||||
|
||||
+218
-48
@@ -1,7 +1,15 @@
|
||||
import { WORKSPACE_INVALIDATED } from './pageCache';
|
||||
import { consumeEventStream, type StreamEvent } from './eventStream';
|
||||
import { publicErrorMessage } from './publicDataDisplay';
|
||||
import { RequestTimeoutError, withRequestDeadline } from './requestDeadline';
|
||||
import {
|
||||
clearReadCache,
|
||||
configureRequestScope,
|
||||
coordinateRequest,
|
||||
getRequestDiagnostics,
|
||||
invalidateReadResources,
|
||||
resetRequestScope,
|
||||
type CoordinatedResult,
|
||||
} from './requestCoordinator';
|
||||
import type {
|
||||
AuthUser,
|
||||
FilterField,
|
||||
@@ -9,6 +17,7 @@ import type {
|
||||
Collection,
|
||||
FineDefectTopResponse,
|
||||
MetricsResponse,
|
||||
TrendResponse,
|
||||
OptionsResponse,
|
||||
QueryParams,
|
||||
RecordExportParams,
|
||||
@@ -17,6 +26,8 @@ import type {
|
||||
} from './types';
|
||||
import type { ConfigureSourceBody, DataStage, DataWorkflowOperation, DataWorkflowStatus, MasterWorkbookImportBody, MasterWorkbookPreview, SourceDeletionPreview, SourceUploadOptions, WorkbookPreview } from './NoCodeDataTypes';
|
||||
|
||||
export { configureRequestScope, getRequestDiagnostics, invalidateReadResources, resetRequestScope };
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
details: unknown;
|
||||
@@ -39,8 +50,9 @@ async function fetchApi(path: string, init: RequestInit): Promise<Response> {
|
||||
}
|
||||
}
|
||||
|
||||
async function readResponse<T>(response: Response): Promise<T> {
|
||||
async function readResponse<T>(response: Response): Promise<CoordinatedResult<T>> {
|
||||
const raw = await response.text();
|
||||
const responseBytes = new TextEncoder().encode(raw).byteLength;
|
||||
let payload: unknown;
|
||||
if (raw) {
|
||||
try {
|
||||
@@ -61,43 +73,83 @@ async function readResponse<T>(response: Response): Promise<T> {
|
||||
: typeof payload === 'string' && payload.trim()
|
||||
? payload
|
||||
: `请求失败(${response.status})`;
|
||||
throw new ApiError(response.status, message, payload);
|
||||
const error = new ApiError(response.status, message, payload);
|
||||
Object.defineProperty(error, 'responseBytes', { value: responseBytes });
|
||||
throw error;
|
||||
}
|
||||
if (typeof payload === 'string') throw new ApiError(response.status, '服务返回格式异常,请稍后重试。');
|
||||
return payload as T;
|
||||
if (typeof payload === 'string') {
|
||||
const error = new ApiError(response.status, '服务返回格式异常,请稍后重试。');
|
||||
Object.defineProperty(error, 'responseBytes', { value: responseBytes });
|
||||
throw error;
|
||||
}
|
||||
return { data: payload as T, status: response.status, bytes: responseBytes };
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init: RequestInit = {}, timeoutMs?: number): Promise<T> {
|
||||
export async function request<T>(path: string, init: RequestInit = {}, timeoutMs?: number): Promise<T> {
|
||||
const headers = new Headers(init.headers);
|
||||
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json');
|
||||
const send = async (signal = init.signal) => {
|
||||
const response = await fetchApi(path, { ...init, signal, headers, credentials: 'same-origin', cache: 'no-store' });
|
||||
return readResponse<T>(response);
|
||||
};
|
||||
if (!timeoutMs) return send();
|
||||
try { return await withRequestDeadline(signal => send(signal), timeoutMs); }
|
||||
const method = (init.method ?? 'GET').toUpperCase();
|
||||
try {
|
||||
return await coordinateRequest({
|
||||
url: path,
|
||||
method,
|
||||
signal: init.signal ?? undefined,
|
||||
timeoutMs: timeoutMs ?? requestTimeoutFor(path),
|
||||
cache: method === 'GET' && isImmutableRead(path),
|
||||
tags: requestResourceTags(path),
|
||||
category: requestCategory(path),
|
||||
priority: requestPriority(path),
|
||||
execute: async signal => {
|
||||
const response = await fetchApi(path, { ...init, signal, headers, credentials: 'same-origin', cache: 'no-store' });
|
||||
return readResponse<T>(response);
|
||||
},
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof RequestTimeoutError) throw new ApiError(408, '连接质量数据服务超时,请点击重新连接;服务恢复后可继续使用。');
|
||||
handleAccessFailure(error);
|
||||
if (error instanceof Error && error.name === 'RequestTimeoutError') throw new ApiError(408, '连接质量数据服务超时,请点击重新连接;服务恢复后可继续使用。');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function requestBlob(path: string, signal?: AbortSignal): Promise<{ blob: Blob; filename: string }> {
|
||||
const response = await fetchApi(path, { credentials: 'same-origin', cache: 'no-store', signal });
|
||||
if (!response.ok) {
|
||||
const raw = await response.text();
|
||||
let payload: unknown = raw;
|
||||
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
||||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||||
const message = typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `下载失败(${response.status})`;
|
||||
throw new ApiError(response.status, message, payload);
|
||||
try {
|
||||
return await coordinateRequest({
|
||||
url: path,
|
||||
method: 'GET',
|
||||
signal,
|
||||
timeoutMs: 900_000,
|
||||
queue: false,
|
||||
retry: false,
|
||||
tags: requestResourceTags(path),
|
||||
category: 'export',
|
||||
priority: 'active',
|
||||
execute: async requestSignal => {
|
||||
const response = await fetchApi(path, { credentials: 'same-origin', cache: 'no-store', signal: requestSignal });
|
||||
if (!response.ok) {
|
||||
const raw = await response.text();
|
||||
let payload: unknown = raw;
|
||||
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
||||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||||
const message = typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `下载失败(${response.status})`;
|
||||
const error = new ApiError(response.status, message, payload);
|
||||
Object.defineProperty(error, 'responseBytes', { value: new TextEncoder().encode(raw).byteLength });
|
||||
throw error;
|
||||
}
|
||||
const disposition = response.headers.get('Content-Disposition') || '';
|
||||
const encoded = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
|
||||
const plain = disposition.match(/filename="?([^";]+)"?/i)?.[1];
|
||||
let filename = 'source-evidence.xlsx';
|
||||
try { filename = encoded ? decodeURIComponent(encoded) : plain || filename; } catch { filename = plain || filename; }
|
||||
const blob = await response.blob();
|
||||
return { data: { blob, filename }, status: response.status, bytes: blob.size };
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
handleAccessFailure(error);
|
||||
if (error instanceof Error && error.name === 'RequestTimeoutError') throw new ApiError(408, '文件导出超时,请稍后重试。');
|
||||
throw error;
|
||||
}
|
||||
const disposition = response.headers.get('Content-Disposition') || '';
|
||||
const encoded = disposition.match(/filename\*=UTF-8''([^;]+)/i)?.[1];
|
||||
const plain = disposition.match(/filename="?([^";]+)"?/i)?.[1];
|
||||
let filename = 'source-evidence.xlsx';
|
||||
try { filename = encoded ? decodeURIComponent(encoded) : plain || filename; } catch { filename = plain || filename; }
|
||||
return { blob: await response.blob(), filename };
|
||||
}
|
||||
|
||||
export type { StreamEvent } from './eventStream';
|
||||
@@ -105,16 +157,21 @@ export type { StreamEvent } from './eventStream';
|
||||
async function readEventStream(path: string, options: { signal?: AbortSignal; lastEventId?: string; onEvent: (event: StreamEvent) => void }): Promise<void> {
|
||||
const headers = new Headers({ Accept: 'text/event-stream' });
|
||||
if (options.lastEventId) headers.set('Last-Event-ID', options.lastEventId);
|
||||
const response = await fetchApi(path, { headers, credentials: 'same-origin', cache: 'no-store', signal: options.signal });
|
||||
if (!response.ok) {
|
||||
const raw = await response.text();
|
||||
let payload: unknown = raw;
|
||||
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
||||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||||
throw new ApiError(response.status, typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `事件流读取失败(${response.status})`, payload);
|
||||
try {
|
||||
const response = await fetchApi(path, { headers, credentials: 'same-origin', cache: 'no-store', signal: options.signal });
|
||||
if (!response.ok) {
|
||||
const raw = await response.text();
|
||||
let payload: unknown = raw;
|
||||
try { payload = raw ? JSON.parse(raw) as unknown : undefined; } catch { /* keep plain text */ }
|
||||
const body = payload && typeof payload === 'object' ? payload as Record<string, unknown> : undefined;
|
||||
throw new ApiError(response.status, typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `事件流读取失败(${response.status})`, payload);
|
||||
}
|
||||
if (!response.body) throw new ApiError(response.status, '浏览器没有收到可读的分析事件流');
|
||||
await consumeEventStream(response.body, options.onEvent);
|
||||
} catch (error) {
|
||||
handleAccessFailure(error);
|
||||
throw error;
|
||||
}
|
||||
if (!response.body) throw new ApiError(response.status, '浏览器没有收到可读的分析事件流');
|
||||
await consumeEventStream(response.body, options.onEvent);
|
||||
}
|
||||
|
||||
export async function refreshCsrf(): Promise<string> {
|
||||
@@ -131,7 +188,7 @@ async function mutate<T>(path: string, body?: unknown, method = 'POST', timeoutM
|
||||
headers,
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
}, timeoutMs);
|
||||
if (!silent && !/^\/api\/(?:analysis|auth)(?:\/|$)/.test(path)) window.dispatchEvent(new Event(WORKSPACE_INVALIDATED));
|
||||
if (!silent && !/^\/api\/(?:analysis|auth)(?:\/|$)/.test(path)) invalidateAfterMutation(path);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -142,17 +199,17 @@ async function queryPost<T>(path: string, body: unknown, signal?: AbortSignal):
|
||||
|
||||
async function mutateForm<T>(path: string, body: FormData): Promise<T> {
|
||||
const token = csrfToken ?? await refreshCsrf();
|
||||
const result = await request<T>(path, { method: 'POST', headers: { 'X-XSRF-TOKEN': token }, body });
|
||||
window.dispatchEvent(new Event(WORKSPACE_INVALIDATED));
|
||||
const result = await request<T>(path, { method: 'POST', headers: { 'X-XSRF-TOKEN': token }, body }, 900_000);
|
||||
invalidateAfterMutation(path);
|
||||
return result;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
sourceColumnCatalog(releaseId?: string) { return request<{releaseId:string;sourceFields:SourceColumnField[]}>(`/api/analysis/source/catalog?${toQuery({releaseId})}`); },
|
||||
sourceColumnCatalog(releaseId?: string, signal?: AbortSignal) { return request<{releaseId:string;sourceFields:SourceColumnField[]}>(`/api/analysis/source/catalog?${toQuery({releaseId})}`, { signal }); },
|
||||
sourceColumnValues(body: Record<string,unknown>, signal?: AbortSignal) { return queryPost<{values:Array<string|null>;hasMore?:boolean;total?:number;limit?:number}>('/api/analysis/source/values',body,signal); },
|
||||
workspaceState() { return request<{ authRevision: string; dataRevision: string }>('/api/workspace/state', {}, 8000); },
|
||||
filterFields(manage = false) { return request<FilterField[]>(`/api/filter-fields?manage=${manage}`); },
|
||||
filterFieldOptions(key: string, search = '') { return request<{ values: string[]; hasMore: boolean }>(`/api/filter-fields/options?${toQuery({key, search})}`); },
|
||||
workspaceState() { return request<{ authRevision: string; dataRevision: string; currentReleaseId: string | null }>('/api/workspace/state', {}, 8000); },
|
||||
filterFields(manage = false, signal?: AbortSignal) { return request<FilterField[]>(`/api/filter-fields?manage=${manage}`, { signal }); },
|
||||
filterFieldOptions(key: string, search = '', signal?: AbortSignal) { return request<{ values: string[]; hasMore: boolean }>(`/api/filter-fields/options?${toQuery({key, search})}`, { signal }); },
|
||||
filterFieldColumns() { return request<{ black: string[]; bright: string[] }>('/api/filter-fields/columns'); },
|
||||
saveFilterFields(fields: FilterField[]) { return mutate<FilterField[]>('/api/filter-fields', fields, 'PUT'); },
|
||||
refreshCsrf,
|
||||
@@ -160,17 +217,20 @@ export const api = {
|
||||
const result = await request<{ user: AuthUser }>('/api/auth/me', {}, 8000);
|
||||
return result.user;
|
||||
},
|
||||
login(username: string, password: string) {
|
||||
async login(username: string, password: string) {
|
||||
csrfToken = undefined;
|
||||
resetRequestScope();
|
||||
return mutate<{ user: AuthUser }>('/api/auth/login', { username, password });
|
||||
},
|
||||
logout() {
|
||||
return mutate<void>('/api/auth/logout');
|
||||
async logout() {
|
||||
try { return await mutate<void>('/api/auth/logout'); }
|
||||
finally { csrfToken = undefined; resetRequestScope(); }
|
||||
},
|
||||
changePassword(currentPassword: string, newPassword: string) {
|
||||
return mutate<{ success: boolean }>('/api/auth/change-password', { currentPassword, newPassword });
|
||||
},
|
||||
options() {
|
||||
return request<OptionsResponse>('/api/options');
|
||||
options(signal?: AbortSignal) {
|
||||
return request<OptionsResponse>('/api/options', { signal });
|
||||
},
|
||||
referenceNames() {
|
||||
return request<Pick<OptionsResponse, 'departments' | 'groups' | 'products' | 'projectGroups' | 'groupDepartments'>>('/api/options/reference-names');
|
||||
@@ -178,6 +238,9 @@ export const api = {
|
||||
metrics(params: QueryParams, signal?: AbortSignal) {
|
||||
return request<MetricsResponse>(`/api/metrics?${toQuery(params)}`, { signal });
|
||||
},
|
||||
trend(params: QueryParams, signal?: AbortSignal) {
|
||||
return request<TrendResponse>(`/api/metrics/trend?${toQuery(params)}`, { signal });
|
||||
},
|
||||
fineDefectTop(params: Record<string, unknown>, signal?: AbortSignal) {
|
||||
return queryPost<FineDefectTopResponse>('/api/analysis/defects', params, signal);
|
||||
},
|
||||
@@ -690,6 +753,113 @@ function toQuery(values: object): string {
|
||||
return query.toString();
|
||||
}
|
||||
|
||||
function requestPath(path: string): string {
|
||||
const base = typeof location === 'undefined' ? 'http://localhost' : location.origin;
|
||||
return new URL(path, base).pathname;
|
||||
}
|
||||
|
||||
function requestTimeoutFor(path: string): number | undefined {
|
||||
const pathname = requestPath(path);
|
||||
return pathname === '/api/workspace/state' || pathname === '/api/auth/me' || pathname === '/api/auth/csrf' ? 8_000 : undefined;
|
||||
}
|
||||
|
||||
function isImmutableRead(path: string): boolean {
|
||||
const pathname = requestPath(path);
|
||||
if (pathname === '/api/metrics' || pathname === '/api/metrics/trend') return true;
|
||||
if (pathname === '/api/options' || pathname === '/api/options/reference-names') return true;
|
||||
if (pathname === '/api/analysis/source/catalog' || pathname === '/api/rules/schema') return true;
|
||||
if (/^\/api\/governance\/releases\/[^/]+\/(?:inspect|diff)$/.test(pathname)) return true;
|
||||
if (pathname === '/api/governance/coverage') {
|
||||
const url = new URL(path, typeof location === 'undefined' ? 'http://localhost' : location.origin);
|
||||
return Boolean(url.searchParams.get('releaseId'));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function requestResourceTags(path: string): string[] {
|
||||
const pathname = requestPath(path);
|
||||
if (pathname.startsWith('/api/metrics')) return ['metrics', 'trend', 'query'];
|
||||
if (pathname.startsWith('/api/options')) return ['options', 'query'];
|
||||
if (pathname.startsWith('/api/filter-fields') || pathname === '/api/analysis/source/catalog') return ['options', 'catalog', 'configuration'];
|
||||
if (pathname.startsWith('/api/records')) return ['records', 'query'];
|
||||
if (pathname.startsWith('/api/analytics/targets')) return ['targets', 'query'];
|
||||
if (pathname.startsWith('/api/sources')) return ['sources', 'workflow', 'catalog'];
|
||||
if (pathname.startsWith('/api/data-workflow')) return ['workflow', 'sources', 'tasks', 'releases'];
|
||||
if (pathname.startsWith('/api/tasks') || pathname.startsWith('/api/import-runs')) return ['tasks', 'workflow'];
|
||||
if (pathname.startsWith('/api/analysis/')) return ['analysis', 'reports', 'options', 'catalog'];
|
||||
if (pathname.startsWith('/api/rules') || pathname.startsWith('/api/mappings') || pathname.startsWith('/api/governance/mapping-issues')) return ['configuration', 'metrics', 'trend', 'records', 'options', 'catalog'];
|
||||
if (pathname.startsWith('/api/governance/backups')) return ['backups', 'monitor', 'workflow'];
|
||||
if (pathname.startsWith('/api/governance/monitor')) return ['monitor', 'workflow'];
|
||||
if (pathname.startsWith('/api/governance/')) return ['configuration', 'workflow', 'sources', 'releases'];
|
||||
if (pathname.startsWith('/api/analytics/')) return ['configuration', 'targets'];
|
||||
if (pathname.startsWith('/api/users') || pathname.startsWith('/api/audit') || pathname.includes('/access-policy') || pathname.includes('/effective-access') || pathname.includes('/scope-preview') || pathname.includes('/service-identities') || pathname.includes('/service-bindings')) return ['access', 'users', 'audit', 'policy'];
|
||||
return [];
|
||||
}
|
||||
|
||||
function requestCategory(path: string): string {
|
||||
const pathname = requestPath(path);
|
||||
if (pathname === '/api/workspace/state') return 'workspace';
|
||||
if (pathname.startsWith('/api/auth/')) return 'auth';
|
||||
if (pathname.startsWith('/api/metrics')) return 'metrics';
|
||||
if (pathname.includes('/export') || pathname.endsWith('/download')) return 'export';
|
||||
if (pathname.startsWith('/api/analysis/')) return 'analysis';
|
||||
if (pathname.startsWith('/api/governance/')) return 'governance';
|
||||
if (pathname.startsWith('/api/tasks') || pathname.startsWith('/api/import-runs')) return 'tasks';
|
||||
if (pathname.startsWith('/api/sources')) return 'sources';
|
||||
if (pathname.startsWith('/api/analytics/')) return 'analytics';
|
||||
return 'other';
|
||||
}
|
||||
|
||||
function requestPriority(path: string): 'active' | 'background' {
|
||||
const pathname = requestPath(path);
|
||||
return pathname.startsWith('/api/data-workflow/operations/') || pathname.startsWith('/api/import-runs/') || pathname.startsWith('/api/tasks/')
|
||||
? 'background'
|
||||
: 'active';
|
||||
}
|
||||
|
||||
function mutationResources(path: string): string[] | null {
|
||||
const pathname = requestPath(path);
|
||||
if (pathname.startsWith('/api/auth/') || pathname.startsWith('/api/analysis/')) return [];
|
||||
if (pathname.startsWith('/api/users') || pathname.startsWith('/api/audit') || pathname.includes('/access-policy') || pathname.includes('/effective-access') || pathname.includes('/scope-preview') || pathname.includes('/service-identities') || pathname.includes('/service-bindings')) return ['*'];
|
||||
if (pathname.startsWith('/api/sources') || pathname.startsWith('/api/releases') || pathname.startsWith('/api/data-workflow') || pathname.startsWith('/api/import-runs')) {
|
||||
return ['metrics', 'trend', 'records', 'options', 'catalog', 'sources', 'workflow', 'tasks', 'releases', 'configuration'];
|
||||
}
|
||||
if (pathname.startsWith('/api/filter-fields')) return ['options', 'catalog', 'query', 'configuration'];
|
||||
if (pathname.startsWith('/api/rules') || pathname.startsWith('/api/mappings') || pathname.startsWith('/api/governance/mapping-issues') || pathname.startsWith('/api/metric-dictionary')) {
|
||||
return ['metrics', 'trend', 'records', 'options', 'catalog', 'configuration'];
|
||||
}
|
||||
if (pathname.startsWith('/api/tasks')) return ['tasks', 'workflow'];
|
||||
if (pathname.startsWith('/api/governance/backups')) return ['backups', 'monitor', 'workflow', 'configuration'];
|
||||
if (pathname.startsWith('/api/governance/monitor')) return ['monitor', 'workflow', 'configuration'];
|
||||
if (pathname.startsWith('/api/analytics/targets')) return ['targets', 'configuration'];
|
||||
if (pathname.startsWith('/api/analytics/')) return ['configuration'];
|
||||
if (pathname.startsWith('/api/governance/')) return ['configuration', 'workflow', 'sources', 'releases'];
|
||||
if (pathname.startsWith('/api/')) return null;
|
||||
return null;
|
||||
}
|
||||
|
||||
function invalidateAfterMutation(path: string): void {
|
||||
const resources = mutationResources(path);
|
||||
if (resources?.length === 0) return;
|
||||
const invalidated = resources ?? ['*'];
|
||||
invalidateReadResources(resources?.includes('*') ? undefined : resources ?? undefined);
|
||||
window.dispatchEvent(new CustomEvent(WORKSPACE_INVALIDATED, { detail: { resources: invalidated } }));
|
||||
}
|
||||
|
||||
function hasStatus(error: unknown, status: number): boolean {
|
||||
return !!error && typeof error === 'object' && (error as { status?: unknown }).status === status;
|
||||
}
|
||||
|
||||
function handleAccessFailure(error: unknown): void {
|
||||
if (hasStatus(error, 401)) {
|
||||
csrfToken = undefined;
|
||||
resetRequestScope();
|
||||
} else if (hasStatus(error, 403)) {
|
||||
clearReadCache();
|
||||
window.dispatchEvent(new Event('quality-permission-recheck'));
|
||||
}
|
||||
}
|
||||
|
||||
const MULTI_VALUE_MARKER = '~qv1~';
|
||||
|
||||
/** Encodes multiple selected values into the scalar query wire format understood by the API. */
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
.query-page { --defect-black: #718797; --defect-black-2: #A9BAC5; --defect-black-3: #D5E0E6; --defect-bright: var(--query-bright,var(--blue)); }
|
||||
:root[data-workspace-theme='dark'] .query-page { --defect-black: #B9BEC8; }
|
||||
.query-page .defect-stage-title.black { color: var(--defect-black); }
|
||||
.query-page .defect-stage-title.bright { color: var(--defect-bright); }
|
||||
.query-page .defect-stage-title.black i,.query-page .defect-stage-title.bright i { background: currentColor; }
|
||||
.defect-composition { position: relative; min-width: 0; padding-top: 2px; }
|
||||
.defect-composition-unit { font-size: var(--font-note); line-height: 18px; color: var(--muted-ink); }
|
||||
.defect-composition-plot { width: 100%; min-width: 0; height: 94px; }
|
||||
.defect-composition-empty { position: absolute; inset: 23px 0 auto; height: 65px; display: flex; align-items: center; justify-content: center; color: var(--muted-ink); font-size: var(--font-control); }
|
||||
.defect-composition-table { width: 100%; table-layout: fixed; border-collapse: collapse; margin: 8px 0 0; font-size: var(--font-table); }
|
||||
.defect-composition-table th { width: 25%; padding: 0 4px; text-align: center; height: 30px; font-size: var(--font-note); font-weight: 500; color: var(--ink); }
|
||||
.defect-composition-table td { height: 37px; padding: 0 4px; text-align: center; border-top: 1px solid color-mix(in srgb,var(--line) 65%,transparent); color: var(--muted-ink); font-family: var(--font-numeric); font-variant-numeric: tabular-nums; cursor: pointer; }
|
||||
.defect-composition-table td.defect-composition-weight { color: var(--ink); font-weight: 600; }
|
||||
.defect-composition-table tr:hover td { background: var(--hover); }
|
||||
.defect-composition-category { display: inline-grid; grid-template-columns: 9px minmax(0,1fr); align-items: center; gap: 9px; width: calc(3em + 18px); max-width: 100%; padding: 5px 0; text-align: center; color: var(--ink); font: var(--font-table) var(--font-ui); background: transparent; border: 0; cursor: pointer; }
|
||||
.defect-composition-category i { flex: 0 0 9px; height: 9px; background: var(--blue); }
|
||||
.defect-composition-category:focus-visible { outline: 2px solid var(--blue); outline-offset: 3px; }
|
||||
.defect-stage-grid:has(.defect-composition) > .defect-stage-column { padding: 0 16px 14px; }
|
||||
.defect-stage-grid:has(.defect-composition) .defect-stage-title { padding: 14px 1px 10px; }
|
||||
@media(max-width:760px) { :is(.defect-stage-grid,.stage-defect-comparison):has(.defect-composition) > .defect-stage-column { padding: 0 12px 12px; } }
|
||||
@@ -0,0 +1,26 @@
|
||||
export type GovernanceResource = 'coverage' | 'protocols' | 'changes' | 'candidates' | 'documents';
|
||||
export type GovernanceFreshness = Partial<Record<GovernanceResource, boolean>>;
|
||||
|
||||
export const GOVERNANCE_RESOURCES: GovernanceResource[] = ['coverage', 'protocols', 'changes', 'candidates', 'documents'];
|
||||
|
||||
const TAB_RESOURCES: Record<string, GovernanceResource[]> = {
|
||||
coverage: ['coverage'],
|
||||
protocols: ['protocols'],
|
||||
changes: ['changes', 'candidates'],
|
||||
revisions: ['documents'],
|
||||
};
|
||||
|
||||
export function governanceResourcesForTab(tab: string): GovernanceResource[] {
|
||||
return TAB_RESOURCES[tab] || [];
|
||||
}
|
||||
|
||||
export function markGovernanceResourcesStale(
|
||||
current: GovernanceFreshness,
|
||||
resources: GovernanceResource[] = GOVERNANCE_RESOURCES,
|
||||
): GovernanceFreshness {
|
||||
return resources.reduce((next, resource) => ({ ...next, [resource]: true }), { ...current });
|
||||
}
|
||||
|
||||
export function markGovernanceResourcesFresh(current: GovernanceFreshness, resources: GovernanceResource[]): GovernanceFreshness {
|
||||
return resources.reduce((next, resource) => ({ ...next, [resource]: false }), { ...current });
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export function importIssuePageKey(runId: string, page: number): string {
|
||||
return `${runId}:${page}`;
|
||||
}
|
||||
|
||||
export function matchesImportIssuePage(loadedRunId: string, loadedPage: number, runId: string, page: number): boolean {
|
||||
return loadedRunId === runId && loadedPage === page;
|
||||
}
|
||||
|
||||
export async function runImportPollFollowup<T>(
|
||||
runId: string,
|
||||
isCurrent: (runId: string) => boolean,
|
||||
followup: () => Promise<T>,
|
||||
): Promise<{ started: false; current: false } | { started: true; current: boolean; value: T }> {
|
||||
if (!isCurrent(runId)) return { started: false, current: false };
|
||||
const value = await followup();
|
||||
return { started: true, current: isCurrent(runId), value };
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { MetricRow, Stage } from './types';
|
||||
|
||||
export type MetricStageField = 'totalWeight' | 'qualifiedWeight' | 'scrapWeight' | 'headquartersScrapWeight' | 'rate';
|
||||
export type MetricStageColumn = { kind: 'metric'; field: MetricStageField } | { kind: 'defect'; name: string };
|
||||
export type MetricFieldView = 'key' | 'full';
|
||||
export type MetricPageView = 'overall' | 'department' | 'group' | 'product' | 'blackProduct' | 'brightProduct';
|
||||
|
||||
const KEY_FIELDS: MetricStageField[] = ['totalWeight', 'qualifiedWeight', 'scrapWeight'];
|
||||
|
||||
/** The stage pages start expanded; the four organization/product pages start compact. */
|
||||
export function defaultFullMetricFields(page: string): boolean {
|
||||
return page === 'blackProduct' || page === 'brightProduct';
|
||||
}
|
||||
|
||||
/** Keep the full/key field contract shared by the summary and trend tables. */
|
||||
export function metricStageColumnPlan(
|
||||
rows: MetricRow[],
|
||||
stage: Stage,
|
||||
fullFields: boolean,
|
||||
rateBasis: 'original' | 'withoutHeadquartersScrap',
|
||||
): MetricStageColumn[] {
|
||||
const columns: MetricStageColumn[] = KEY_FIELDS.map(field => ({ kind: 'metric', field }));
|
||||
if (fullFields) {
|
||||
const defectNames = Array.from(new Set(rows.flatMap(row => (row[stage]?.defects || []).map(item => item.name))));
|
||||
const defectColumns = defectNames.map(name => ({ kind: 'defect' as const, name }));
|
||||
columns.push(...defectColumns);
|
||||
if (stage === 'bright' && rateBasis === 'original') {
|
||||
const diffusionIndex = defectNames.indexOf('扩散废');
|
||||
const insertAt = KEY_FIELDS.length + (diffusionIndex < 0 ? defectNames.length : diffusionIndex + 1);
|
||||
columns.splice(insertAt, 0, { kind: 'metric', field: 'headquartersScrapWeight' });
|
||||
}
|
||||
}
|
||||
columns.push({ kind: 'metric', field: 'rate' });
|
||||
return columns;
|
||||
}
|
||||
@@ -1,7 +1,12 @@
|
||||
import { createContext, useContext, useEffect, useRef } from 'react';
|
||||
|
||||
export const WORKSPACE_INVALIDATED = 'quality-workspace-invalidated';
|
||||
export const PageCacheContext = createContext({ active: true, initialSearch: undefined as string | undefined, refreshKey: 0, onLocationChange: (_search: string) => {} });
|
||||
export type PageCacheState = {
|
||||
active: boolean; initialSearch?: string; refreshKey: number;
|
||||
currentReleaseId?: string | null; authRevision?: string; dataRevision?: string;
|
||||
onLocationChange: (search: string) => void;
|
||||
};
|
||||
export const PageCacheContext = createContext<PageCacheState>({ active: true, refreshKey: 0, onLocationChange: () => {} });
|
||||
export const usePageCache = () => useContext(PageCacheContext);
|
||||
|
||||
/** Revalidate retained maintenance data on a real revision change, not on every visit. */
|
||||
|
||||
@@ -3,6 +3,18 @@ export function previousCompleteMonth(reference = new Date()): { year: number; m
|
||||
return { year: previous.getFullYear(), month: previous.getMonth() + 1 };
|
||||
}
|
||||
|
||||
export function defaultQueryMonth(options?: { periods?: string[]; latestDataPeriod?: { year?: number; month?: number } } | null, reference = new Date()): { year: number; month: number } {
|
||||
const previous = previousCompleteMonth(reference);
|
||||
const key = `${previous.year}-${String(previous.month).padStart(2, '0')}`;
|
||||
const latest = options?.latestDataPeriod;
|
||||
const latestKey = latest?.year && latest.month && latest.month >= 1 && latest.month <= 12
|
||||
? `${latest.year}-${String(latest.month).padStart(2, '0')}` : undefined;
|
||||
const previousMissing = Array.isArray(options?.periods)
|
||||
? !options.periods.includes(key) : latestKey != null && latestKey < key;
|
||||
// 只按已发布月份判断;筛选结果为空不会改动用户选定的月份。
|
||||
return previousMissing ? previousCompleteMonth(new Date(previous.year, previous.month - 1, 1)) : previous;
|
||||
}
|
||||
|
||||
export function previousCompleteQuarter(reference = new Date()): { year: number; quarter: number } {
|
||||
const firstMonthOfCurrentQuarter = Math.floor(reference.getMonth() / 3) * 3;
|
||||
const previousQuarterEnd = new Date(reference.getFullYear(), firstMonthOfCurrentQuarter, 0);
|
||||
|
||||
@@ -4,6 +4,11 @@
|
||||
.query-awaiting-data .metric-value { opacity: .5; }
|
||||
.query-table-content { min-width: 0; }
|
||||
.query-table-content[aria-busy="true"] { pointer-events: none; }
|
||||
.defect-refresh-indicator { display: inline-flex; align-items: center; gap: 6px; margin-left: auto; color: var(--ink); font-size: var(--font-note); }
|
||||
.defect-pareto-heading { align-items: center; }
|
||||
.defect-track > i { transition: width 520ms cubic-bezier(.22,.61,.36,1); }
|
||||
.defect-pareto-chart[inert] { pointer-events: none; }
|
||||
@media (prefers-reduced-motion: reduce) { .defect-track > i { transition: none; } }
|
||||
.source-records-drawer .ant-drawer-content,
|
||||
.source-records-drawer .ant-drawer-header,
|
||||
.source-records-drawer .ant-drawer-body { background: var(--surface, #fff); }
|
||||
@@ -46,3 +51,6 @@
|
||||
.record-query-tools { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.record-query-tools > .ant-segmented { grid-column: 2; }
|
||||
}
|
||||
.smooth-table-frame { min-width: 0; overflow: clip; transition: height 520ms cubic-bezier(.22,.61,.36,1); }
|
||||
.animated-metric-text { font-variant-numeric: tabular-nums lining-nums; }
|
||||
@media (prefers-reduced-motion: reduce) { .smooth-table-frame { transition: none; } }
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { QueryParams } from './types';
|
||||
|
||||
export function loadedQueryPeriod(query: Pick<QueryParams, 'year' | 'month' | 'quarter'>): string {
|
||||
if (query.year == null) return '全部年份';
|
||||
return query.month ? `${query.year}年${String(query.month).padStart(2, '0')}月`
|
||||
: query.quarter ? `${query.year}年第${query.quarter}季度` : `${query.year}年全年`;
|
||||
}
|
||||
|
||||
|
||||
/** Request snapshots follow the workspace unless the incoming link explicitly pins a release. */
|
||||
export function queryForLocation(query: QueryParams, explicitReleaseId?: string): QueryParams {
|
||||
const { releaseId: _boundRelease, ...filters } = query;
|
||||
return explicitReleaseId ? { ...filters, releaseId: explicitReleaseId } : filters;
|
||||
}
|
||||
|
||||
export function readQueryLocation(search = window.location.search): Partial<QueryParams> {
|
||||
const context = new URLSearchParams(search).get('context');
|
||||
if (!context) return {};
|
||||
try {
|
||||
const binary = atob(context.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - context.length % 4) % 4));
|
||||
const parsed = JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, character => character.charCodeAt(0)))) as { query?: unknown };
|
||||
if (!parsed.query || typeof parsed.query !== 'object') return {};
|
||||
const query = { ...(parsed.query as Partial<QueryParams>) };
|
||||
return query;
|
||||
} catch { return {}; }
|
||||
}
|
||||
|
||||
|
||||
/** Keep the applied scope readable while the controls already show a newer draft. */
|
||||
export function loadedQueryScope(query: QueryParams, decode: (value: string | undefined) => string[]): string {
|
||||
const selections = [query.department, query.group, query.product, query.projectGroup]
|
||||
.flatMap(value => decode(value)).map(value => value === '__UNASSIGNED__' ? '未分类' : value);
|
||||
const sourceCount = (query.columnFilters?.length || 0) + Object.keys(query.extraFilters || {}).length;
|
||||
return [loadedQueryPeriod(query), ...selections, query.productSearch ? `搜索:${query.productSearch}` : '', sourceCount ? `来源条件 ${sourceCount} 项` : ''].filter(Boolean).join(' · ');
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
export interface RequestScope {
|
||||
userId: string | null;
|
||||
authRevision: string | null;
|
||||
dataRevision: string | null;
|
||||
currentReleaseId: string | null;
|
||||
}
|
||||
|
||||
export interface CoordinatedResult<T> {
|
||||
data: T;
|
||||
status?: number;
|
||||
bytes?: number;
|
||||
}
|
||||
|
||||
export interface CoordinatedRequest<T> {
|
||||
url: string;
|
||||
method?: string;
|
||||
signal?: AbortSignal;
|
||||
timeoutMs?: number;
|
||||
cache?: boolean;
|
||||
queue?: boolean;
|
||||
retry?: boolean;
|
||||
tags?: readonly string[];
|
||||
category?: string;
|
||||
priority?: 'active' | 'background';
|
||||
execute: (signal: AbortSignal) => Promise<CoordinatedResult<T>>;
|
||||
}
|
||||
|
||||
export interface RequestDiagnostic {
|
||||
category: string;
|
||||
elapsedMs: number;
|
||||
bytes: number;
|
||||
status: number | null;
|
||||
retries: number;
|
||||
}
|
||||
|
||||
export const REQUEST_CACHE_LIMIT_BYTES = 32 * 1024 * 1024;
|
||||
export const REQUEST_MAX_GET_CONCURRENCY = 4;
|
||||
const DEFAULT_GET_TIMEOUT_MS = 30_000;
|
||||
const RETRY_DELAY_MS = 1_000;
|
||||
const MAX_DIAGNOSTICS = 120;
|
||||
|
||||
export class RequestTimeoutError extends Error {
|
||||
constructor() {
|
||||
super('请求超时');
|
||||
this.name = 'RequestTimeoutError';
|
||||
}
|
||||
}
|
||||
|
||||
interface CacheEntry {
|
||||
data: unknown;
|
||||
bytes: number;
|
||||
tags: readonly string[];
|
||||
}
|
||||
|
||||
interface Subscriber<T = unknown> {
|
||||
resolve: (value: T) => void;
|
||||
reject: (error: unknown) => void;
|
||||
signal?: AbortSignal;
|
||||
abortListener?: () => void;
|
||||
}
|
||||
|
||||
interface Flight<T = unknown> {
|
||||
key: string;
|
||||
url: string;
|
||||
scopeKey: string;
|
||||
scopeEpoch: number;
|
||||
cacheEpoch: number;
|
||||
controller: AbortController;
|
||||
subscribers: Set<Subscriber<T>>;
|
||||
request: CoordinatedRequest<T>;
|
||||
startedAt: number;
|
||||
deadlineAt: number;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
retries: number;
|
||||
queued: boolean;
|
||||
slotHeld: boolean;
|
||||
settled: boolean;
|
||||
}
|
||||
|
||||
let scope: RequestScope = { userId: null, authRevision: null, dataRevision: null, currentReleaseId: null };
|
||||
let scopeKey = serializeScope(scope);
|
||||
let scopeEpoch = 0;
|
||||
let cacheEpoch = 0;
|
||||
let activeGets = 0;
|
||||
let cacheBytes = 0;
|
||||
const flights = new Map<string, Flight<any>>();
|
||||
const queue: Flight<any>[] = [];
|
||||
const cache = new Map<string, CacheEntry>();
|
||||
const diagnostics: RequestDiagnostic[] = [];
|
||||
const directControllers = new Set<AbortController>();
|
||||
|
||||
export function configureRequestScope(next: RequestScope): void {
|
||||
const normalized: RequestScope = {
|
||||
userId: next.userId ?? null,
|
||||
authRevision: next.authRevision ?? null,
|
||||
dataRevision: next.dataRevision ?? null,
|
||||
currentReleaseId: next.currentReleaseId ?? null,
|
||||
};
|
||||
const nextKey = serializeScope(normalized);
|
||||
if (nextKey === scopeKey) return;
|
||||
scope = normalized;
|
||||
scopeKey = nextKey;
|
||||
scopeEpoch += 1;
|
||||
clearCache();
|
||||
for (const flight of [...flights.values()]) abortFlight(flight, createAbortError());
|
||||
for (const controller of directControllers) controller.abort();
|
||||
drainQueue();
|
||||
}
|
||||
|
||||
export function invalidateReadResources(tags?: readonly string[]): void {
|
||||
const selected = tags ? new Set(tags) : null;
|
||||
for (const [key, entry] of cache) {
|
||||
if (!selected || entry.tags.some(tag => selected.has(tag))) {
|
||||
cacheBytes -= entry.bytes;
|
||||
cache.delete(key);
|
||||
}
|
||||
}
|
||||
for (const flight of [...flights.values()]) {
|
||||
if (!selected || flight.request.tags?.some(tag => selected.has(tag))) abortFlight(flight, createAbortError());
|
||||
}
|
||||
drainQueue();
|
||||
}
|
||||
|
||||
/** Clears private response data without interrupting unrelated active reads. */
|
||||
export function clearReadCache(): void {
|
||||
clearCache();
|
||||
}
|
||||
|
||||
export function resetRequestScope(): void {
|
||||
scope = { userId: null, authRevision: null, dataRevision: null, currentReleaseId: null };
|
||||
scopeKey = serializeScope(scope);
|
||||
scopeEpoch += 1;
|
||||
clearCache();
|
||||
for (const flight of [...flights.values()]) abortFlight(flight, createAbortError());
|
||||
for (const controller of directControllers) controller.abort();
|
||||
drainQueue();
|
||||
}
|
||||
|
||||
export function coordinateRequest<T>(request: CoordinatedRequest<T>): Promise<T> {
|
||||
const method = (request.method ?? 'GET').toUpperCase();
|
||||
if (request.signal?.aborted) return Promise.reject(createAbortError());
|
||||
if (method !== 'GET' || request.queue === false) return runDirect(request);
|
||||
|
||||
const normalizedUrl = normalizeUrl(request.url);
|
||||
const flightKey = `${scopeEpoch}\u0000${scopeKey}\u0000${normalizedUrl}`;
|
||||
if (request.cache) {
|
||||
const cached = cache.get(flightKey);
|
||||
if (cached) {
|
||||
cache.delete(flightKey);
|
||||
cache.set(flightKey, cached);
|
||||
recordDiagnostic(request.category ?? categoryFromUrl(normalizedUrl), 0, cached.bytes, 200, 0);
|
||||
return Promise.resolve(cloneValue(cached.data) as T);
|
||||
}
|
||||
}
|
||||
|
||||
const existing = flights.get(flightKey) as Flight<T> | undefined;
|
||||
if (existing && !existing.settled) return subscribe(existing, request.signal);
|
||||
|
||||
const timeoutMs = request.timeoutMs ?? DEFAULT_GET_TIMEOUT_MS;
|
||||
const flight: Flight<T> = {
|
||||
key: flightKey,
|
||||
url: normalizedUrl,
|
||||
scopeKey,
|
||||
scopeEpoch,
|
||||
cacheEpoch,
|
||||
controller: new AbortController(),
|
||||
subscribers: new Set(),
|
||||
request: { ...request, method },
|
||||
startedAt: Date.now(),
|
||||
deadlineAt: Date.now() + timeoutMs,
|
||||
retries: 0,
|
||||
queued: true,
|
||||
slotHeld: false,
|
||||
settled: false,
|
||||
};
|
||||
flights.set(flightKey, flight);
|
||||
const subscriber = subscribe(flight, request.signal);
|
||||
flight.timer = setTimeout(() => {
|
||||
abortFlight(flight, new RequestTimeoutError());
|
||||
}, timeoutMs);
|
||||
queue.push(flight);
|
||||
drainQueue();
|
||||
return subscriber;
|
||||
}
|
||||
|
||||
export function getRequestDiagnostics(): readonly RequestDiagnostic[] {
|
||||
return diagnostics.map(item => ({ ...item }));
|
||||
}
|
||||
|
||||
export function clearRequestDiagnostics(): void {
|
||||
diagnostics.length = 0;
|
||||
}
|
||||
|
||||
function subscribe<T>(flight: Flight<T>, signal?: AbortSignal): Promise<T> {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const subscriber: Subscriber<T> = { resolve, reject, signal };
|
||||
if (signal?.aborted) {
|
||||
reject(createAbortError());
|
||||
return;
|
||||
}
|
||||
subscriber.abortListener = () => {
|
||||
removeSubscriber(flight, subscriber);
|
||||
reject(createAbortError());
|
||||
if (flight.subscribers.size === 0) abortFlight(flight, createAbortError());
|
||||
};
|
||||
signal?.addEventListener('abort', subscriber.abortListener, { once: true });
|
||||
flight.subscribers.add(subscriber);
|
||||
});
|
||||
}
|
||||
|
||||
function removeSubscriber<T>(flight: Flight<T>, subscriber: Subscriber<T>): void {
|
||||
flight.subscribers.delete(subscriber);
|
||||
if (subscriber.signal && subscriber.abortListener) subscriber.signal.removeEventListener('abort', subscriber.abortListener);
|
||||
}
|
||||
|
||||
function drainQueue(): void {
|
||||
if (activeGets >= REQUEST_MAX_GET_CONCURRENCY || queue.length === 0) return;
|
||||
queue.sort((left, right) => {
|
||||
const priority = Number(right.request.priority !== 'background') - Number(left.request.priority !== 'background');
|
||||
return priority || left.startedAt - right.startedAt;
|
||||
});
|
||||
while (activeGets < REQUEST_MAX_GET_CONCURRENCY && queue.length > 0) {
|
||||
const flight = queue.shift()!;
|
||||
if (flight.settled || flight.subscribers.size === 0) continue;
|
||||
flight.queued = false;
|
||||
flight.slotHeld = true;
|
||||
activeGets += 1;
|
||||
void executeFlight(flight);
|
||||
}
|
||||
}
|
||||
|
||||
async function executeFlight(flight: Flight<any>): Promise<void> {
|
||||
const request = flight.request;
|
||||
let status: number | null = null;
|
||||
let bytes = 0;
|
||||
try {
|
||||
const result = await executeWithRetry(flight);
|
||||
status = result.status ?? 200;
|
||||
bytes = result.bytes ?? estimateBytes(result.data);
|
||||
if (flight.settled) return;
|
||||
if (!isCurrentScope(flight)) throw createAbortError();
|
||||
if (request.cache && flight.cacheEpoch === cacheEpoch) putCache(flight.key, { data: cloneValue(result.data), bytes, tags: request.tags ?? [] });
|
||||
settleFlight(flight, undefined, result.data);
|
||||
} catch (error) {
|
||||
status = readStatus(error);
|
||||
bytes = readBytes(error);
|
||||
if (!flight.settled) settleFlight(flight, error);
|
||||
} finally {
|
||||
if (flight.timer) clearTimeout(flight.timer);
|
||||
flight.timer = undefined;
|
||||
releaseSlot(flight);
|
||||
recordDiagnostic(request.category ?? categoryFromUrl(flight.url), Date.now() - flight.startedAt, bytes, status, flight.retries);
|
||||
drainQueue();
|
||||
}
|
||||
}
|
||||
|
||||
async function executeWithRetry(flight: Flight<any>): Promise<CoordinatedResult<any>> {
|
||||
for (;;) {
|
||||
if (flight.controller.signal.aborted) throw createAbortError();
|
||||
try {
|
||||
const result = await flight.request.execute(flight.controller.signal);
|
||||
if (flight.controller.signal.aborted) throw createAbortError();
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (flight.controller.signal.aborted || flight.request.retry === false || flight.retries >= 1 || !isRetryable(error)) throw error;
|
||||
flight.retries += 1;
|
||||
await delay(RETRY_DELAY_MS, flight.controller.signal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function runDirect<T>(request: CoordinatedRequest<T>): Promise<T> {
|
||||
const startedAt = Date.now(), ownerEpoch = scopeEpoch;
|
||||
const controller = new AbortController();
|
||||
directControllers.add(controller);
|
||||
let timedOut = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let status: number | null = null;
|
||||
let bytes = 0;
|
||||
let rejectCancellation: (error: Error) => void = () => {};
|
||||
const cancelled = new Promise<never>((_, reject) => { rejectCancellation = reject; });
|
||||
const onCancelled = () => rejectCancellation(createAbortError());
|
||||
controller.signal.addEventListener('abort', onCancelled, { once: true });
|
||||
const abortListener = () => controller.abort();
|
||||
request.signal?.addEventListener('abort', abortListener, { once: true });
|
||||
if (request.signal?.aborted) controller.abort();
|
||||
try {
|
||||
if (controller.signal.aborted) throw createAbortError();
|
||||
if (request.timeoutMs && request.timeoutMs > 0) {
|
||||
timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
controller.abort();
|
||||
}, request.timeoutMs);
|
||||
}
|
||||
const result = await Promise.race([request.execute(controller.signal), cancelled]);
|
||||
if (controller.signal.aborted || ownerEpoch !== scopeEpoch) throw createAbortError();
|
||||
status = result.status ?? 200;
|
||||
bytes = result.bytes ?? estimateBytes(result.data);
|
||||
return result.data;
|
||||
} catch (error) {
|
||||
status = readStatus(error);
|
||||
bytes = readBytes(error);
|
||||
if (timedOut) throw new RequestTimeoutError();
|
||||
throw error;
|
||||
} finally {
|
||||
if (timer) clearTimeout(timer);
|
||||
directControllers.delete(controller);
|
||||
controller.signal.removeEventListener('abort', onCancelled);
|
||||
request.signal?.removeEventListener('abort', abortListener);
|
||||
recordDiagnostic(request.category ?? categoryFromUrl(request.url), Date.now() - startedAt, bytes, status, 0);
|
||||
}
|
||||
}
|
||||
|
||||
function settleFlight(flight: Flight<any>, error?: unknown, value?: unknown): void {
|
||||
if (flight.settled) return;
|
||||
flight.settled = true;
|
||||
if (flight.timer) clearTimeout(flight.timer);
|
||||
flight.timer = undefined;
|
||||
flights.delete(flight.key);
|
||||
if (flight.queued) {
|
||||
const index = queue.indexOf(flight);
|
||||
if (index >= 0) queue.splice(index, 1);
|
||||
flight.queued = false;
|
||||
}
|
||||
const subscribers = [...flight.subscribers];
|
||||
flight.subscribers.clear();
|
||||
for (const subscriber of subscribers) {
|
||||
if (subscriber.signal && subscriber.abortListener) subscriber.signal.removeEventListener('abort', subscriber.abortListener);
|
||||
if (error !== undefined) subscriber.reject(error);
|
||||
else subscriber.resolve(value as any);
|
||||
}
|
||||
}
|
||||
|
||||
function abortFlight(flight: Flight<any>, error: unknown): void {
|
||||
if (flight.settled) return;
|
||||
flight.controller.abort();
|
||||
settleFlight(flight, error);
|
||||
releaseSlot(flight);
|
||||
}
|
||||
|
||||
function releaseSlot(flight: Flight<any>): void {
|
||||
if (!flight.slotHeld) return;
|
||||
flight.slotHeld = false;
|
||||
activeGets = Math.max(0, activeGets - 1);
|
||||
}
|
||||
|
||||
function isCurrentScope(flight: Flight<any>): boolean {
|
||||
return flight.scopeEpoch === scopeEpoch && flight.scopeKey === scopeKey;
|
||||
}
|
||||
|
||||
function putCache(key: string, entry: CacheEntry): void {
|
||||
const safeBytes = Math.max(0, Number.isFinite(entry.bytes) ? entry.bytes : estimateBytes(entry.data));
|
||||
if (safeBytes > REQUEST_CACHE_LIMIT_BYTES) return;
|
||||
const previous = cache.get(key);
|
||||
if (previous) cacheBytes -= previous.bytes;
|
||||
cache.delete(key);
|
||||
cache.set(key, { ...entry, bytes: safeBytes });
|
||||
cacheBytes += safeBytes;
|
||||
while (cacheBytes > REQUEST_CACHE_LIMIT_BYTES && cache.size > 0) {
|
||||
const oldestKey = cache.keys().next().value as string | undefined;
|
||||
if (oldestKey === undefined) break;
|
||||
const oldest = cache.get(oldestKey)!;
|
||||
cache.delete(oldestKey);
|
||||
cacheBytes -= oldest.bytes;
|
||||
}
|
||||
}
|
||||
|
||||
function clearCache(): void {
|
||||
cache.clear();
|
||||
cacheBytes = 0;
|
||||
cacheEpoch += 1;
|
||||
}
|
||||
|
||||
function estimateBytes(value: unknown): number {
|
||||
try { return new TextEncoder().encode(JSON.stringify(value) ?? '').byteLength; }
|
||||
catch { return 0; }
|
||||
}
|
||||
|
||||
function cloneValue(value: unknown): unknown {
|
||||
if (typeof structuredClone === 'function') return structuredClone(value);
|
||||
return value;
|
||||
}
|
||||
|
||||
function recordDiagnostic(category: string, elapsedMs: number, bytes: number, status: number | null, retries: number): void {
|
||||
diagnostics.push({ category, elapsedMs: Math.max(0, elapsedMs), bytes: Math.max(0, bytes), status, retries });
|
||||
if (diagnostics.length > MAX_DIAGNOSTICS) diagnostics.splice(0, diagnostics.length - MAX_DIAGNOSTICS);
|
||||
}
|
||||
|
||||
function isRetryable(error: unknown): boolean {
|
||||
if (!error || typeof error !== 'object') return false;
|
||||
if ((error as { name?: unknown }).name === 'AbortError' || (error as { name?: unknown }).name === 'RequestTimeoutError') return false;
|
||||
const status = readStatus(error);
|
||||
return error instanceof TypeError || status === 0 || status === 502 || status === 503 || status === 504;
|
||||
}
|
||||
|
||||
function readStatus(error: unknown): number | null {
|
||||
if (!error || typeof error !== 'object') return null;
|
||||
const status = (error as { status?: unknown }).status;
|
||||
return typeof status === 'number' && Number.isFinite(status) ? status : null;
|
||||
}
|
||||
|
||||
function readBytes(error: unknown): number {
|
||||
if (!error || typeof error !== 'object') return 0;
|
||||
const bytes = (error as { responseBytes?: unknown }).responseBytes;
|
||||
return typeof bytes === 'number' && Number.isFinite(bytes) ? bytes : 0;
|
||||
}
|
||||
|
||||
function delay(ms: number, signal: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (signal.aborted) { reject(createAbortError()); return; }
|
||||
const timer = setTimeout(() => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
reject(createAbortError());
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeUrl(value: string): string {
|
||||
const base = typeof location === 'undefined' ? 'http://localhost' : location.origin;
|
||||
const url = new URL(value, base);
|
||||
const params = [...url.searchParams.entries()].sort(([leftKey, leftValue], [rightKey, rightValue]) =>
|
||||
leftKey.localeCompare(rightKey) || leftValue.localeCompare(rightValue));
|
||||
const normalized = new URLSearchParams();
|
||||
for (const [key, item] of params) normalized.append(key, item);
|
||||
return `${url.pathname}${normalized.size ? `?${normalized.toString()}` : ''}`;
|
||||
}
|
||||
|
||||
function serializeScope(value: RequestScope): string {
|
||||
return JSON.stringify([value.userId, value.authRevision, value.dataRevision, value.currentReleaseId]);
|
||||
}
|
||||
|
||||
function categoryFromUrl(value: string): string {
|
||||
const pathname = new URL(value, 'http://localhost').pathname;
|
||||
if (pathname === '/api/workspace/state') return 'workspace';
|
||||
if (pathname.startsWith('/api/auth/')) return 'auth';
|
||||
if (pathname.startsWith('/api/metrics')) return 'metrics';
|
||||
if (pathname.includes('/export')) return 'export';
|
||||
if (pathname.startsWith('/api/analysis/')) return 'analysis';
|
||||
if (pathname.startsWith('/api/governance/')) return 'governance';
|
||||
if (pathname.startsWith('/api/tasks')) return 'tasks';
|
||||
if (pathname.startsWith('/api/sources')) return 'sources';
|
||||
if (pathname.startsWith('/api/analytics/')) return 'analytics';
|
||||
return 'other';
|
||||
}
|
||||
|
||||
function createAbortError(): Error {
|
||||
if (typeof DOMException !== 'undefined') return new DOMException('请求已取消', 'AbortError');
|
||||
const error = new Error('请求已取消');
|
||||
error.name = 'AbortError';
|
||||
return error;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/** 仅唤醒依赖这些资源的页面;未知写操作按全局失效处理。 */
|
||||
export function pageUsesResources(page: string, resources?: string[]): boolean {
|
||||
if (!resources?.length || resources.includes('*')) return true;
|
||||
const query = ['overall', 'department', 'group', 'product', 'blackProduct', 'brightProduct'].includes(page);
|
||||
const dependencies = query ? ['metrics', 'trend', 'records', 'options', 'catalog', 'targets', 'query']
|
||||
: page === 'analysis' ? ['analysis', 'options', 'reports', 'catalog']
|
||||
: page === 'sources' || page === 'imports' ? ['sources', 'workflow', 'tasks', 'releases']
|
||||
: page === 'tasks' ? ['tasks', 'workflow', 'backups', 'monitor']
|
||||
: page === 'access' ? ['access', 'users', 'audit', 'policy']
|
||||
: [page, 'configuration', 'workflow'];
|
||||
return resources.some(resource => dependencies.includes(resource));
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { DataField, DataStage, WorkbookPreview } from './NoCodeDataTypes';
|
||||
|
||||
type Candidate = { workbook: WorkbookPreview; stage: DataStage; score: number; matched: number };
|
||||
|
||||
function identify(workbook: WorkbookPreview, fields: Record<DataStage, DataField[]>): Candidate {
|
||||
return (['black', 'bright'] as DataStage[]).map(stage => {
|
||||
const required = fields[stage].filter(field => field.required);
|
||||
const matched = required.filter(field => workbook.preview.headers.includes(field.name)).length;
|
||||
return { workbook, stage, matched, score: required.length ? matched / required.length : 0 };
|
||||
}).sort((a, b) => b.score - a.score || b.matched - a.matched)[0];
|
||||
}
|
||||
|
||||
/** 按业务字段比较各工作表,避免把排在明细前面的汇总页当作导入来源。 */
|
||||
export async function detectSourceWorkbook(
|
||||
initial: WorkbookPreview,
|
||||
fields: Record<DataStage, DataField[]>,
|
||||
preview: (uploadId: string, params: { sheetName: string; headerRow: number; stage: DataStage }) => Promise<WorkbookPreview>,
|
||||
): Promise<{ workbook: WorkbookPreview; stage: DataStage }> {
|
||||
let best = identify(initial, fields);
|
||||
const sheets = initial.sheets.filter(sheet => sheet.sheetName !== initial.preview.sheetName)
|
||||
.sort((a, b) => Number(b.sheetName.includes('明细')) - Number(a.sheetName.includes('明细')));
|
||||
for (const sheet of sheets) {
|
||||
if (best.score === 1) break;
|
||||
const workbook = await preview(initial.uploadId, { sheetName: sheet.sheetName, headerRow: 1, stage: best.stage });
|
||||
const candidate = identify(workbook, fields);
|
||||
if (candidate.score > best.score || candidate.score === best.score && candidate.matched > best.matched) best = candidate;
|
||||
}
|
||||
return { workbook: best.workbook, stage: best.stage };
|
||||
}
|
||||
@@ -1,12 +1,9 @@
|
||||
.stage-product-page .query-toolbar { gap: 10px; }
|
||||
.stage-source-filters { display: contents; }
|
||||
.stage-source-filters > .ant-select { width: 220px; }
|
||||
.stage-source-filter-row { flex: 1 0 100%; display: grid; grid-template-columns: minmax(120px,180px) 150px minmax(240px,1fr) 32px; align-items: center; gap: 10px; }
|
||||
.stage-source-filter-row > strong { overflow-wrap: anywhere; font-size: var(--font-body); }
|
||||
.stage-source-filter-row > .ant-select { width: 100%; min-width: 0; }
|
||||
.stage-query-pending { flex-basis: 100%; color: var(--muted-ink); font-size: var(--font-control); }
|
||||
.stage-product-page .query-field > .ant-select { min-width: 110px; }
|
||||
.stage-product-page .query-primary-field > .ant-select { min-width: 0; }
|
||||
@media(max-width:760px) {
|
||||
.stage-source-filter-row { grid-template-columns: minmax(0,1fr) 140px 32px; }
|
||||
.stage-source-filter-row > .ant-select:nth-of-type(2) { grid-column: 1 / 3; grid-row: 2; }
|
||||
@@ -14,4 +11,12 @@
|
||||
.stage-metric-strip { grid-template-columns: repeat(2,minmax(0,1fr)); }
|
||||
}
|
||||
|
||||
.stage-product-page .defects-panel > .defect-stage-column { padding: 14px; }
|
||||
.stage-defect-comparison { display: grid; grid-template-columns: minmax(300px,1fr) minmax(0,2fr); border-top: 1px solid var(--line); }
|
||||
.stage-defect-comparison > .defect-stage-column { padding: 0 16px 14px; }
|
||||
.stage-defect-comparison .defect-stage-title { min-height: 40px; padding: 10px 0; }
|
||||
.stage-defect-comparison > .defect-pareto-section { min-width: 0; border-top: 0; border-left: 1px solid var(--line); padding: 0 12px 10px; }
|
||||
.stage-defect-comparison .defect-pareto-chart { height: 360px; }
|
||||
@media(max-width:1000px) {
|
||||
.stage-defect-comparison { grid-template-columns: 1fr; }
|
||||
.stage-defect-comparison > .defect-pareto-section { border-left: 0; border-top: 1px solid var(--line); }
|
||||
}
|
||||
|
||||
+39
-18
@@ -15,21 +15,21 @@
|
||||
--sidebar-surface: #f8fafd;
|
||||
--sidebar: 202px;
|
||||
--mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
--ui-scale: .8;
|
||||
--viewport-height: calc(100vh / var(--ui-scale));
|
||||
--dynamic-viewport-height: calc(100dvh / var(--ui-scale));
|
||||
--small-viewport-height: calc(100svh / var(--ui-scale));
|
||||
--viewport-height: 100vh;
|
||||
--dynamic-viewport-height: 100dvh;
|
||||
--small-viewport-height: 100svh;
|
||||
--topbar-height: 53px;
|
||||
--workspace-sticky-top: var(--topbar-height);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html { zoom: var(--ui-scale); }
|
||||
@media (max-width: 760px) { :root { --ui-scale: 1; } }
|
||||
@media (max-width: 760px) { :root { --topbar-height: 40px; } }
|
||||
html, body, #root { min-width: 320px; min-height: 100%; margin: 0; }
|
||||
body { color: var(--ink); background: #f4f6fb; font-size: var(--font-body); }
|
||||
button, input, textarea, select { font: inherit; }
|
||||
button { color: inherit; }
|
||||
.app-shell { min-height: var(--viewport-height); }
|
||||
.sidebar { position: fixed; inset: 0 auto 0 0; z-index: 15; display: flex; width: var(--sidebar); flex-direction: column; padding: 16px 12px 10px; background: #f8f9fc; border-right: 1px solid var(--line); }
|
||||
.sidebar { --font-body: 14px; --font-control: 13px; position: fixed; inset: 0 auto 0 0; z-index: 15; display: flex; width: var(--sidebar); flex-direction: column; padding: 16px 12px 10px; background: #f8f9fc; border-right: 1px solid var(--line); }
|
||||
.brand { display: flex; align-items: center; gap: 8px; min-height: 34px; padding: 0 7px; border: 0; background: transparent; text-align: left; font-size: var(--font-dialog-title); font-weight: 700; cursor: pointer; white-space: nowrap; }
|
||||
.brand-mark { display: inline-flex; align-items: center; gap: 2px; width: 22px; height: 23px; transform: skew(-17deg); }
|
||||
.brand-mark i { display: block; width: 4px; height: 17px; background: var(--blue); }
|
||||
@@ -40,7 +40,7 @@ button { color: inherit; }
|
||||
.nav-group { margin-top: 12px; }
|
||||
.nav-group-label { padding: 7px 9px 6px; color: var(--ink); font-size: var(--font-control); font-weight: 650; }
|
||||
.nav-item { display: flex; width: 100%; min-height: 36px; align-items: center; gap: 10px; padding: 7px 9px; border: 0; background: transparent; text-align: left; cursor: pointer; font-size: var(--font-body); }
|
||||
.nav-item .anticon { width: 16px; color: var(--ink); font-size: var(--font-dialog-title); }
|
||||
.nav-item .anticon { width: 18px; flex: 0 0 18px; color: var(--ink); font-size: 18px; }
|
||||
.nav-item:hover { background: #eef2fb; }
|
||||
.nav-item.active { color: var(--blue-dark); background: #e3ebff; font-weight: 650; }
|
||||
.nav-item.active .anticon { color: var(--blue); }
|
||||
@@ -69,7 +69,7 @@ button { color: inherit; }
|
||||
.sidebar-collapsed .user-profile-trigger { flex: 0; }
|
||||
}
|
||||
@media (max-width: 760px) { .sidebar-toggle.ant-btn { display: none; } }
|
||||
.topbar { position: sticky; top: 0; z-index: 40; display: flex; height: 44px; align-items: center; justify-content: space-between; padding: 0 22px; background: var(--surface); border-bottom: 1px solid var(--line); }
|
||||
.topbar { position: sticky; top: 0; z-index: 40; display: flex; height: var(--topbar-height); align-items: center; justify-content: space-between; padding: 0 22px; background: var(--surface); border-bottom: 1px solid var(--line); }
|
||||
.breadcrumb { display: flex; align-items: center; gap: 10px; font-size: var(--font-control); }
|
||||
.breadcrumb strong { font-weight: 650; }
|
||||
.breadcrumb-slash { color: #63738a; }
|
||||
@@ -77,8 +77,8 @@ button { color: inherit; }
|
||||
.mobile-brand { display: none; }
|
||||
.page-content { width: 100%; min-width: 0; margin: 0; padding: 15px 20px 20px; }
|
||||
.panel { background: var(--surface); border: 1px solid var(--line); border-radius: var(--panel-radius, 5px) !important; }
|
||||
.query-page { display: flex; min-width: 0; flex-direction: column; gap: 11px; }
|
||||
.query-toolbar { position: sticky; top: 53px; z-index: 35; display: flex; min-height: 48px; flex-wrap: wrap; align-items: center; gap: 10px 13px; padding: 7px 11px; }
|
||||
.query-page { display: flex; min-width: 0; flex-direction: column; gap: 11px; overflow-anchor: none; }
|
||||
.query-toolbar { position: sticky; top: var(--workspace-sticky-top); z-index: 35; display: flex; min-height: 48px; flex-wrap: wrap; align-items: center; gap: 10px 13px; padding: 7px 11px; }
|
||||
.query-toolbar::before { content: ''; position: absolute; right: -20px; bottom: 100%; left: -20px; height: 18px; background: var(--background); pointer-events: none; }
|
||||
.query-field { display: inline-flex; min-width: 0; align-items: center; gap: 7px; }
|
||||
.query-field > span { flex: 0 0 auto; white-space: nowrap; font-size: var(--font-control); }
|
||||
@@ -155,8 +155,8 @@ button { color: inherit; }
|
||||
.trend-object .ant-select { width: min(420px, 100%); }
|
||||
.chart-viewport { width: 100%; overflow-x: auto; }
|
||||
.chart-surface { position: relative; width: 100%; min-width: 0; }
|
||||
/* Keep SVG chart coordinates aligned with pointer events under the app's global UI zoom. */
|
||||
.chart-container { width: 100%; height: calc(380px * var(--ui-scale)); min-width: 0; zoom: calc(1 / var(--ui-scale)); }
|
||||
/* 图表与页面使用同一坐标尺寸,保持 SVG 和鼠标位置一致。 */
|
||||
.chart-container { width: 100%; height: 380px; min-width: 0; }
|
||||
.chart-footnote { display: flex; justify-content: space-between; gap: 12px; padding: 0 13px 10px; font-size: var(--font-note); }
|
||||
.defects-panel { min-height: 120px; }
|
||||
.defect-stage-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); border-top: 1px solid var(--line); }
|
||||
@@ -164,7 +164,7 @@ button { color: inherit; }
|
||||
.defect-pareto-heading { display: flex; min-height: 38px; flex-wrap: wrap; align-items: baseline; gap: 5px 12px; padding: 8px 1px 0; }
|
||||
.defect-pareto-heading strong { font-size: var(--font-body); font-weight: 650; }
|
||||
.defect-pareto-heading span { color: var(--ink); font-size: var(--font-note); }
|
||||
.defect-pareto-chart { width: 100%; height: calc(470px * var(--ui-scale)); min-width: 0; zoom: calc(1 / var(--ui-scale)); }
|
||||
.defect-pareto-chart { width: 100%; height: 470px; min-width: 0; }
|
||||
.defect-pareto-status { display: flex; min-height: 52px; align-items: center; justify-content: center; gap: 8px; font-size: var(--font-control); }
|
||||
.defect-stage-column { min-width: 0; padding: 0 12px 10px; }
|
||||
.defect-stage-column + .defect-stage-column { border-left: 1px solid var(--line); }
|
||||
@@ -374,7 +374,7 @@ button { color: inherit; }
|
||||
:root { --sidebar: 0px; }
|
||||
.sidebar { display: none; }
|
||||
.main-column { margin-left: 0; }
|
||||
.topbar { height: 40px; padding: 0 12px; }
|
||||
.topbar { padding: 0 12px; }
|
||||
.top-organization { display: none; }
|
||||
.mobile-brand { display: flex; min-height: 44px; align-items: center; gap: 7px; padding: 4px 10px; background: #f8f9fc; border-bottom: 1px solid var(--line); font-size: var(--font-section); }
|
||||
.mobile-brand > strong { white-space: nowrap; }
|
||||
@@ -478,7 +478,7 @@ body { background: var(--background); }
|
||||
.nav-item:hover { background: var(--hover); }
|
||||
.nav-item.active { color: var(--blue-dark); background: var(--blue-soft); }
|
||||
.nav-item.active .anticon { color: var(--blue); }
|
||||
.topbar { height: 53px; padding: 0 20px; }
|
||||
.topbar { height: var(--topbar-height); padding: 0 20px; }
|
||||
.topbar-actions { display: flex; align-items: center; gap: 8px; }
|
||||
.topbar-search.ant-btn {
|
||||
display: inline-flex;
|
||||
@@ -559,7 +559,7 @@ body { background: var(--background); }
|
||||
.query-toolbar::before { right: -15px; left: -15px; height: 16px; }
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.topbar { height: 40px; padding: 0 12px; }
|
||||
.topbar { padding: 0 12px; }
|
||||
.topbar-actions { gap: 2px; }
|
||||
.topbar-search.ant-btn { width: 30px; justify-content: center; padding: 0; }
|
||||
.topbar-search > span:not(.anticon), .topbar-search kbd { display: none; }
|
||||
@@ -568,7 +568,7 @@ body { background: var(--background); }
|
||||
.top-organization { display: none; }
|
||||
.mobile-brand { background: var(--sidebar-surface); }
|
||||
.page-content { padding: 11px 10px 18px; }
|
||||
.query-toolbar { top: 40px; }
|
||||
.query-toolbar { top: var(--workspace-sticky-top); }
|
||||
.query-toolbar::before { right: -10px; left: -10px; height: 12px; }
|
||||
.navigation-search-modal { max-width: calc(100vw - 24px); }
|
||||
}
|
||||
@@ -633,3 +633,24 @@ body { background: var(--background); }
|
||||
}
|
||||
|
||||
.query-quality-summary { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 14px; color: var(--muted-ink); font-size: var(--font-control); margin: 0 0 14px; }
|
||||
|
||||
/* 浏览器保留前后两帧连续交接;顶部与侧栏独立固定,不进行整页位移或缩放。 */
|
||||
:root { view-transition-name: root; }
|
||||
.sidebar { view-transition-name: workspace-sidebar; }
|
||||
.topbar { view-transition-name: workspace-header; }
|
||||
::view-transition { pointer-events: none; }
|
||||
::view-transition-group(root),
|
||||
::view-transition-group(workspace-sidebar),
|
||||
::view-transition-group(workspace-header) { animation: none; }
|
||||
::view-transition-old(root) { animation: workspace-page-out 280ms cubic-bezier(.22,.61,.36,1) both; }
|
||||
::view-transition-new(root) { animation: workspace-page-in 280ms cubic-bezier(.22,.61,.36,1) both; }
|
||||
::view-transition-old(root), ::view-transition-new(root) { mix-blend-mode: plus-lighter; }
|
||||
::view-transition-old(workspace-sidebar), ::view-transition-old(workspace-header) { display: none; }
|
||||
::view-transition-new(workspace-sidebar), ::view-transition-new(workspace-header) { animation: none; }
|
||||
@keyframes workspace-page-out { to { opacity: 0; } }
|
||||
@keyframes workspace-page-in { from { opacity: 0; } }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
::view-transition-group(*) { animation: none !important; }
|
||||
::view-transition-old(root) { display: none; }
|
||||
::view-transition-new(root) { animation: none; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import {getWorkspaceTheme,type WorkspaceThemeId} from './ui-themes';
|
||||
export type BarPalette={qualified:string;scrap:string;selectedQualified:string;selectedScrap:string;hoverQualified:string;hoverScrap:string;wash:number};
|
||||
const selected:BarPalette={qualified:'#99A8E3',scrap:'#E49A70',selectedQualified:'#7F92DA',selectedScrap:'#DB8656',hoverQualified:'#6078CE',hoverScrap:'#CD7546',wash:.50};
|
||||
export const blend=(front:string,back:string,alpha:number)=>'#'+[0,2,4].map(offset=>Math.round(parseInt(front.slice(1+offset,3+offset),16)*alpha+parseInt(back.slice(1+offset,3+offset),16)*(1-alpha)).toString(16).padStart(2,'0')).join('').toUpperCase();
|
||||
/** 已确认的 01 轻度加深:沿用各主题蓝色方向及原有交互。 */
|
||||
export function trendBarPalette(themeId:WorkspaceThemeId):BarPalette {
|
||||
const p=selected,theme=getWorkspaceTheme(themeId);
|
||||
if(themeId==='light')return p;
|
||||
if(themeId==='dark'){
|
||||
const qualified='#6076A7';
|
||||
return {...p,qualified,selectedQualified:blend(qualified,'#B8C8FF',.72),hoverQualified:blend(qualified,'#CCD8FF',.60),scrap:'#E6A171',selectedScrap:blend(p.selectedScrap,'#FFD1A6',.56),hoverScrap:blend(p.hoverScrap,'#FFCC9A',.54)};
|
||||
}
|
||||
return {...p,qualified:blend(theme.muted,theme.primary,.76),selectedQualified:blend(theme.muted,theme.primary,.50),hoverQualified:blend(theme.primary,'#263451',.94)};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { PeriodKind } from './types';
|
||||
|
||||
type PeriodSelection = { period: PeriodKind; year: number; month: number; quarter: number };
|
||||
|
||||
export function selectTrendPeriod(value: number | string, current: PeriodSelection): PeriodSelection {
|
||||
const raw = String(value);
|
||||
const quarterly = raw.match(/^(\d{4})-Q([1-4])$/);
|
||||
const monthly = raw.match(/^(\d{4})-(\d{1,2})$/);
|
||||
if (quarterly) {
|
||||
const year = Number(quarterly[1]), quarter = Number(quarterly[2]);
|
||||
return { ...current, year, quarter, period: current.period === 'quarter' && current.year === year && current.quarter === quarter ? 'year' : 'quarter' };
|
||||
}
|
||||
if (monthly) {
|
||||
const year = Number(monthly[1]), month = Number(monthly[2]);
|
||||
if (month < 1 || month > 12) return current;
|
||||
return { ...current, year, month, period: current.period === 'month' && current.year === year && current.month === month ? 'year' : 'month' };
|
||||
}
|
||||
if (/^\d{4}$/.test(raw)) return { ...current, year: Number(raw), period: 'year' };
|
||||
const month = Number(raw.match(/\d{1,2}/)?.[0]);
|
||||
return Number.isInteger(month) && month >= 1 && month <= 12
|
||||
? { ...current, month, period: current.period === 'month' && current.month === month ? 'year' : 'month' }
|
||||
: current;
|
||||
}
|
||||
@@ -107,6 +107,14 @@ export interface MetricsResponse {
|
||||
coverage: CoverageSummary;
|
||||
}
|
||||
|
||||
/** 趋势专用响应,不包含汇总表的产品行。 */
|
||||
export interface TrendResponse {
|
||||
release: MetricsResponse['release'];
|
||||
context: Record<string, unknown>;
|
||||
trend: TrendMetricRow[];
|
||||
coverage: CoverageSummary;
|
||||
}
|
||||
|
||||
export interface CoverageSummary {
|
||||
rawRows: number;
|
||||
includedRows: number;
|
||||
@@ -125,6 +133,8 @@ export interface ReleaseOption {
|
||||
|
||||
export interface OptionsResponse {
|
||||
years: (number | string)[];
|
||||
periods?: string[];
|
||||
latestDataPeriod?: { year?: number; month?: number };
|
||||
departments: string[];
|
||||
groups: string[];
|
||||
groupDepartments?: Record<string, string | null>;
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
|
||||
body, button, input, textarea, select { font-family: var(--font-ui); }
|
||||
|
||||
/* 查询区在既有缩放下保留可读正文,避免指标与明细的字号反差过大。 */
|
||||
/* 查询区保留统一的可读正文,避免指标与明细的字号反差过大。 */
|
||||
.query-page {
|
||||
--font-control: 13px;
|
||||
--font-table: 13px;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { api } from './api';
|
||||
import { WORKSPACE_INVALIDATED } from './pageCache';
|
||||
import { WORKSPACE_INVALIDATED, usePageCache } from './pageCache';
|
||||
import type { DataWorkflowOperation } from './NoCodeDataTypes';
|
||||
import { useVisiblePolling } from './useVisiblePolling';
|
||||
|
||||
type StoredOperation = { operationId: string; startedAt: string };
|
||||
const storageKey = (slot: string) => `quality-data-workflow:${slot}`;
|
||||
const isPending = (value: DataWorkflowOperation | null) => value && ['QUEUED', 'RUNNING'].includes(String(value.status).toUpperCase());
|
||||
const delay = (ms: number) => new Promise(resolve => window.setTimeout(resolve, ms));
|
||||
|
||||
export function operationError(value: DataWorkflowOperation | null): string {
|
||||
const errors = Array.isArray(value?.errors) ? value.errors : [];
|
||||
@@ -14,14 +14,25 @@ export function operationError(value: DataWorkflowOperation | null): string {
|
||||
}
|
||||
|
||||
export function useDataWorkflowOperation(slot: string, onComplete?: (value: DataWorkflowOperation) => void) {
|
||||
const { active } = usePageCache();
|
||||
const [operation, setOperation] = useState<DataWorkflowOperation | null>(null);
|
||||
const [operationId, setOperationId] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [pollRevision, setPollRevision] = useState(0);
|
||||
const [starting, setStarting] = useState(false);
|
||||
const callbackRef = useRef(onComplete);
|
||||
const activeRef = useRef(0);
|
||||
const startPromiseRef = useRef<Promise<DataWorkflowOperation> | null>(null);
|
||||
const pollRequestRef = useRef<Promise<void> | null>(null);
|
||||
const terminalHandledRef = useRef(new Set<string>());
|
||||
const generationRef = useRef(0);
|
||||
const mountedRef = useRef(false);
|
||||
useEffect(() => { callbackRef.current = onComplete; }, [onComplete]);
|
||||
useEffect(() => {
|
||||
mountedRef.current = true;
|
||||
let pending: StoredOperation | null = null;
|
||||
try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; }
|
||||
if (pending?.operationId) setOperationId(pending.operationId);
|
||||
return () => { mountedRef.current = false; generationRef.current++; };
|
||||
}, [slot]);
|
||||
|
||||
const savePendingId = useCallback((value: StoredOperation | null) => {
|
||||
try {
|
||||
@@ -30,35 +41,36 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
|
||||
} catch { /* storage may be unavailable in a restricted browser context */ }
|
||||
}, [slot]);
|
||||
|
||||
const poll = useCallback(async (operationId: string) => {
|
||||
const runId = ++activeRef.current;
|
||||
setError('');
|
||||
while (activeRef.current === runId) {
|
||||
const poll = useCallback((id: string) => {
|
||||
if (!id || terminalHandledRef.current.has(id) || pollRequestRef.current) return pollRequestRef.current || Promise.resolve();
|
||||
const generation = generationRef.current;
|
||||
const attempt = (async () => {
|
||||
try {
|
||||
const current = await api.dataWorkflowOperation(operationId);
|
||||
if (activeRef.current !== runId) return;
|
||||
const current = await api.dataWorkflowOperation(id);
|
||||
if (!mountedRef.current || generation !== generationRef.current) return;
|
||||
setOperation(current);
|
||||
setError('');
|
||||
const status = String(current.status || '').toUpperCase();
|
||||
if (status === 'COMPLETED' || status === 'FAILED') {
|
||||
if (status === 'COMPLETED') { savePendingId(null); window.dispatchEvent(new Event(WORKSPACE_INVALIDATED)); callbackRef.current?.(current); }
|
||||
else setError(operationError(current));
|
||||
return;
|
||||
terminalHandledRef.current.add(id);
|
||||
generationRef.current++;
|
||||
setOperationId('');
|
||||
if (status === 'COMPLETED') {
|
||||
savePendingId(null);
|
||||
window.dispatchEvent(new CustomEvent(WORKSPACE_INVALIDATED, { detail: { resources: ['sources', 'workflow', 'tasks', 'releases', 'metrics', 'trend', 'records', 'options', 'catalog', 'configuration'] } }));
|
||||
callbackRef.current?.(current);
|
||||
} else setError(operationError(current));
|
||||
}
|
||||
} catch (value) {
|
||||
if (activeRef.current !== runId) return;
|
||||
if (!mountedRef.current || generation !== generationRef.current) return;
|
||||
setError(value instanceof Error ? value.message : '处理进度读取失败');
|
||||
return;
|
||||
}
|
||||
await delay(900);
|
||||
}
|
||||
})().finally(() => { if (pollRequestRef.current === attempt) pollRequestRef.current = null; });
|
||||
pollRequestRef.current = attempt;
|
||||
return attempt;
|
||||
}, [savePendingId]);
|
||||
|
||||
useEffect(() => {
|
||||
let pending: StoredOperation | null = null;
|
||||
try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; }
|
||||
if (pending?.operationId) void poll(pending.operationId);
|
||||
return () => { activeRef.current++; };
|
||||
}, [poll, slot, pollRevision]);
|
||||
useVisiblePolling(() => poll(operationId), 2000, active && Boolean(operationId), true);
|
||||
|
||||
const start = useCallback(async (create: () => Promise<DataWorkflowOperation>) => {
|
||||
if (startPromiseRef.current) return startPromiseRef.current;
|
||||
@@ -69,9 +81,11 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
|
||||
try {
|
||||
const started = await create();
|
||||
if (!started?.operationId) throw new Error('服务端未返回操作编号');
|
||||
generationRef.current++;
|
||||
setOperation(started);
|
||||
terminalHandledRef.current.delete(started.operationId);
|
||||
setOperationId(started.operationId);
|
||||
savePendingId({ operationId: started.operationId, startedAt: new Date().toISOString() });
|
||||
void poll(started.operationId);
|
||||
return started;
|
||||
} catch (value) {
|
||||
setError(value instanceof Error ? value.message : '操作未能开始');
|
||||
@@ -83,18 +97,19 @@ export function useDataWorkflowOperation(slot: string, onComplete?: (value: Data
|
||||
})();
|
||||
startPromiseRef.current = attempt;
|
||||
return attempt;
|
||||
}, [operation, poll, savePendingId]);
|
||||
}, [operation, savePendingId]);
|
||||
|
||||
const resume = useCallback(() => {
|
||||
if (operation?.operationId) void poll(operation.operationId);
|
||||
else {
|
||||
let pending: StoredOperation | null = null;
|
||||
try { pending = JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null; } catch { pending = null; }
|
||||
if (pending?.operationId) void poll(pending.operationId);
|
||||
else setPollRevision(value => value + 1);
|
||||
}
|
||||
const id = operation?.operationId || (() => {
|
||||
try { return (JSON.parse(localStorage.getItem(storageKey(slot)) || 'null') as StoredOperation | null)?.operationId || ''; }
|
||||
catch { return ''; }
|
||||
})();
|
||||
if (id) { setError(''); setOperationId(id); void poll(id); }
|
||||
}, [operation?.operationId, poll, slot]);
|
||||
|
||||
const clear = useCallback(() => { activeRef.current++; setOperation(null); setError(''); savePendingId(null); }, [savePendingId]);
|
||||
const clear = useCallback(() => {
|
||||
generationRef.current++;
|
||||
setOperation(null); setOperationId(''); setError(''); savePendingId(null);
|
||||
}, [savePendingId]);
|
||||
return { operation, error, busy: starting || Boolean(isPending(operation)), start, resume, clear };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
/** Shows a loading indicator only when the request has lasted beyond the delay. */
|
||||
export function useDelayedIndicator(active: boolean, delayMs = 150): boolean {
|
||||
const [visible, setVisible] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!active) { setVisible(false); return; }
|
||||
setVisible(false);
|
||||
const timer = window.setTimeout(() => setVisible(true), delayMs);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [active, delayMs]);
|
||||
return active && visible;
|
||||
}
|
||||
|
||||
/** Wraps reads with a delayed, concurrency-safe busy indicator. */
|
||||
export function useDelayedBusy(delayMs = 150) {
|
||||
const [pendingCount, setPendingCount] = useState(0);
|
||||
const busy = useDelayedIndicator(pendingCount > 0, delayMs);
|
||||
const mounted = useRef(false);
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => { mounted.current = false; };
|
||||
}, []);
|
||||
const run = useCallback(async <T,>(work: () => Promise<T>): Promise<T> => {
|
||||
setPendingCount(count => count + 1);
|
||||
try { return await work(); }
|
||||
finally { if (mounted.current) setPendingCount(count => Math.max(0, count - 1)); }
|
||||
}, []);
|
||||
return { busy, run };
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useEffect, useState, type RefObject } from 'react';
|
||||
|
||||
/** 低频图表接近视口后才读取,页面隐藏时不发起请求。 */
|
||||
export function useResourceVisibility(ref: RefObject<HTMLElement | null>, active: boolean): boolean {
|
||||
const [seen, setSeen] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!active || seen) return;
|
||||
const node = ref.current;
|
||||
if (!node) return;
|
||||
if (typeof IntersectionObserver === 'undefined') { setSeen(true); return; }
|
||||
const observer = new IntersectionObserver(entries => {
|
||||
if (entries.some(entry => entry.isIntersecting)) { setSeen(true); observer.disconnect(); }
|
||||
}, { rootMargin: '240px' });
|
||||
observer.observe(node);
|
||||
return () => observer.disconnect();
|
||||
}, [ref, active, seen]);
|
||||
return active && seen;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { createVisiblePollingController } from './visiblePollingController';
|
||||
|
||||
/** Polls serially while the owning page is active and the browser tab is visible. */
|
||||
export function useVisiblePolling(callback: () => void | Promise<void>, intervalMs: number, enabled: boolean, immediateOnEnable = false) {
|
||||
const callbackRef = useRef(callback);
|
||||
callbackRef.current = callback;
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const controller = createVisiblePollingController(() => callbackRef.current(), intervalMs);
|
||||
const syncVisibility = () => controller.setVisible(document.visibilityState === 'visible');
|
||||
controller.start(document.visibilityState === 'visible', immediateOnEnable);
|
||||
document.addEventListener('visibilitychange', syncVisibility);
|
||||
return () => {
|
||||
document.removeEventListener('visibilitychange', syncVisibility);
|
||||
controller.stop();
|
||||
};
|
||||
}, [enabled, intervalMs, immediateOnEnable]);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
export type PollScheduler = {
|
||||
setTimeout: (callback: () => void, delayMs: number) => unknown;
|
||||
clearTimeout: (handle: unknown) => void;
|
||||
};
|
||||
|
||||
export type VisiblePollingController = {
|
||||
start: (visible: boolean, runImmediately?: boolean) => void;
|
||||
setVisible: (visible: boolean) => void;
|
||||
stop: () => void;
|
||||
};
|
||||
|
||||
/** Runs one request at a time and starts the next delay only after it settles. */
|
||||
export function createVisiblePollingController(
|
||||
callback: () => void | Promise<void>,
|
||||
intervalMs: number,
|
||||
scheduler: PollScheduler = {
|
||||
setTimeout: (run, delay) => window.setTimeout(run, delay),
|
||||
clearTimeout: handle => window.clearTimeout(handle as number),
|
||||
},
|
||||
): VisiblePollingController {
|
||||
let enabled = false;
|
||||
let visible = false;
|
||||
let inFlight = false;
|
||||
let runImmediatelyAfterFlight = false;
|
||||
let timer: unknown = null;
|
||||
|
||||
const clear = () => {
|
||||
if (timer !== null) scheduler.clearTimeout(timer);
|
||||
timer = null;
|
||||
};
|
||||
const schedule = () => {
|
||||
if (!enabled || !visible || inFlight || timer !== null) return;
|
||||
timer = scheduler.setTimeout(() => {
|
||||
timer = null;
|
||||
void run();
|
||||
}, intervalMs);
|
||||
};
|
||||
const run = async () => {
|
||||
if (!enabled || !visible) return;
|
||||
if (inFlight) {
|
||||
runImmediatelyAfterFlight = true;
|
||||
return;
|
||||
}
|
||||
clear();
|
||||
inFlight = true;
|
||||
try { await callback(); } catch { /* Polling errors are rendered by the caller. */ }
|
||||
finally {
|
||||
inFlight = false;
|
||||
if (!enabled || !visible) return;
|
||||
if (runImmediatelyAfterFlight) {
|
||||
runImmediatelyAfterFlight = false;
|
||||
void run();
|
||||
} else schedule();
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
start(nextVisible, runImmediately = false) {
|
||||
enabled = true;
|
||||
visible = nextVisible;
|
||||
if (visible) runImmediately ? void run() : schedule();
|
||||
},
|
||||
setVisible(nextVisible) {
|
||||
if (visible === nextVisible) return;
|
||||
visible = nextVisible;
|
||||
if (!enabled) return;
|
||||
if (!visible) clear();
|
||||
else void run();
|
||||
},
|
||||
stop() {
|
||||
enabled = false;
|
||||
runImmediatelyAfterFlight = false;
|
||||
clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -37,6 +37,13 @@ body, .app-shell, .main-column { color: var(--ink); background: var(--background
|
||||
.ant-segmented .ant-segmented-item-selected { color: var(--blue-dark); background: var(--blue-soft); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--blue) 22%, transparent); }
|
||||
.ant-segmented .ant-segmented-item, .ant-segmented .ant-segmented-thumb { border-radius: calc(var(--control-radius) - 1px); }
|
||||
.ant-btn-primary { box-shadow: 0 1px 2px #101b3010; }
|
||||
.table-tools :is(.query-return-button, .query-export-button) { font-weight: 600; }
|
||||
.table-tools .query-return-button:not(:disabled) {
|
||||
border-color: var(--blue);
|
||||
color: var(--blue-dark);
|
||||
background: var(--blue-soft);
|
||||
}
|
||||
.table-tools .query-return-button:not(:disabled):hover { background: var(--hover); }
|
||||
.ant-btn:focus-visible, .nav-item:focus-visible, .metric-card:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; }
|
||||
.workspace-theme-dropdown .ant-dropdown-menu { border-radius: var(--panel-radius); }
|
||||
.workspace-theme-dropdown .ant-dropdown-menu-item { border-radius: calc(var(--control-radius) - 1px); }
|
||||
@@ -92,12 +99,13 @@ body, .app-shell, .main-column { color: var(--ink); background: var(--background
|
||||
z-index: 1;
|
||||
}
|
||||
.query-page .metric-strip > .metric-card {
|
||||
min-height: 84px;
|
||||
min-height: 96px;
|
||||
padding: 8px 13px;
|
||||
gap: 3px;
|
||||
}
|
||||
.query-page .metric-strip:has(> .rate-basis-control) > .metric-card:last-child .metric-label { padding-right: 140px; }
|
||||
@media (max-width: 760px) {
|
||||
.query-page .metric-strip > .metric-card { min-height: 84px; }
|
||||
.query-page .metric-strip > .rate-basis-control { position: static; padding: 0 8px; }
|
||||
.query-page .metric-strip:has(> .rate-basis-control) > .metric-card:last-child .metric-label { padding-right: 0; }
|
||||
}
|
||||
@@ -106,19 +114,19 @@ body, .app-shell, .main-column { color: var(--ink); background: var(--background
|
||||
.mapping-issue-filters .ant-select { min-width: 180px; flex: 0 1 240px; }
|
||||
|
||||
/* Retained maintenance sections share a compact, sticky navigation bar. */
|
||||
.management-sections > .ant-tabs-nav { position: sticky; top: 53px; z-index: 34; margin: 0 0 12px; padding: 0 16px; background: var(--surface); border: 1px solid var(--line); }
|
||||
.management-sections > .ant-tabs-nav { position: sticky; top: var(--workspace-sticky-top); z-index: 34; margin: 0 0 12px; padding: 0 16px; background: var(--surface); border: 1px solid var(--line); }
|
||||
.management-sections > .ant-tabs-body-holder > .ant-tabs-body > .ant-tabs-content { padding: 12px; background: var(--surface); border: 1px solid var(--line); }
|
||||
.management-sections .management-page { gap: 10px; }
|
||||
.management-module-actions { display: flex; justify-content: flex-end; margin: 0; padding: 0 0 6px; }
|
||||
.management-module-actions .page-heading-actions { margin: 0; }
|
||||
.management-sections .nc-simple-config-tabs > .ant-tabs-nav { position: sticky; top: 100px; z-index: 33; background: var(--surface); }
|
||||
@media (max-width: 760px) { .management-sections > .ant-tabs-nav { top: 40px; } .management-sections .nc-simple-config-tabs > .ant-tabs-nav { top: 87px; } }
|
||||
.management-sections .nc-simple-config-tabs > .ant-tabs-nav { position: sticky; top: calc(var(--workspace-sticky-top) + 47px); z-index: 33; background: var(--surface); }
|
||||
|
||||
|
||||
.management-sections > .ant-tabs-body-holder, .management-sections > .ant-tabs-body-holder > .ant-tabs-body { overflow: visible; }
|
||||
.management-sections { overflow: visible; }
|
||||
.management-sections .management-sections > .ant-tabs-nav { top: 100px; z-index: 33; }
|
||||
.management-sections .management-sections .management-sections > .ant-tabs-nav { top: 147px; z-index: 32; }
|
||||
@media (max-width: 760px) { .management-sections .management-sections > .ant-tabs-nav { top: 87px; } .management-sections .management-sections .management-sections > .ant-tabs-nav { top: 134px; } }
|
||||
.management-sections .management-sections > .ant-tabs-nav { top: calc(var(--workspace-sticky-top) + 47px); z-index: 33; }
|
||||
.management-sections .management-sections .management-sections > .ant-tabs-nav { top: calc(var(--workspace-sticky-top) + 94px); z-index: 32; }
|
||||
|
||||
/* A clipping panel becomes a false scroll ancestor for sticky tab navigation. */
|
||||
.management-sections .panel:has(.ant-tabs-nav) { overflow: visible; }
|
||||
.management-sections .resource-toolbar > .completion-actions { margin-left: auto; }
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
type Transition = Pick<ViewTransition, 'ready' | 'finished' | 'skipTransition'>;
|
||||
type StartTransition = (update: () => Promise<void>) => Transition;
|
||||
|
||||
/** 每次导航都可打断;跳过旧动画时,旧回调也不能覆盖最后一次选择。 */
|
||||
export function createWorkspaceTransition(start?: StartTransition, reducedMotion: () => boolean = () => false, onBusy: (busy: boolean) => void = () => {}) {
|
||||
let sequence = 0;
|
||||
let running: Transition | undefined;
|
||||
let controller: AbortController | undefined;
|
||||
const cancel = () => {
|
||||
sequence++;
|
||||
controller?.abort();
|
||||
running?.skipTransition();
|
||||
running = undefined;
|
||||
onBusy(false);
|
||||
};
|
||||
return {
|
||||
cancel,
|
||||
run(update: (signal: AbortSignal) => void | Promise<void>) {
|
||||
cancel();
|
||||
const epoch = sequence;
|
||||
const request = new AbortController();
|
||||
controller = request;
|
||||
let committed = false;
|
||||
const apply = async () => {
|
||||
if (epoch !== sequence || request.signal.aborted) return;
|
||||
committed = true;
|
||||
await update(request.signal);
|
||||
};
|
||||
if (!start || reducedMotion()) { void apply(); return; }
|
||||
onBusy(true);
|
||||
try {
|
||||
const transition = start(apply);
|
||||
running = transition;
|
||||
// 重复点击、缩放及不支持的快照状态都可以正常跳过动画。
|
||||
void transition.ready.catch(() => {});
|
||||
const finish = () => { if (running === transition) { running = undefined; onBusy(false); } };
|
||||
void transition.finished.then(finish, finish);
|
||||
} catch {
|
||||
onBusy(false);
|
||||
if (!committed) void apply();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** 首次打开先准备目标内容;网络慢时有明确上限,连续导航会立即解除等待。 */
|
||||
export function waitForWorkspaceContent(getPage: () => Element | null, signal: AbortSignal, timeout = 900): Promise<void> {
|
||||
return new Promise(resolve => {
|
||||
let settled = false;
|
||||
let settleTimer: number | undefined;
|
||||
const finish = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
observer.disconnect();
|
||||
window.clearTimeout(timer);
|
||||
window.clearTimeout(settleTimer);
|
||||
signal.removeEventListener('abort', finish);
|
||||
resolve();
|
||||
};
|
||||
const isReady = () => {
|
||||
const page = getPage();
|
||||
return page && !page.querySelector('.loading-panel, .query-table-content[aria-busy="true"], .metric-strip[aria-busy="true"], .trend-chart-shell[aria-busy="true"], .defect-pareto-section[aria-busy="true"]');
|
||||
};
|
||||
const check = () => {
|
||||
if (settled) return;
|
||||
if (signal.aborted) { finish(); return; }
|
||||
if (isReady()) {
|
||||
// 留出一次提交的时间,让图表初始化及后续查询状态先就位。
|
||||
if (settleTimer == null) settleTimer = window.setTimeout(() => {
|
||||
settleTimer = undefined;
|
||||
if (isReady()) finish();
|
||||
}, 32);
|
||||
} else {
|
||||
window.clearTimeout(settleTimer);
|
||||
settleTimer = undefined;
|
||||
}
|
||||
};
|
||||
const observer = new MutationObserver(check);
|
||||
const timer = window.setTimeout(finish, timeout);
|
||||
observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['aria-busy', 'hidden'] });
|
||||
signal.addEventListener('abort', finish, { once: true });
|
||||
check();
|
||||
});
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user