Author SHA1 Message Date
lyun 7ffb5cdb9c 优化:趋势图采用轻度平滑曲线并保留柏拉图直线 2026-11-02 16:30:53 +08:00
lyun a84ee85a84 修复:普通对话沿用模型原文并保留业务前态 2026-11-02 13:37:17 +08:00
lyun b03715cb76 新增:月度数据关键和完整指标切换及分视图默认 2026-11-02 13:23:59 +08:00
lyun 1b0274974c 修复:分析会话独立加载并保持加载布局稳定 2026-11-02 12:38:40 +08:00
lyun 903fa94c00 修复:完整展示AI原文并穿插图表,统一运行反馈与变化符号 2026-11-02 12:03:37 +08:00
lyun cf8e25a30d Merge remote-tracking branch 'origin/main' into codex/unified-loading 2026-11-02 09:54:04 +08:00
lyun b711327c8e 统一全系统资源加载、轻量趋势与缓存恢复 2026-11-02 09:54:01 +08:00
lyun b73240b2db 修复:按业务字段识别导入明细页与黑片亮片阶段 2026-11-02 09:25:58 +08:00
lyun 8b8f9b7728 界面:删除侧栏品牌下方重复的分析工作台标题 2026-11-01 22:50:05 +08:00
lyun 5bcf1dee4f 同步:补齐已发布的查询面板与不良构成源码 2026-11-01 22:49:56 +08:00
lyun db5349dbde 统一黑片亮片查询状态与重置并自动应用筛选条件 2026-11-01 18:47:18 +08:00
lyun f8f289395e 调整总体合格率和产业部菜单及合格率目标名称 2026-11-01 18:40:40 +08:00
lyun 46b920f28a 统一返回上一级按钮并精简趋势图底部内容 2026-11-01 17:16:16 +08:00
lyun d0fee1544a 修复:统一阶段筛选尺寸并平滑更新钻取趋势 2026-11-01 17:01:35 +08:00
lyun 5c37b39858 修复:统一黑片亮片与其他查询页指标卡高度 2026-11-01 16:00:45 +08:00
lyun fb245f7d2e 优化:统一阶段更多筛选并放大侧栏内容 2026-11-01 15:33:59 +08:00
lyun e6ceae12f0 优化:取消内部缩放并统一图表和冻结位置 2026-11-01 15:13:23 +08:00
114 changed files with 5216 additions and 1033 deletions
+57 -1
View File
@@ -1,6 +1,17 @@
# 质量数据分析平台设计规范
更新:2026-10-30
更新:2026-11-02
- 月度趋势数据表提供“关键指标 / 完整指标”切换,完整列与主汇总表共用字段口径与顺序。黑片、亮片页面首次默认完整指标,其余四类查询首次默认关键指标;各缓存页保留用户选择,查询和重置不改写选择,不增加数据请求。
## 智能分析正文与运行反馈(2026-11-02)
- 历史正文与会话列表分别读取,指定会话链接不等待列表;只有从查询条件创建会话时才加载选项。加载提示放在对应面板内部,首次读取不得显示欢迎空状态,也不得用通用大高度加载块推移会话框和输入区;列表失败不阻止已授权正文读取。
- 原生 AI 会话及报告以模型完整原文为正文,保留段落、表格和顺序,正式查询图表穿插在相关章节后;取消二次改写和统计兜底报告替换。历史兜底报告仅在保存的模型原文可恢复时恢复,原文缺失不伪造补齐。
- 会话只显示一次最终回答,运行过程保留思考与工具步骤;运行中默认展开,可手动收起。发送立即显示等待状态和计时,收到服务器开始时间后显示运行计时和旋转图标。
- 不在会话追加范围说明、进度句、错误或“部分完成”提示;真实失败、证据缺口和完成状态仍保存在后台,恢复及重试入口保留。
- 合格率变化统一为本期减比较期:下降为负 pp,上升为正 pp。用于筛选和排序的降幅指标保持原有语义,转换仅作用于展示值;图表、数据表和导出一致。
## 已确认方向
- 保持现有导航宽度、模块顺序、筛选承载、指标横条、表格及趋势位置。(用户确认)
@@ -79,3 +90,48 @@
- 六个查询页默认月份、六主题切换、手动选择的慢加载保护、显式年月和返回时的筛选/滚动位置均已在本地验证。页面转场补充快速连续点击、取消等待及不可见控件保护验证,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),沿横轴约束曲线;查询合格率、不良率、智能分析与导出统一。柏拉图累计线保持直线,数据点、缺失断点和计算口径不变。
+2
View File
@@ -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。期间、范围、基期、发布版本要一致。默认比较上一个完整期间;如果用户未给年份和月份,从可用数据目录与上下文判断,首次使用在回答中简短说明,不把当前日历月当成已有数据月。
@@ -8,6 +8,8 @@
优先使用工具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原样,不额外添加子对象。之后的方向和深度由真实返回的线索决定。
+1 -1
View File
@@ -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();
}
@@ -415,7 +420,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 +492,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 +632,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 +688,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 +696,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 +817,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 +1693,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()&&notice.length()<=1000).distinct().limit(20).toList());
answer.put("answerQuality",safe);
}
Object count = details.get("toolCount");
@@ -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:
@@ -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"));
}
}
@@ -1134,6 +1134,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 +1239,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 +1296,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 +1312,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 +1349,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");
@@ -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); }
}
}
+5
View File
@@ -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 推断后端。保留旧哈希资源供已打开浏览器继续加载。无需数据库结构迁移,不恢复或重写业务数据。
+8 -5
View File
@@ -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:
+13 -3
View File
@@ -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.')):
+3 -3
View File
@@ -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)):
+1
View File
@@ -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、加入比较或转成原因/缺陷调查。
+77 -43
View File
@@ -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
@@ -112,6 +118,8 @@ def run_native_exploration(*, request, task, authority, actor_root, delegated, c
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 +127,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 +135,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
+19
View File
@@ -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,
+9 -3
View File
@@ -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 = {
+36
View File
@@ -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()
+313
View File
@@ -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()
+77 -51
View File
@@ -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
@@ -54,31 +63,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 +108,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 +125,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 +159,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 +174,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 +210,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 +234,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 +246,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 +321,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()
+8 -4
View File
@@ -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 }}>
+1 -1
View File
@@ -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" />}
+4 -1
View File
@@ -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>;
}
+13
View File
@@ -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>;
}
+7 -7
View File
@@ -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>
+6 -3
View File
@@ -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} />}
+4 -1
View File
@@ -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>;
+33 -16
View File
@@ -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>;
}
+6 -3
View File
@@ -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>
+1 -1
View File
@@ -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>}</>}
+61 -13
View File
@@ -1,19 +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));
@@ -23,10 +33,12 @@ 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('');
@@ -38,28 +50,47 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
() => window.matchMedia('(prefers-reduced-motion: reduce)').matches,
busy => { if (alive.current) setNavigationBusy(busy); },
);
const validate = () => {
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;
}
@@ -79,6 +110,11 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
const entry = entries.current.get(next)!;
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(() => {
@@ -86,8 +122,8 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
current.current = next; onPageChange(next); render(value => value + 1);
});
window.scrollTo(0, entry.scroll);
void validate();
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) => {
@@ -105,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; transitions.current?.cancel(); 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(() => {
@@ -121,7 +169,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
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} inert={active && navigationBusy} style={!active ? { display: 'none' } : undefined}>
<PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey, onLocationChange: search => { entry.search = search; } }}>
<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>
+115
View File
@@ -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 => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[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>;
}
+18 -10
View File
@@ -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); }} />)}
File diff suppressed because one or more lines are too long
+320 -189
View File
@@ -38,7 +38,7 @@ import {
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { CompactManagementTables, QualityTable as Table } from './QualityTable';
import { DeleteOutlined, EditOutlined, MoreOutlined, ReloadOutlined, RobotOutlined } from '@ant-design/icons';
import { DeleteOutlined, EditOutlined, MoreOutlined, ReloadOutlined, RobotOutlined, LoadingOutlined } from '@ant-design/icons';
import { ApiError, api, collectionItems, decodeQueryValueList } from './api';
import type { AuthUser, Collection, OptionsResponse, QueryParams, SourceItem, ViewKind } from './types';
import type { DataWorkflowStatus } from './NoCodeDataTypes';
@@ -50,11 +50,11 @@ import { AnalysisReportExport, NativeAnalysisReport } from './AnalysisReportExpo
import { AiMarkdown } from './AiMarkdown';
import { authorizeAnalysisSnapshot } from './analysisSnapshot';
import { AnalysisApiSettings } from './AnalysisApiSettings';
import { acceptAnalysisEvent, analysisScrollFollows, partialAnalysisNotice, partialAnswerIsOnlyProgress, type AnalysisScrollIntent } from './analysisConversationState';
import { acceptAnalysisEvent, analysisScrollFollows, analysisStreamStatus, partialAnswerIsOnlyProgress, type AnalysisScrollIntent } from './analysisConversationState';
import { AnalysisProcess } from './AnalysisProcess';
import { AnalysisMemberListPanel } from './AnalysisMemberList';
import { AnalysisRecordListPanel } from './AnalysisRecordList';
import { analysisScopeText, restoredAnalysisDraft, analysisComposerState, analysisFollowRequestReady } from './analysisScope';
import { restoredAnalysisDraft, analysisComposerState, analysisFollowRequestReady } from './analysisScope';
import { isValidAnalysisPeriodContext } from './analysisPeriodModel';
import { beginAnalysisSubmission, requestSubmissionCancellation, submissionOutcomeUnknown, type AnalysisSubmission } from './analysisSubmission';
import { activeAnalysisTurn, analysisIsRunning, beginAnalysisSelection, defaultAnalysisSession, rememberAnalysisSession, rememberPendingAnalysisSession, settledAnalysisTurn } from './analysisConversationState';
@@ -65,6 +65,9 @@ import { DataWorkflowHub, MasterWorkbookUpload, ReadableConfigDefinition, Source
import { MappingDefinitionEditor, MasterDataDefinitionEditor, MatchRulesDefinitionEditor, RuleDefinitionEditor, TechnicalDefinitionEditor, validateStructuredMappingDefinition, type ConfigDefinition } from './StructuredConfigEditors';
import { useDataWorkflowOperation } from './useDataWorkflowOperation';
import { ServiceIdentityPanel, SourceGovernancePanel, UserAccessPolicyPanel } from './GovernanceCompletion';
import { useDelayedBusy, useDelayedIndicator } from './useDelayedBusy';
import { useVisiblePolling } from './useVisiblePolling';
import { importIssuePageKey, matchesImportIssuePage } from './importLifecycleGuards';
function apiMessage(error: unknown): string {
if (error instanceof ApiError && error.status === 409) return '当前数据或配置已变化,请刷新后重新操作。';
@@ -248,9 +251,12 @@ function PageHeader({ actions }: { title: string; description?: string; actions?
}
function SourcesPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown) => boolean; user: AuthUser }) {
const { active } = usePageCache();
const [sources, setSources] = useState<SourceItem[]>([]);
const [currentReleaseId, setCurrentReleaseId] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [sourcesLoaded, setSourcesLoaded] = useState(false);
const [releaseLoaded, setReleaseLoaded] = useState(false);
const sourceRead = useDelayedBusy();
const [error, setError] = useState('');
const [maintenanceBusy, setMaintenanceBusy] = useState(false);
const [historyOpen] = useState(() => new URLSearchParams(window.location.search).get('showImportHistory') === '1');
@@ -268,64 +274,85 @@ function SourcesPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown
? { ...previous, ids: previous.ids.filter(value => value !== id) }
: previous.ids.length >= 50 ? previous : { ids: [...previous.ids, id], releaseId: previous.ids.length ? previous.releaseId : currentReleaseId });
const load = async () => {
setLoading(true);
try {
const [sourceResult, releaseResult] = await Promise.all([api.sources(), api.releases()]);
setSources(collectionItems(sourceResult)); setCurrentReleaseId(releaseResult.currentReleaseId ?? null); setError('');
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
finally { setLoading(false); }
};
useEffect(() => { void load(); }, []);
const load = useCallback(() => sourceRead.run(async () => {
const failures: string[] = [];
const [sourceResult, releaseResult] = await Promise.allSettled([api.sources(), api.releases()]);
if (sourceResult.status === 'fulfilled') { setSources(collectionItems(sourceResult.value)); setSourcesLoaded(true); }
else if (!onUnauthorized(sourceResult.reason)) failures.push(`来源清单:${apiMessage(sourceResult.reason)}`);
if (releaseResult.status === 'fulfilled') { setCurrentReleaseId(releaseResult.value.currentReleaseId ?? null); setReleaseLoaded(true); }
else if (!onUnauthorized(releaseResult.reason)) failures.push(`当前发布版本:${apiMessage(releaseResult.reason)}`);
setError(failures.join(';'));
}), [onUnauthorized, sourceRead.run]);
useEffect(() => { if (active && (!sourcesLoaded || !releaseLoaded)) void load(); }, [active, sourcesLoaded, releaseLoaded, load]);
useMaintenanceRefresh(load);
return <div className="management-page">
{error && <Alert showIcon type="error" message="来源清单读取失败" description={error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
{error && <Alert showIcon type="error" message="来源信息读取失败" description={sourcesLoaded || releaseLoaded ? `${error};已成功读取的内容仍保留。` : error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
<ManagementSections initialKey={historyOpen ? 'history' : 'intake'} items={[
{ key: 'intake', label: '数据接入', children: <DataWorkflowHub user={user} sources={sources} currentReleaseId={currentReleaseId} pendingDeletion={pendingDeletion} onDeleted={onDeleted} onBusyChange={setMaintenanceBusy} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
{ key: 'files', label: '来源文件', children: <SourceFilesPanel user={user} sources={sources} loading={loading} pendingIds={pendingDeletion.ids} maintenanceBusy={maintenanceBusy} onToggleDelete={toggleDelete} onClearDeletes={() => setPendingDeletion({ ids: [], releaseId: null })} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
{ key: 'history', label: '导入记录', children: <ImportHistoryPanel user={user} currentReleaseId={currentReleaseId} onUnauthorized={onUnauthorized} /> },
{ key: 'files', label: '来源文件', children: <SourceFilesPanel user={user} sources={sources} sourcesLoaded={sourcesLoaded} loading={sourceRead.busy} pendingIds={pendingDeletion.ids} maintenanceBusy={maintenanceBusy} onToggleDelete={toggleDelete} onClearDeletes={() => setPendingDeletion({ ids: [], releaseId: null })} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
{ key: 'history', label: '导入记录', children: <ImportHistoryPanel user={user} onUnauthorized={onUnauthorized} /> },
{ key: 'audit', label: '来源审计', children: <SourceGovernancePanel user={user} currentReleaseId={currentReleaseId} onUnauthorized={onUnauthorized} /> },
]} />
</div>;
}
function ImportHistoryPanel({ user, currentReleaseId, onUnauthorized }: { user: AuthUser; currentReleaseId: string | null; onUnauthorized: (error: unknown) => boolean }) {
function ImportHistoryPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
const { active } = usePageCache();
const [items, setItems] = useState<Record<string, unknown>[]>([]);
const [loading, setLoading] = useState(true);
const [loaded, setLoaded] = useState(false);
const read = useDelayedBusy();
const loading = read.busy;
const [error, setError] = useState('');
const load = useCallback(async () => {
try { const result = unwrapItems(await api.tasks()); setItems(result.items.filter(item => String(item.type).toUpperCase() === 'IMPORT')); setError(''); }
const load = useCallback(() => read.run(async () => {
try { const result = unwrapItems(await api.tasks()); setItems(result.items.filter(item => String(item.type).toUpperCase() === 'IMPORT')); setLoaded(true); setError(''); }
catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
finally { setLoading(false); }
}, [onUnauthorized]);
useEffect(() => { void load(); }, [load, currentReleaseId]);
useEffect(() => { if (active && items.some(item => ['QUEUED', 'RUNNING'].includes(String(item.status).toUpperCase()))) { const timer = window.setTimeout(() => void load(), 2000); return () => window.clearTimeout(timer); } }, [items, load, active]);
return <section className="panel section-panel"><div className="resource-toolbar"><strong>导入记录</strong><span>{items.length} 条 · 可查看处理结果和逐行校验问题</span></div>
{error && <Alert showIcon type="error" message="导入记录读取失败" description={error} action={<Button onClick={() => void load()}>重试</Button>} />}
{loading ? <Spin /> : <TaskTable items={items} importOnly user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
}), [onUnauthorized, read.run]);
useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]);
useVisiblePolling(load, 2000, active && items.some(item => ['QUEUED', 'RUNNING'].includes(String(item.status).toUpperCase())));
useMaintenanceRefresh(load);
return <section className="panel section-panel"><div className="resource-toolbar"><strong>导入记录</strong><span>{items.length} 条 · 可查看处理结果和逐行校验问题</span><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新</Button></div>
{error && <Alert showIcon type="error" message="导入记录读取失败" description={loaded ? `${error};以下为上次成功读取的结果。` : error} action={<Button onClick={() => void load()}>重试</Button>} />}
{loading && !loaded ? <Spin /> : loaded && <TaskTable items={items} importOnly user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
</section>;
}
function ImportIssuesDrawer({ runId, onClose, onUnauthorized }: { runId: string; onClose: () => void; onUnauthorized: (error: unknown) => boolean }) {
const { active } = usePageCache();
const [result, setResult] = useState<Collection | null>(null);
const [loading, setLoading] = useState(false);
const [loadedRunId, setLoadedRunId] = useState('');
const [loadedPage, setLoadedPage] = useState(0);
const read = useDelayedBusy();
const loading = read.busy;
const [error, setError] = useState('');
const [page, setPage] = useState(1);
const activeRef = useRef(active); activeRef.current = active;
const requestGeneration = useRef(0);
const requestRef = useRef<{ key: string; promise: Promise<void> } | null>(null);
const load = useCallback(() => {
if (!active || !runId) return Promise.resolve();
const key = importIssuePageKey(runId, page);
if (requestRef.current?.key === key) return requestRef.current.promise;
const generation = ++requestGeneration.current;
const promise = read.run(async () => {
try {
const value = await api.importIssues(runId, page, TABLE_PAGE_SIZE);
if (generation !== requestGeneration.current || !activeRef.current) return;
setResult(value); setLoadedRunId(runId); setLoadedPage(page); setError('');
} catch (value) { if (generation === requestGeneration.current && activeRef.current && !onUnauthorized(value)) setError(apiMessage(value)); }
}).finally(() => { if (requestRef.current?.promise === promise) requestRef.current = null; });
requestRef.current = { key, promise };
return promise;
}, [active, onUnauthorized, page, read.run, runId]);
useEffect(() => {
if (!runId) return;
let alive = true;
setLoading(true);
api.importIssues(runId, page, TABLE_PAGE_SIZE).then(value => { if (alive) { setResult(value); setError(''); } })
.catch(value => { if (alive && !onUnauthorized(value)) setError(apiMessage(value)); })
.finally(() => { if (alive) setLoading(false); });
return () => { alive = false; };
}, [runId, page, onUnauthorized]);
const items = unwrapItems(result).items;
if (active && runId && (loadedRunId !== runId || loadedPage !== page)) void load();
}, [active, loadedPage, loadedRunId, load, page, runId]);
const items = loadedRunId === runId ? unwrapItems(result).items : [];
const hasSameRunResult = loadedRunId === runId && loadedPage > 0;
const pageMatches = hasSameRunResult && matchesImportIssuePage(loadedRunId, loadedPage, runId, page);
return <Drawer className="management-drawer" open={Boolean(runId)} title="导入校验问题" width={Math.min(900, window.innerWidth)} onClose={onClose}>
{error && <Alert showIcon type="error" message="问题清单读取失败" description={error} />}
{loading ? <div className="loading-panel"><Spin />正在读取问题行…</div> : <DynamicTable items={items} paginate={false} indexOffset={(page - 1) * TABLE_PAGE_SIZE} />}
{result?.total && result.total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={result.total} showTotal={count => `共 ${count} 条问题`} onChange={setPage} />}
{error && <Alert showIcon type="error" message="问题清单读取失败" description={pageMatches ? `${error};第 ${page} 页的上次成功结果仍保留。` : hasSameRunResult ? `${error};以下仍显示第 ${loadedPage} 页上次成功结果。` : error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
{loading && !hasSameRunResult ? <div className="loading-panel"><Spin />正在读取问题行…</div> : hasSameRunResult ? <><DynamicTable items={items} paginate={false} indexOffset={(loadedPage - 1) * TABLE_PAGE_SIZE} />{!pageMatches && loading && <div className="completion-note"><Spin size="small" /> 正在读取第 {page} 页,暂时保留第 {loadedPage} 页结果。</div>}</> : null}
{hasSameRunResult && result?.total && result.total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={pageMatches ? page : loadedPage} pageSize={TABLE_PAGE_SIZE} total={result.total} showTotal={count => `共 ${count} 条问题`} onChange={setPage} />}
</Drawer>;
}
@@ -333,27 +360,30 @@ function ReadOnlyResourcePage({ endpoint, title, subtitle, user, onUnauthorized
endpoint: 'imports' | 'tasks'; title: string; subtitle: string; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate?: () => void;
}) {
const [items, setItems] = useState<Record<string, unknown>[]>([]);
const [loading, setLoading] = useState(true);
const { active } = usePageCache();
const [loaded, setLoaded] = useState(false);
const read = useDelayedBusy();
const loading = read.busy;
const [error, setError] = useState('');
const [metadata, setMetadata] = useState<{ total?: number; page?: number; pageSize?: number }>({});
const load = async () => {
setLoading(true);
const load = useCallback(() => read.run(async () => {
try {
const result = await api.tasks();
const normalized = unwrapItems(result);
setItems(endpoint === 'imports' ? normalized.items.filter(item => String(item.type).toUpperCase() === 'IMPORT') : normalized.items);
setMetadata({ total: normalized.total, page: normalized.page, pageSize: normalized.pageSize });
setError('');
setError(''); setLoaded(true);
} catch (value) {
if (!onUnauthorized(value)) setError(apiMessage(value));
} finally { setLoading(false); }
};
useEffect(() => { void load(); }, [endpoint]);
}
}), [endpoint, onUnauthorized, read.run]);
useEffect(() => { if (active && !loaded) void load(); }, [active, endpoint, loaded, load]);
useVisiblePolling(load, endpoint === 'imports' ? 2000 : 15000, active && loaded && items.some(item => ['QUEUED', 'RUNNING'].includes(String(item.status || '').toUpperCase())));
return <div className="management-page">
<PageHeader title={title} description={subtitle} actions={<Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>} />
{error && <Alert type="error" showIcon message="列表读取失败" description={error} />}
<PageHeader title={title} description={subtitle} actions={<Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新</Button>} />
{error && <Alert type="error" showIcon message="列表读取失败" description={loaded ? `${error};以下为上次成功读取的结果。` : error} action={!loaded ? <Button onClick={() => void load()}>重试</Button> : undefined} />}
<section className="panel section-panel"><div className="resource-toolbar"><strong>{title}</strong><span>{metadata.total !== undefined ? `共 ${metadata.total} 条` : `服务端返回 ${items.length} 条`}</span></div>
{loading ? <div className="loading-panel"><Spin />正在读取…</div> : <TaskTable items={items} importOnly={endpoint === 'imports'} user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
{loading && !loaded ? <div className="loading-panel"><Spin />正在读取…</div> : loaded && <TaskTable items={items} importOnly={endpoint === 'imports'} user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
</section>
</div>;
}
@@ -373,10 +403,14 @@ type PublishedConfigNames = Pick<OptionsResponse, 'departments' | 'groups' | 'pr
function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSections }: { extraSections?: { key: string; label: string; children: React.ReactNode }[]; kind: 'rules' | 'mappings' | 'masterData'; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate: (page: PageKey) => void }) {
const { message } = App.useApp();
const { active: pageActive } = usePageCache();
const [items, setItems] = useState<Record<string, unknown>[]>([]);
const [loading, setLoading] = useState(true);
const [itemsLoaded, setItemsLoaded] = useState(false);
const itemRead = useDelayedBusy();
const loading = itemRead.busy;
const [error, setError] = useState('');
const [busyId, setBusyId] = useState('');
const actionLock = useRef(false);
const [drafting, setDrafting] = useState<Record<string, unknown> | null>(null);
const [validation, setValidation] = useState<{ id: string; value: unknown; purpose?: 'definition' } | null>(null);
const [impactOpen, setImpactOpen] = useState(false);
@@ -399,6 +433,9 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
const [differenceConfirmed, setDifferenceConfirmed] = useState(false);
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
const [workflowStatusError, setWorkflowStatusError] = useState('');
const statusRead = useDelayedBusy();
const supportRequested = useRef(false);
const isRules = kind === 'rules';
const title = isRules ? '计算规则' : kind === 'masterData' ? '基础数据' : '对应关系';
const testMode = workflowStatus?.simplified === true && workflowStatus.mode === 'TEST';
@@ -410,31 +447,37 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
? { ...items.find(item => String(item.id || '') === String(workflowStatus.activeMapping?.id || '')), ...workflowStatus.activeMapping }
: items.find(item => String(item.status).toUpperCase() === 'ACTIVE');
const load = async (silent = false) => {
if(!silent)setLoading(true);
try {
const result = isRules ? await api.rules() : await api.mappings();
setItems(collectionItems(result)); setError('');
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
finally { setLoading(false); }
};
const loadEditorSupport = async () => {
const load = useCallback((silent = false) => {
const read = async () => {
try {
const result = isRules ? await api.rules() : await api.mappings();
setItems(collectionItems(result)); setItemsLoaded(true); setError('');
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
};
return silent ? read() : itemRead.run(read);
}, [isRules, itemRead.run, onUnauthorized]);
const loadEditorSupport = useCallback(async () => {
try {
if (isRules) { setRuleSchema(await api.ruleSchema()); setRuleSchemaError(''); }
else {const [names,metadata]=await Promise.all([api.referenceNames(),api.classificationMetadata()]);setPublishedNames(names);setMatchMetadata(metadata);}
else {
const [names, metadata] = await Promise.allSettled([api.referenceNames(), api.classificationMetadata()]);
if (names.status === 'fulfilled') setPublishedNames(names.value);
if (metadata.status === 'fulfilled') setMatchMetadata(metadata.value);
const errors = [names, metadata].flatMap((result, index) => result.status === 'rejected' && !onUnauthorized(result.reason) ? [`${index === 0 ? '发布名录' : '对应关系元数据'}:${apiMessage(result.reason)}`] : []);
if (errors.length) setError(errors.join(';'));
}
} catch (value) { if (!onUnauthorized(value)) { if (isRules) setRuleSchemaError(apiMessage(value)); else setError(`当前发布名录读取失败:${apiMessage(value)}`); } }
};
const refreshWorkflowStatus = async () => {
try { setWorkflowStatus(await api.dataWorkflowStatus()); }
catch { setWorkflowStatus(null); }
finally { setWorkflowStatusLoaded(true); }
};
}, [isRules, onUnauthorized]);
const refreshWorkflowStatus = useCallback(() => statusRead.run(async () => {
try { setWorkflowStatus(await api.dataWorkflowStatus()); setWorkflowStatusLoaded(true); setWorkflowStatusError(''); }
catch (value) { if (!onUnauthorized(value)) setWorkflowStatusError(apiMessage(value)); }
}), [onUnauthorized, statusRead.run]);
const workflowOperation = useDataWorkflowOperation(isRules ? 'apply-rule' : 'apply-mapping', () => {
void load(); void refreshWorkflowStatus();
});
useEffect(() => { void load(); }, [kind]);
useEffect(() => { void loadEditorSupport(); }, [isRules]);
useEffect(() => { void refreshWorkflowStatus(); }, [kind]);
useEffect(() => { if (pageActive && !itemsLoaded) void load(); }, [pageActive, itemsLoaded, load]);
useEffect(() => { if (pageActive && !supportRequested.current) { supportRequested.current = true; void loadEditorSupport(); } }, [pageActive, loadEditorSupport]);
useEffect(() => { if (pageActive && !workflowStatusLoaded && !workflowStatusError) void refreshWorkflowStatus(); }, [pageActive, workflowStatusLoaded, workflowStatusError, refreshWorkflowStatus]);
useEffect(() => {
if (!workflowStatus) return;
const active = (isRules ? workflowStatus.activeRule : workflowStatus.activeMapping) as { id?: string; name?: string; description?: string; definition?: Record<string, unknown> } | null | undefined;
@@ -445,8 +488,8 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
const definitionKey=JSON.stringify([kind,active?.id??fallback?.id,definition]);
if (definition && typeof definition === 'object' && loadedDefinitionKey.current!==definitionKey) {loadedDefinitionKey.current=definitionKey;const serialized=JSON.stringify(definition),prior=loadedDefinition.current;setDraftDefinition(previous=>!prior||JSON.stringify(previous)===prior?JSON.parse(serialized) as ConfigDefinition:previous);loadedDefinition.current=serialized;}
const metadata = items.find(row => String(row.id) === String(active?.id)) ?? fallback;
form.setFieldsValue({ name: testMode ? currentConfigurationName(active?.name ?? metadata?.name, metadata?.createdAt) : isRules ? ruleDisplayName(active?.name || fallback?.name || '测试计算规则') : String(active?.name || fallback?.name || '测试基础数据与对应关系'), description: isRules ? readableRuleDescription(active?.description || fallback?.description) : String(active?.description || fallback?.description || '') });
}, [workflowStatus, items, kind, isRules, testMode, ruleSchema]);
if (!drafting) form.setFieldsValue({ name: testMode ? currentConfigurationName(active?.name ?? metadata?.name, metadata?.createdAt) : isRules ? ruleDisplayName(active?.name || fallback?.name || '测试计算规则') : String(active?.name || fallback?.name || '测试基础数据与对应关系'), description: isRules ? readableRuleDescription(active?.description || fallback?.description) : String(active?.description || fallback?.description || '') });
}, [workflowStatus, items, kind, isRules, testMode, ruleSchema, drafting, form]);
const openRegression = async (item: Record<string, unknown>, preferredRunId?: string) => {
if (!isRules) return;
@@ -486,6 +529,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
};
const saveDraft = async () => {
if (actionLock.current) return; actionLock.current = true;
try {
const values = await form.validateFields();
const body: Record<string, unknown> = { name: values.name.trim(), definition: isRules ? draftDefinition : { ...draftDefinition, maintenanceNote: values.description?.trim() || '' } };
@@ -504,11 +548,11 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
if (value && typeof value === 'object' && 'errorFields' in value) return;
if (!onUnauthorized(value)) message.error(apiMessage(value));
if (value instanceof ApiError && value.status === 409) await load();
} finally { setBusyId(''); }
} finally { actionLock.current = false; setBusyId(''); }
};
const runAction = async (item: Record<string, unknown>, action: 'validate' | 'activate', confirmDifferences = false) => {
const id = String(item.id || ''); if (!id) return;
const id = String(item.id || ''); if (!id || actionLock.current) return; actionLock.current = true;
setBusyId(id);
try {
const result = isRules
@@ -522,7 +566,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
if (action === 'activate') setDifferenceItem(null);
await load();
} catch (value) { if (!onUnauthorized(value)) message.error(apiMessage(value)); if (value instanceof ApiError && value.status === 409) await load(); }
finally { setBusyId(''); }
finally { actionLock.current = false; setBusyId(''); }
};
const showImpact = async (item: Record<string, unknown>) => {
@@ -566,6 +610,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
};
const classificationBusy=classificationUpdates.jobs.some(job=>!['failed','completed'].includes(job.status));
const applyCurrent = async () => {
if (actionLock.current) return; actionLock.current = true;
try {
await form.validateFields();
const values = form.getFieldsValue(true);
@@ -574,17 +619,18 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
if (value && typeof value === 'object' && 'errorFields' in value) return;
if (!onUnauthorized(value)) message.error(apiMessage(value));
}
finally { actionLock.current = false; }
};
useMaintenanceRefresh(() => { void load(true); void refreshWorkflowStatus(); void loadEditorSupport(); });
if (!workflowStatusLoaded) return <div className="management-page"><div className="loading-panel"><Spin />正在读取当前维护模式…</div></div>;
if (!workflowStatusLoaded) return <div className="management-page">{statusRead.busy ? <div className="loading-panel"><Spin />正在读取当前维护模式…</div> : workflowStatusError ? <Alert showIcon type="error" message="维护模式读取失败" description={workflowStatusError} action={<Button size="small" onClick={() => void refreshWorkflowStatus()}>重试</Button>} /> : null}</div>;
if (testMode) {
const notices = <>
{kind==='mappings'&&classificationUpdates.jobs.some(job=>job.status!=='completed')&&<div className="classification-queue-status" role="status">
{classificationBusy&&<span><Spin size="small"/> 后台更新中 · {classificationUpdates.jobs.filter(job=>!['failed','completed'].includes(job.status)).length} 条</span>}
{classificationUpdates.jobs.filter(job=>['failed','paused'].includes(job.status)).map(job=><Alert key={job.id} type="error" showIcon message={`${job.target}:${job.error}`} action={<><Button size="small" onClick={()=>classificationUpdates.queue.retry(job.id)}>重试</Button>{job.status==='failed'&&<Button size="small" onClick={()=>classificationUpdates.queue.dismiss(job.id)}>关闭</Button>}</>}/>)}
</div>}
{error && <Alert showIcon type="error" message="配置清单读取失败" description={error} />}
{error && <Alert showIcon type="error" message="配置清单读取失败" description={itemsLoaded ? `${error};下方仍显示上次成功结果。` : error} action={!itemsLoaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
{isRules && ruleSchemaError && <Alert showIcon type="error" message="规则编辑结构读取失败" description={ruleSchemaError} />}
{!canApplyWorkflow && <Alert showIcon type="info" message="当前账号可查看配置;保存和更新报表需要发布权限。" />}
{workflowOperation.error && <Alert showIcon type="error" message="保存或报表更新失败" description={workflowOperation.error} action={workflowOperation.operation?.operationId ? <Button size="small" onClick={workflowOperation.resume}>重试读取进度</Button> : undefined} />}
@@ -621,10 +667,10 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
{canManage && <Button type={isRules ? 'primary' : 'default'} disabled={loading || (isRules && !ruleSchema) || (kind === 'masterData' && !publishedNames)} onClick={() => openDraft()}>从启用版新建草稿</Button>}
<Button icon={<ReloadOutlined />} onClick={() => { void load(); void loadEditorSupport(); }}>刷新</Button>
</>} />
{error && <Alert showIcon type="error" message="配置清单读取失败" description={error} />}
{error && <Alert showIcon type="error" message="配置清单读取失败" description={itemsLoaded ? `${error};下方仍显示上次成功结果。` : error} action={!itemsLoaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
{isRules && ruleSchemaError && <Alert showIcon type="error" message="规则编辑结构读取失败" description={ruleSchemaError} />}
<section className="panel section-panel"><div className="resource-toolbar"><strong>{title}记录</strong><span>{items.length} 个服务端记录</span></div>
{loading ? <div className="loading-panel"><Spin />正在读取…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1160 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有配置记录;可新建草稿。" />}
{loading && !itemsLoaded ? <div className="loading-panel"><Spin />正在读取…</div> : itemsLoaded ? items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1160 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有配置记录;可新建草稿。" /> : null}
</section>
<Alert showIcon type="info" message="变更先保存为草稿" description="保存后在清单中校验并启用;启用后重新计算、核对并发布,查询结果才采用新配置。" action={!isRules ? <Button onClick={() => onNavigate('sources')}>前往重新计算</Button> : undefined} />
<Modal className="management-modal structured-config-modal" open={Boolean(drafting)} title={drafting?.id ? `编辑${title}草稿` : `新建${title}草稿`} width={1120} okText="保存草稿" confirmLoading={Boolean(busyId)} onCancel={() => setDrafting(null)} onOk={() => void saveDraft()}>
@@ -691,7 +737,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
<details className="completion-technical-detail"><summary>影响预览技术字段</summary><pre className="json-result">{publicJson(impact)}</pre></details>
</> : <div className="completion-loading"><Spin />由服务端重新核对配置依赖…</div>}</Drawer>
</div>;
return extraSections ? <MappingEditorContext.Provider value={{definition:draftDefinition,ready:!loading && !!matchMetadata,defaultRules:Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[],groups:publishedNames?.groups??[],projectGroups:publishedNames?.projectGroups??[],update:definition=>{void api.createMapping({name:`分类规则 ${configurationDateTime(new Date())}`,definition}).then(raw=>{const result=raw as Record<string,unknown>;setDraftDefinition(definition);setDrafting(result);form.setFieldsValue({name:String(result.name),description:''});void load();}).catch(value=>{if(!onUnauthorized(value))message.error(apiMessage(value));});}}}><ManagementSections items={[{ key: 'configuration', label: '对应关系', children: standardContent }, ...extraSections]} /></MappingEditorContext.Provider> : standardContent;
return extraSections ? <MappingEditorContext.Provider value={{definition:draftDefinition,ready:!loading && !!matchMetadata,defaultRules:Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[],groups:publishedNames?.groups??[],projectGroups:publishedNames?.projectGroups??[],update:definition=>{if(actionLock.current)return;actionLock.current=true;setBusyId('editor-new');void api.createMapping({name:`分类规则 ${configurationDateTime(new Date())}`,definition}).then(raw=>{const result=raw as Record<string,unknown>;setDraftDefinition(definition);setDrafting(result);form.setFieldsValue({name:String(result.name),description:''});void load();}).catch(value=>{if(!onUnauthorized(value))message.error(apiMessage(value));}).finally(()=>{actionLock.current=false;setBusyId('');});}}}><ManagementSections items={[{ key: 'configuration', label: '对应关系', children: standardContent }, ...extraSections]} /></MappingEditorContext.Provider> : standardContent;
}
function MappingMaintenancePage({ user, onUnauthorized, onNavigate }: Omit<ManagementPageProps, 'page'>) {
@@ -767,24 +813,23 @@ function MappingIssueResolutionPanel({ onUnauthorized, onEdit }: { onUnauthorize
function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
const { message } = App.useApp();
const { active } = usePageCache();
const [items, setItems] = useState<Record<string, unknown>[]>([]);
const [loading, setLoading] = useState(true);
const [loaded, setLoaded] = useState(false);
const read = useDelayedBusy(); const loading = read.busy;
const [dictionaryError, setDictionaryError] = useState('');
const [saving, setSaving] = useState(false);
const savingRef = useRef(false);
const [editing, setEditing] = useState<Record<string, unknown> | null>(null);
const [inspecting, setInspecting] = useState<Record<string, unknown> | null>(null);
const [form] = Form.useForm<{ name: string; aliases: string; description: string; reason: string }>();
const canManage = user.roles.some(role => ['SYSTEM_ADMIN', 'RULE_MAINTAINER'].includes(role));
const load = async () => {
setLoading(true);
try {
const result = await api.metricDictionary();
setItems(collectionItems(result)); setDictionaryError('');
} catch (value) { if (!onUnauthorized(value)) setDictionaryError(apiMessage(value)); }
setLoading(false);
};
useEffect(() => { void load(); }, []);
const load = useCallback(() => read.run(async () => {
try { const result = await api.metricDictionary(); setItems(collectionItems(result)); setLoaded(true); setDictionaryError(''); }
catch (value) { if (!onUnauthorized(value)) setDictionaryError(apiMessage(value)); }
}), [onUnauthorized, read.run]);
useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]);
const openEditor = (item: Record<string, unknown>) => {
setEditing(item);
@@ -795,7 +840,7 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
});
};
const save = async () => {
if (!editing) return;
if (!editing || savingRef.current) return; savingRef.current = true;
try {
const values = await form.validateFields();
const code = String(editing.code || '');
@@ -813,7 +858,7 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
if (value && typeof value === 'object' && 'errorFields' in value) return;
if (!onUnauthorized(value)) message.error(apiMessage(value));
if (value instanceof ApiError && value.status === 409) await load();
} finally { setSaving(false); }
} finally { savingRef.current = false; setSaving(false); }
};
const columns: ColumnsType<Record<string, unknown>> = [
@@ -828,8 +873,8 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
useMaintenanceRefresh(load);
return <section className="panel section-panel completion-tools">
<div className="completion-panel-heading"><div><strong>指标术语字典</strong><span>维护展示名称与别名;计算公式在上方计算规则中维护</span></div><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新字典</Button></div>
{dictionaryError && <Alert showIcon type="error" message="术语字典读取失败" description={dictionaryError} />}
{loading ? <div className="loading-panel"><Spin />读取术语定义…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.code)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1100 }} /></div> : !dictionaryError && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无指标术语" />}
{dictionaryError && <Alert showIcon type="error" message="术语字典读取失败" description={loaded ? `${dictionaryError};以下为上次成功读取的结果。` : dictionaryError} action={!loaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
{loading && !loaded ? <div className="loading-panel"><Spin />读取术语定义…</div> : loaded ? items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.code)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1100 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无指标术语" /> : null}
<Alert showIcon type="info" message="术语编辑不改变计算规则" description="公式来自当前查询数据所绑定的计算规则;编辑术语不会改变计算结果。" />
<Modal className="management-modal" open={Boolean(editing)} title={`编辑术语 · ${String(editing?.code || '')}`} okText="保存术语" confirmLoading={saving} onCancel={() => { setEditing(null); form.resetFields(); }} onOk={() => void save()}>
<Form form={form} layout="vertical">
@@ -851,6 +896,7 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
const [selected, setSelected] = useState<Record<string, unknown> | null>(null);
const [issuesRunId, setIssuesRunId] = useState('');
const [busyId, setBusyId] = useState('');
const actionLock = useRef(false);
const canRetry = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER'].includes(role));
const canCancel = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER', 'SYSTEM_OPERATOR'].includes(role));
const runIdOf = (row: Record<string, unknown>) => {
@@ -859,6 +905,7 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
};
const retry = async (row: Record<string, unknown>) => {
const id = String(row.id || ''); if (!id) return;
if (actionLock.current) return; actionLock.current = true;
setBusyId(id);
try {
const releases = await api.releases();
@@ -869,16 +916,17 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
else message.success(`任务重试完成:${toText(run.status || '已更新')}`);
onRefresh();
} catch (error) { if (!onUnauthorized(error)) message.error(apiMessage(error)); if (error instanceof ApiError && error.status === 409) onRefresh(); }
finally { setBusyId(''); }
finally { actionLock.current = false; setBusyId(''); }
};
const cancel = async (row: Record<string, unknown>) => {
const id = String(row.id || ''); if (!id) return;
if (actionLock.current) return; actionLock.current = true;
setBusyId(id);
try {
await api.cancelTask(id, { expectedStatus: String(row.status || '') });
message.success('已取消排队任务'); onRefresh();
} catch (error) { if (!onUnauthorized(error)) message.error(apiMessage(error)); if (error instanceof ApiError && error.status === 409) onRefresh(); }
finally { setBusyId(''); }
finally { actionLock.current = false; setBusyId(''); }
};
const importState = (value: unknown) => ({ COMPLETED: '导入完成', SUCCEEDED: '导入完成', FAILED: '导入失败', ERROR: '导入失败', RUNNING: '正在导入', QUEUED: '等待导入', CANCELLED: '已取消' }[String(value).toUpperCase()] || toText(value));
const columns: ColumnsType<Record<string, unknown>> = [
@@ -894,8 +942,8 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
{ title: '操作', key: 'detail', fixed: 'right', width: importOnly ? 240 : 150, align: 'center', render: (_, row) => <span className="task-actions">
<Button type="link" onClick={() => setSelected(row)}>详情</Button>
{importOnly && runIdOf(row) && <Button type="link" onClick={() => setIssuesRunId(runIdOf(row))}>校验问题</Button>}
{canRetry && String(row.status).toUpperCase() === 'FAILED' && runIdOf(row) && <Button type="link" loading={busyId === String(row.id)} onClick={() => void retry(row)}>重试</Button>}
{canCancel && String(row.status).toUpperCase() === 'QUEUED' && <Button type="link" danger loading={busyId === String(row.id)} onClick={() => void cancel(row)}>取消</Button>}
{canRetry && String(row.status).toUpperCase() === 'FAILED' && runIdOf(row) && <Button type="link" disabled={Boolean(busyId)} loading={busyId === String(row.id)} onClick={() => void retry(row)}>重试</Button>}
{canCancel && String(row.status).toUpperCase() === 'QUEUED' && <Button type="link" danger disabled={Boolean(busyId)} loading={busyId === String(row.id)} onClick={() => void cancel(row)}>取消</Button>}
</span> },
];
return <>
@@ -913,20 +961,32 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
const [renameTarget, setRenameTarget] = useState<Record<string, unknown> | null>(null);
const [renameTitle, setRenameTitle] = useState('');
const [renaming, setRenaming] = useState(false);
const sessionMutationLock = useRef(false);
const { active, initialSearch, refreshKey, onLocationChange } = usePageCache();
const activePage = useRef(active); activePage.current = active;
const initialParams = new URLSearchParams(initialSearch ?? window.location.search);
const initialSessionId = initialParams.get('sessionId') || '';
const initialTurnId = initialParams.get('turnId') || '';
const pendingTurnLink = useRef(initialTurnId);
const [initialLink] = useState(() => decodeAnalysisLinkContext(initialParams.get('context')));
const [query, setQuery] = useState('');
const [sessionId, setSessionId] = useState(initialSessionId);
const [sessionReadOnly, setSessionReadOnly] = useState(false);
const [sessionContext, setSessionContext] = useState<Record<string, unknown> | null>(null);
const [sessions, setSessions] = useState<Record<string, unknown>[]>([]);
const [sessionsLoaded, setSessionsLoaded] = useState(false);
const [sessionsLoading, setSessionsLoading] = useState(true);
const [sessionsError, setSessionsError] = useState('');
const showSessionsLoading = useDelayedIndicator(sessionsLoading && active, 150);
const sessionReadRequest = useRef<Promise<Record<string, unknown>[] | undefined> | null>(null);
const [turns, setTurns] = useState<Record<string, unknown>[]>([]);
const [options, setOptions] = useState<OptionsResponse | null>(null);
const [historyLoading, setHistoryLoading] = useState(true);
const showHistoryLoading = useDelayedIndicator(historyLoading && active, 150);
const optionsRead = useDelayedBusy();
const [optionsError, setOptionsError] = useState('');
const optionsRequestStarted = useRef(false);
const restoreStarted = useRef(false);
const [busy, setBusy] = useState(false);
const [queuedFollowup, setQueuedFollowup] = useState('');
const [stopping, setStopping] = useState(false);
@@ -1052,22 +1112,57 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
}, [lastTurn, busy, turns, sessionId, active]);
const loadSessions = async () => {
try { const items = collectionItems(await api.analysisSessions()); if (mounted.current) setSessions(items); }
catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); }
// 隐藏时的定时刷新由 useVisiblePolling 暂停;首次恢复不能因后台打开标签页而丢失。
if (!mounted.current || !active) return;
if (sessionReadRequest.current) return sessionReadRequest.current;
setSessionsLoading(true);
const request = (async () => {
try { const items = collectionItems(await api.analysisSessions()); if (mounted.current) { setSessions(items); setSessionsLoaded(true); setSessionsError(''); } return items; }
catch (value) { if (mounted.current && !onUnauthorized(value)) setSessionsError(apiMessage(value)); }
finally { if (mounted.current) setSessionsLoading(false); }
})();
sessionReadRequest.current = request;
try { return await request; }
finally { if (sessionReadRequest.current === request) sessionReadRequest.current = null; }
};
const retrySessions = async () => {
const generation = navigationGeneration.current;
setHistoryLoading(true);
const listRequest = loadSessions();
try {
const focusTurnId = pendingTurnLink.current;
let target = sessionId;
if (!target && focusTurnId) {
const turn = await api.analysisTurn(focusTurnId);
if (!mounted.current || generation !== navigationGeneration.current) return;
target = String(turn.sessionId || '');
if (!target) throw new Error('服务端未返回目标轮次所属会话');
}
if (target) await openSession(target, focusTurnId || undefined);
else {
const items = await listRequest;
const id = items && !initialLink.present ? defaultAnalysisSession(user.id, items) : '';
if (mounted.current && generation === navigationGeneration.current && id) await openSession(id);
}
} catch (value) { if (mounted.current && generation === navigationGeneration.current && !onUnauthorized(value)) setError(apiMessage(value)); }
finally { if (mounted.current && generation === navigationGeneration.current) setHistoryLoading(false); }
};
useEffect(() => {
let alive = true;
api.options().then(value => { if (alive) setOptions(value); })
.catch(value => { if (alive && !onUnauthorized(value)) setError(apiMessage(value)); });
return () => { alive = false; };
}, []);
if (!active || !initialLink.present || initialSessionId || initialTurnId || optionsRequestStarted.current) return;
optionsRequestStarted.current = true;
void optionsRead.run(async () => {
try { const value = await api.options(); if (mounted.current) { setOptions(value); setOptionsError(''); } }
catch (value) { if (mounted.current && !onUnauthorized(value)) setOptionsError(apiMessage(value)); }
});
}, [active, onUnauthorized, optionsRead.run]);
const hasBackgroundTurns = sessions.some(item => analysisIsRunning(item.activeTurnStatus));
useVisiblePolling(async () => { await loadSessions(); }, 5000, active && hasBackgroundTurns);
const wasActive = useRef(active);
useEffect(() => {
if (!hasBackgroundTurns) return;
const timer = window.setInterval(() => void loadSessions(), 5000);
return () => window.clearInterval(timer);
}, [hasBackgroundTurns]);
if (active && !wasActive.current && hasBackgroundTurns) void loadSessions();
wasActive.current = active;
}, [active, hasBackgroundTurns]);
useEffect(() => {
if (!initialLink.present || initialSessionId || initialTurnId || !options || userSelectionMade.current) return;
@@ -1165,6 +1260,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
}, [active, refreshKey]);
const openSession = async (id: string, focusTurnId?: string): Promise<boolean> => {
if (!focusTurnId) pendingTurnLink.current = '';
userSelectionMade.current = true;
beginAnalysisSelection(user.id);
const generation = ++navigationGeneration.current;
@@ -1204,12 +1300,14 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
setLastTurn(restored);
if (analysisIsRunning(restored.status)) void followTurn(selectedTurnId, String(restored.question || ''), id);
}
pendingTurnLink.current = '';
return true;
} catch (value) { if (current() && !onUnauthorized(value)) setError(apiMessage(value)); return false; }
finally { if (current()) setHistoryLoading(false); }
};
const newSession = () => {
pendingTurnLink.current = '';
userSelectionMade.current = true;
beginAnalysisSelection(user.id);
setQueuedFollowup('');
@@ -1229,6 +1327,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
};
const deleteSession = async (id: string) => {
if (sessionMutationLock.current) return; sessionMutationLock.current = true;
const generation = navigationGeneration.current;
try {
await api.deleteAnalysisSession(id);
@@ -1237,17 +1336,17 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
message.success('会话已删除');
} catch (value) {
if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '删除会话失败');
}
} finally { sessionMutationLock.current = false; }
};
const renameSession = async () => {
if (!renameTarget || !renameTitle.trim() || renaming) return;
if (!renameTarget || !renameTitle.trim() || sessionMutationLock.current) return; sessionMutationLock.current = true;
setRenaming(true);
try {
await api.renameAnalysisSession(String(renameTarget.id), renameTitle.trim());
setRenameTarget(null); await loadSessions(); message.success('会话已重命名');
} catch (value) { if (!onUnauthorized(value)) message.error(apiMessage(value)); }
finally { setRenaming(false); }
finally { sessionMutationLock.current = false; setRenaming(false); }
};
const followTurn = async (id: string, question: string, sessionOverride?: string) => {
@@ -1262,6 +1361,28 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
let streamedResult: Record<string, unknown> = {};
let terminalEventStatus = '';
setLastTurn(previous => ({ ...(previous || {}), id, question, status: previous?.status || 'QUEUED' }));
let timingReadInFlight = false, timingReadAgain = false, startConfirmed = false;
const refreshTiming = async (): Promise<void> => {
if (!linkedSessionId || !current() || startConfirmed) return;
if (timingReadInFlight) { timingReadAgain = true; return; }
timingReadInFlight = true;
try {
const history = await api.analysisSessionTurns(linkedSessionId);
if (!current()) return;
const timing = collectionItems(history).find(item => item.id === id);
if (!timing) return;
startConfirmed = typeof timing.startedAt === 'string' && Number.isFinite(Date.parse(timing.startedAt));
setLastTurn(previous => previous?.id !== id ? previous : { ...previous,
...(typeof timing.createdAt === 'string' ? { createdAt: timing.createdAt } : {}),
...(startConfirmed ? { startedAt: timing.startedAt } : {}),
});
} catch (value) { if (current()) onUnauthorized(value); }
finally {
timingReadInFlight = false;
if (timingReadAgain && !startConfirmed && current()) { timingReadAgain = false; void refreshTiming(); }
}
};
void refreshTiming();
try {
let detail: Record<string, unknown> = {};
let reconnectAttempt = 0;
@@ -1282,15 +1403,13 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
if (eventResult) streamedResult = { ...streamedResult, ...eventResult };
const eventName = event.event.toUpperCase().replaceAll('.', '_').replaceAll('-', '_');
const eventStatus = String(data.status || '').toUpperCase();
if (ANALYSIS_FINAL_STATUSES.has(eventStatus)) terminalEventStatus = eventStatus;
else if (/^(?:TURN_)?(COMPLETED|PARTIAL|FAILED|CANCELLED|NEEDS_CLARIFICATION)$/.test(eventName)) {
terminalEventStatus = eventName.replace(/^TURN_/, '');
}
const turnEventStatus = analysisStreamStatus(undefined, event.event, data.status);
if (ANALYSIS_FINAL_STATUSES.has(turnEventStatus)) terminalEventStatus = turnEventStatus;
setLastTurn(previous => {
const prior = previous || {};
if (prior.id === id && ANALYSIS_FINAL_STATUSES.has(String(prior.status || '').toUpperCase()) && !ANALYSIS_FINAL_STATUSES.has(eventStatus)) return prior;
const priorResult = isObjectRecord(prior.result) ? prior.result : {};
const status = data.status || (['progress', 'message', 'heartbeat'].includes(event.event.toLowerCase()) ? prior.status || 'RUNNING' : event.event.toUpperCase());
const status = analysisStreamStatus(prior.status, event.event, data.status);
return {
...prior,
id,
@@ -1311,6 +1430,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
// The SSE request can otherwise remain open after its terminal event.
// Closing this subscription does not cancel the analysis itself.
if (terminalEventStatus) controller.abort();
else if (eventStatus === 'RUNNING' || eventName.startsWith('TOOL_')) void refreshTiming();
},
});
} catch (streamError) {
@@ -1367,31 +1487,37 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
};
useEffect(() => {
if (!active || restoreStarted.current) return;
restoreStarted.current = true;
mounted.current = true;
let cancelled = false;
const restore = async () => {
const requestedAt = navigationGeneration.current;
setHistoryLoading(true);
try {
const items = collectionItems(await api.analysisSessions());
if (cancelled || requestedAt !== navigationGeneration.current) return;
setSessions(items);
const listRequest = loadSessions();
let linkedSession = initialSessionId;
if (initialTurnId) {
const linkedTurn = await api.analysisTurn(initialTurnId);
if (cancelled || requestedAt !== navigationGeneration.current) return;
if (!mounted.current || requestedAt !== navigationGeneration.current) return;
const turnSession = String(linkedTurn.sessionId || '');
if (linkedSession && turnSession && linkedSession !== turnSession) throw new Error('分析轮次与会话链接不匹配');
linkedSession ||= turnSession;
}
if (!linkedSession && !initialLink.present) linkedSession = defaultAnalysisSession(user.id, items);
if (!cancelled && requestedAt === navigationGeneration.current && linkedSession) await openSession(linkedSession, initialTurnId || undefined);
} catch (value) { if (!cancelled && !onUnauthorized(value)) setError(apiMessage(value)); }
finally { if (!cancelled && requestedAt === navigationGeneration.current && !initialLink.present) setHistoryLoading(false); }
if (!linkedSession && !initialLink.present) {
const items = await listRequest;
if (!mounted.current || requestedAt !== navigationGeneration.current) return;
if (items) linkedSession = defaultAnalysisSession(user.id, items);
}
if (mounted.current && requestedAt === navigationGeneration.current && linkedSession) await openSession(linkedSession, initialTurnId || undefined);
} catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); }
finally { if (mounted.current && requestedAt === navigationGeneration.current && !initialLink.present) setHistoryLoading(false); }
};
void restore();
}, [active]);
useEffect(() => {
mounted.current = true;
return () => {
cancelled = true; mounted.current = false;
mounted.current = false;
navigationGeneration.current += 1; subscriptionGeneration.current += 1;
// Unsubscribe from updates only. The accepted server task continues independently.
streamController.current?.abort(); streamController.current = null;
@@ -1457,7 +1583,8 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
followRequest.current = attempt.idempotencyKey;
followOutput.current = true;
explicitlyFollowing.current = false;
setLastTurn({ ...turn, status: 'QUEUED', _uiFollowKey: attempt.idempotencyKey });
const submittedAt = new Date().toISOString();
setLastTurn({ id, sessionId: targetSessionId, question, status: 'SUBMITTING', _uiSubmittedAt: submittedAt, _uiFollowKey: attempt.idempotencyKey });
const current = () => mounted.current && generation === navigationGeneration.current && submissionAttempt.current === attempt;
setError(''); setBusy(true); setActiveTurnId(id);
try {
@@ -1475,7 +1602,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
if (!current()) return;
const retriedDetail = await api.analysisTurn(retryId);
if (!current()) return;
setLastTurn({ ...retriedDetail, ...retried, id: retryId, sessionId: retrySessionId, question, _uiFollowKey: attempt.idempotencyKey });
setLastTurn({ ...retriedDetail, ...retried, id: retryId, sessionId: retrySessionId, question, _uiSubmittedAt: submittedAt, _uiFollowKey: attempt.idempotencyKey });
writeAnalysisLocation(retrySessionId, retryId);
void loadSessions();
if (!current()) return;
@@ -1517,7 +1644,8 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
setError('');
setRetryQuestion(question.trim());
if (typeof lastTurn?.id === 'string' && lastTurn.id) setTurns(previous => previous.some(item => item.id === lastTurn.id) ? previous : [...previous, lastTurn]);
setLastTurn({ question: question.trim(), status: 'QUEUED', _uiFollowKey: attempt.idempotencyKey });
const submittedAt = new Date().toISOString();
setLastTurn({ question: question.trim(), status: 'SUBMITTING', _uiSubmittedAt: submittedAt, _uiFollowKey: attempt.idempotencyKey });
setQuery('');
try {
let selectedSessionId = sessionId;
@@ -1546,7 +1674,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
attempt.uncertain = false;
attempt.acceptedTurnId = turnId;
setActiveTurnId(turnId);
setLastTurn({ ...turn, id: turnId, question: question.trim(), sessionId: selectedSessionId, _uiFollowKey: attempt.idempotencyKey });
setLastTurn({ ...turn, status: turn.status || 'QUEUED', id: turnId, question: question.trim(), sessionId: selectedSessionId, _uiSubmittedAt: submittedAt, _uiFollowKey: attempt.idempotencyKey });
writeAnalysisLocation(selectedSessionId, turnId);
if (attempt.cancelRequested && await cancelAcceptedTurn(turnId, generation, question.trim())) return;
void loadSessions();
@@ -1589,20 +1717,22 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
return <div className="management-page analysis-simple-page">
<PageHeader title="智能分析" />
{error && <Alert type="error" showIcon message="智能分析状态" description={error} action={retryQuestion && <Button size="small" onClick={() => void submit(retryQuestion)}>重试上一问</Button>} />}
{error && <Alert type="error" showIcon message="智能分析状态" description={error} action={<>{retryQuestion && <Button size="small" onClick={() => void submit(retryQuestion)}>重试上一问</Button>}<Button size="small" onClick={() => void retrySessions()}>重新读取会话</Button></>} />}
{optionsError && <Alert type="error" showIcon message="分析选项读取失败" description={options ? `${optionsError};已成功读取的选项仍保留。` : optionsError} action={<Button size="small" onClick={() => { optionsRequestStarted.current = false; setOptionsError(''); optionsRequestStarted.current = true; void optionsRead.run(async () => { try { setOptions(await api.options()); setOptionsError(''); } catch (value) { if (!onUnauthorized(value)) setOptionsError(apiMessage(value)); } }); }}>重试</Button>} />}
<div className="analysis-workspace">
<aside className="panel analysis-session-panel">
<div className="analysis-session-heading"><strong>会话</strong><Button type="primary" size="small" onClick={newSession}>新会话</Button></div>
{historyLoading ? <div className="loading-panel compact"><Spin />正在读取会话…</div> : sessions.length ? <div className="analysis-session-list">{sessions.map(item => <div key={String(item.id)} className={`analysis-session-row ${sessionId === item.id ? 'active' : ''}`}><button className="analysis-session-item" onClick={() => void openSession(String(item.id))}><strong>{toText(item.title || '未命名会话')}</strong><small>{String(item.updatedAt || item.createdAt || '').slice(0, 10)}{analysisIsRunning(item.activeTurnStatus) && <span className="analysis-session-state">{item.activeTurnStatus === 'QUEUED' ? '排队中' : '分析中'}</span>}</small></button><Dropdown trigger={['click']} menu={{ items: [
{sessionsError && <Alert type="error" message="会话列表读取失败" description={sessionsError} action={<Button size="small" onClick={() => { if (!userSelectionMade.current && !sessionId) void retrySessions(); else void loadSessions(); }}>重试</Button>} />}
{!sessionsLoaded && showSessionsLoading ? <div className="analysis-region-loading" role="status"><Spin />正在读取会话列表…</div> : sessionsLoaded ? sessions.length ? <div className="analysis-session-list">{sessions.map(item => <div key={String(item.id)} className={`analysis-session-row ${sessionId === item.id ? 'active' : ''}`}><button className="analysis-session-item" onClick={() => void openSession(String(item.id))}><strong>{toText(item.title || '未命名会话')}</strong><small>{String(item.updatedAt || item.createdAt || '').slice(0, 10)}{analysisIsRunning(item.activeTurnStatus) && <span className="analysis-session-state">{item.activeTurnStatus === 'QUEUED' ? '排队中' : '分析中'}</span>}</small></button><Dropdown trigger={['click']} menu={{ items: [
{ key: 'rename', icon: <EditOutlined />, label: '重命名' },
{ key: 'delete', icon: <DeleteOutlined />, label: '删除', danger: true, disabled: analysisIsRunning(item.activeTurnStatus) },
], onClick: ({ key }) => {
if (key === 'rename') { setRenameTarget(item); setRenameTitle(String(item.title || '')); }
else if (key === 'delete') modal.confirm({ title: '删除此会话及其分析记录?', content: '删除后无法恢复', okText: '删除', cancelText: '取消', okButtonProps: { danger: true }, onOk: () => deleteSession(String(item.id)) });
} }}><Button className="analysis-session-menu" type="text" icon={<MoreOutlined />} aria-label={`会话操作 ${toText(item.title || '未命名会话')}`} /></Dropdown></div>)}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无历史会话" />}
} }}><Button className="analysis-session-menu" type="text" icon={<MoreOutlined />} aria-label={`会话操作 ${toText(item.title || '未命名会话')}`} /></Dropdown></div>)}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无历史会话" /> : null}
</aside>
<section className="panel analysis-chat-panel">
<div className="analysis-conversation" ref={conversation} aria-live="polite" onWheel={event => {
<div className="analysis-conversation" ref={conversation} aria-live="polite" aria-busy={historyLoading} onWheel={event => {
const direction = event.deltaY < 0 ? 'up' : event.deltaY > 0 ? 'down' : null;
if (direction) handleUserScrollIntent(event.currentTarget, direction);
}} onPointerDown={event => {
@@ -1641,7 +1771,8 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
}}>
{turns.map((turn, index) => <AnalysisTurn key={String(turn.id || index)} turn={turn} onRetry={sessionReadOnly ? undefined : (id) => void retryTurn(turns.find(item => String(item.id || '') === id) || turn)} onResume={id => { if (!historyLoading) void followTurn(id, String(turn.question || '')); }} onUnauthorized={onUnauthorized} retryDisabled={sessionReadOnly || busy || historyLoading} />)}
{lastTurn && <AnalysisTurn turn={lastTurn} onClarify={sessionReadOnly ? undefined : question => submit(question)} onRetry={sessionReadOnly ? undefined : () => void retryTurn(lastTurn)} onResume={id => { if (!historyLoading) void followTurn(id, String(lastTurn.question || '')); }} onUnauthorized={onUnauthorized} retryDisabled={sessionReadOnly || busy || historyLoading} />}
{!turns.length && !lastTurn && !busy && <div className="analysis-empty"><RobotOutlined /><strong>想了解哪些质量情况?</strong><span>例如:9月汽车交通的合格率为什么下降?</span></div>}
{!turns.length && !lastTurn && showHistoryLoading && <div className="analysis-region-loading" role="status"><Spin />正在读取会话…</div>}
{!turns.length && !lastTurn && !busy && !historyLoading && !error && !sessionsError && <div className="analysis-empty"><RobotOutlined /><strong>想了解哪些质量情况?</strong><span>例如:9月汽车交通的合格率为什么下降?</span></div>}
</div>
{hasNewContent && <Button size="small" type="text" className="analysis-new-content" onClick={() => {
const element = conversation.current;
@@ -1669,7 +1800,6 @@ function AnalysisTurn({ turn: sourceTurn, onResume, onRetry, onClarify, onUnauth
const question = typeof turn.question === 'string' ? turn.question : '';
if (!turn.id && typeof turn.submissionNotice === 'string') return <article className="analysis-turn">
{question && <div className="analysis-question"><p>{question}</p></div>}
<p className="analysis-chat-notice" role="status">{turn.submissionNotice}</p>
</article>;
const result = isObjectRecord(turn.result) ? turn.result : turn;
const memberList = result.memberList ?? turn.memberList;
@@ -1679,24 +1809,15 @@ function AnalysisTurn({ turn: sourceTurn, onResume, onRetry, onClarify, onUnauth
const visuals = result.visualSchemaVersion === 1 ? result.visuals : undefined;
const reportMarkdown = typeof result.reportMarkdown === 'string' ? result.reportMarkdown : typeof turn.reportMarkdown === 'string' ? turn.reportMarkdown : '';
const reportHtml = typeof result.reportHtml === 'string' ? result.reportHtml : typeof turn.reportHtml === 'string' ? turn.reportHtml : undefined;
const resumable = ['QUEUED', 'RUNNING', 'PROCESSING', 'PLANNING', 'TOOL_RUNNING'].includes(status);
const errorValue = result.error || turn.error;
const failure = typeof errorValue === 'string' ? errorValue : '分析暂时中断,可以重试或继续提问。';
const emptyStatus = status === 'CANCELLED' ? '本次分析已取消,未返回回答内容。'
: status === 'PARTIAL' ? '本轮已保存查询过程,尚未形成最终答复。'
: status === 'COMPLETED' ? '分析任务已完成,但未返回回答内容。'
: failure;
const scope = analysisScopeText(turn);
const resumable = ['SUBMITTING', 'QUEUED', 'RUNNING', 'PROCESSING', 'PLANNING', 'TOOL_RUNNING'].includes(status);
return <article className="analysis-turn" data-analysis-turn-id={String(turn.id || '')} data-analysis-status={status}>
{question && <div className="analysis-question"><p>{question}</p></div>}
{scope && <p className="analysis-turn-scope" aria-label="本轮分析范围">{scope}</p>}
<AnalysisProcess turn={turn} metadata={<AnalysisTurnMetadata turn={turn} status={status} compact />} />
{(!resumable || !Array.isArray(turn.timeline || (isObjectRecord(turn.plan) ? turn.plan.timeline : undefined))) && (answer || !resumable || !retryDisabled) && <div className="analysis-answer">
{status === 'NEEDS_CLARIFICATION' && onClarify ? <AnalysisClarification turn={turn} disabled={retryDisabled} onContinue={onClarify} /> : answer ? <>
{resumable ? <AiMarkdown content={answer} className="ai-answer" />
: <AnalysisNarrative answer={answer} visuals={visuals} visualState={result.visualState} question={question} turnId={String(turn.id || '')} beforeExport={() => authorizeAnalysisSnapshot(turn)} turn={turn} />}
</> : <p className={resumable ? 'analysis-chat-notice' : undefined}>{resumable ? '分析任务仍在运行,尚未返回完整回答。' : emptyStatus}</p>}
{status === 'PARTIAL' && answer && <p className="analysis-chat-notice">{partialAnalysisNotice(result.stopReason || turn.stopReason || (isObjectRecord(turn.plan) ? turn.plan.stopReason : ''), result)}</p>}
</> : null}
<div className="analysis-message-actions">
{(reportMarkdown.trim() || reportHtml?.trim()) && <NativeAnalysisReport turn={turn} reportMarkdown={reportMarkdown} reportHtml={reportHtml} />}
{!reportMarkdown.trim() && !reportHtml?.trim() && answer && ['COMPLETED', 'PARTIAL'].includes(status) && <AnalysisReportExport turn={turn} />}
@@ -1704,7 +1825,6 @@ function AnalysisTurn({ turn: sourceTurn, onResume, onRetry, onClarify, onUnauth
{['FAILED', 'CANCELLED', 'PARTIAL'].includes(status) && typeof turn.id === 'string' && onRetry && <Button size="small" type="text" disabled={retryDisabled||recovery.recovering} onClick={() => onRetry(String(turn.id))}>重新分析</Button>}
{resumable && !retryDisabled && typeof turn.id === 'string' && onResume && <Button size="small" type="text" onClick={() => onResume(String(turn.id))}>继续分析</Button>}
</div>
{recovery.error&&<p className="analysis-chat-notice" role="alert">{recovery.error}</p>}
</div>}
{memberList !== undefined && memberList !== null && <AnalysisMemberListPanel turn={turn} value={memberList} onUnauthorized={onUnauthorized} />}
{recordList !== undefined && recordList !== null && <AnalysisRecordListPanel turn={turn} value={recordList} onUnauthorized={onUnauthorized} />}
@@ -1713,21 +1833,23 @@ function AnalysisTurn({ turn: sourceTurn, onResume, onRetry, onClarify, onUnauth
function AnalysisTurnMetadata({ turn, status, compact = false }: { turn: Record<string, unknown>; status: string; compact?: boolean }) {
const [now, setNow] = useState(Date.now());
const running = analysisIsRunning(status);
const running = analysisIsRunning(status) || status === 'SUBMITTING';
useEffect(() => { if (!running) return; setNow(Date.now()); const timer = window.setInterval(() => setNow(Date.now()), 1000); return () => window.clearInterval(timer); }, [running]);
const plan = isObjectRecord(turn.plan) ? turn.plan : {};
const date = (value: unknown) => typeof value === 'string' && Number.isFinite(Date.parse(value)) ? Date.parse(value) : undefined;
const start = date(turn.startedAt) ?? date(plan.startedAt);
const waitingSince = date(turn._uiSubmittedAt) ?? date(turn.createdAt);
const clockStart = start ?? (running ? waitingSince : undefined);
const finish = date(turn.finishedAt);
const duration = typeof turn.durationMs === 'number' ? turn.durationMs : start !== undefined && (running || finish !== undefined) ? Math.max(0, (running ? now : finish!) - start) : undefined;
const duration = !running && typeof turn.durationMs === 'number' ? turn.durationMs : clockStart !== undefined && (running || finish !== undefined) ? Math.max(0, (running ? now : finish!) - clockStart) : undefined;
const seconds = duration === undefined ? undefined : Math.floor(duration / 1000);
const durationText = seconds === undefined ? '' : seconds >= 3600 ? `${Math.floor(seconds / 3600)}小时${Math.floor(seconds % 3600 / 60)}分${seconds % 60}秒` : seconds >= 60 ? `${Math.floor(seconds / 60)}分${seconds % 60}秒` : `${seconds}秒`;
const stamp = (value: number) => new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }).format(value);
const steps = Array.isArray(turn.steps) ? turn.steps : Array.isArray(plan.steps) ? plan.steps : [];
const labels: Record<string, string> = { QUEUED: '排队中', RUNNING: '运行中', COMPLETED: '已完成', PARTIAL: '部分完成', FAILED: '未完成', CANCELLED: '已停止', NEEDS_CLARIFICATION: '待补充信息' };
const labels: Record<string, string> = { SUBMITTING: '提交中', QUEUED: '排队中', RUNNING: '运行中', COMPLETED: '已完成', PARTIAL: '', FAILED: '未完成', CANCELLED: '已停止', NEEDS_CLARIFICATION: '待补充信息' };
return <span className="analysis-turn-metadata" aria-label="分析运行信息">
<span>{labels[status] || (running ? '运行中' : '分析记录')}</span>
{durationText && <span>{running ? '已运行' : '运行时长'} {durationText}</span>}
{status !== 'PARTIAL' && <span>{labels[status] || (running ? '运行中' : '分析记录')}</span>}
{durationText && <span className="analysis-runtime-clock">{running && <LoadingOutlined spin className="analysis-runtime-spinner" aria-hidden="true" />}{running ? start === undefined ? '已等待' : '已运行' : '运行时长'} {durationText}</span>}
{!compact && start !== undefined && <span>开始 {stamp(start)}</span>}
{!compact && !running && finish !== undefined && <span>{status === 'COMPLETED' ? '完成时间' : '结束时间'} {stamp(finish)}</span>}
{!compact && steps.length > 0 && <span>工具调用 {steps.length} 次</span>}
@@ -1758,23 +1880,24 @@ function AccessPage({ user, onUnauthorized }: { user: AuthUser; onUnauthorized:
}
function ResourceTab({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
const { active } = usePageCache();
const [result, setResult] = useState<Collection | null>(null);
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(true);
const [loadedPage, setLoadedPage] = useState(0);
const read = useDelayedBusy(); const loading = read.busy;
const [error, setError] = useState('');
const load = async (nextPage = page) => {
setLoading(true);
try { setResult(await api.audit(nextPage, TABLE_PAGE_SIZE)); setError(''); }
const load = useCallback((nextPage = page) => read.run(async () => {
try { setResult(await api.audit(nextPage, TABLE_PAGE_SIZE)); setLoadedPage(nextPage); setError(''); }
catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
finally { setLoading(false); }
};
useEffect(() => { void load(page); }, [page]);
}), [onUnauthorized, page, read.run]);
useEffect(() => { if (active && loadedPage !== page) void load(page); }, [active, loadedPage, page, load]);
useMaintenanceRefresh(() => { void load(page); });
const items = unwrapItems(result).items;
const total = result?.total ?? items.length;
return <div className="resource-tab">
{error && <Alert type="error" showIcon message="审计记录读取失败" description={error} />}
<div className="resource-toolbar"><strong>审计事件</strong><span>{result?.total !== undefined ? `共 ${result.total} 条` : `${items.length} 条`}</span><Button icon={<ReloadOutlined />} onClick={() => void load(page)}>刷新</Button></div>
{loading ? <div className="loading-panel"><Spin />正在读取…</div> : <DynamicTable items={items} paginate={false} indexOffset={(page - 1) * TABLE_PAGE_SIZE} />}
{error && <Alert type="error" showIcon message="审计记录读取失败" description={loadedPage ? `${error};当前仍显示第 ${loadedPage} 页上次成功结果。` : error} action={!loadedPage ? <Button size="small" onClick={() => void load(page)}>重试</Button> : undefined} />}
<div className="resource-toolbar"><strong>审计事件</strong><span>{result?.total !== undefined ? `共 ${result.total} 条` : `${items.length} 条`}</span><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load(page)}>刷新</Button></div>
{loading && loadedPage !== page ? <div className="loading-panel"><Spin />正在读取…</div> : result && <DynamicTable items={items} paginate={false} indexOffset={(loadedPage - 1) * TABLE_PAGE_SIZE} />}
{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={total} showTotal={count => `共 ${count} 条`} onChange={setPage} />}
</div>;
}
@@ -1783,29 +1906,35 @@ const ROLE_OPTIONS = ['SYSTEM_ADMIN', 'QUALITY_VIEWER', 'BUSINESS_ANALYST', 'DAT
function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
const { message } = App.useApp();
const { active } = usePageCache();
const [users, setUsers] = useState<Record<string, unknown>[]>([]);
const [departments, setDepartments] = useState<string[]>([]);
const [groups, setGroups] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
const [usersLoaded, setUsersLoaded] = useState(false);
const [optionsLoaded, setOptionsLoaded] = useState(false);
const read = useDelayedBusy(); const loading = read.busy;
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const saveLock = useRef(false);
const [editing, setEditing] = useState<Record<string, unknown> | null>(null);
const [form] = Form.useForm<{ username: string; displayName: string; password: string; active: boolean; forcePasswordChange: boolean; roles: string[]; departments: string[]; groups: string[] }>();
const canManage = user.roles.includes('SYSTEM_ADMIN');
const load = async () => {
setLoading(true);
try {
const [userResult, optionsResult] = await Promise.all([api.users(), api.options()]);
const rows = collectionItems(userResult);
setUsers(rows);
setDepartments(Array.from(new Set([...(optionsResult.departments || []), ...rows.flatMap(row => Array.isArray(row.departments) ? row.departments.map(String) : [])])));
setGroups(Array.from(new Set([...(optionsResult.groups || []), ...rows.flatMap(row => Array.isArray(row.groups) ? row.groups.map(String) : [])])));
setError('');
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
finally { setLoading(false); }
};
useEffect(() => { void load(); }, []);
const load = useCallback(() => read.run(async () => {
const [userResult, optionsResult] = await Promise.allSettled([api.users(), api.options()]);
const failures: string[] = [];
let rows = users;
if (userResult.status === 'fulfilled') { rows = collectionItems(userResult.value); setUsers(rows); setUsersLoaded(true); }
else if (!onUnauthorized(userResult.reason)) failures.push(`用户清单:${apiMessage(userResult.reason)}`);
if (optionsResult.status === 'fulfilled') {
setDepartments(Array.from(new Set([...(optionsResult.value.departments || []), ...rows.flatMap(row => Array.isArray(row.departments) ? row.departments.map(String) : [])])));
setGroups(Array.from(new Set([...(optionsResult.value.groups || []), ...rows.flatMap(row => Array.isArray(row.groups) ? row.groups.map(String) : [])])));
setOptionsLoaded(true);
} else if (!onUnauthorized(optionsResult.reason)) failures.push(`授权选项:${apiMessage(optionsResult.reason)}`);
setError(failures.join(';'));
}), [onUnauthorized, read.run, users]);
useEffect(() => { if (active && !usersLoaded) void load(); }, [active, usersLoaded, load]);
useMaintenanceRefresh(load);
const openEditor = (record?: Record<string, unknown>) => {
setEditing(record || {});
@@ -1819,6 +1948,7 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
};
const save = async () => {
if (saveLock.current) return; saveLock.current = true;
try {
const values = await form.validateFields();
setBusy(true);
@@ -1834,7 +1964,7 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
if (value && typeof value === 'object' && 'errorFields' in value) return;
if (!onUnauthorized(value)) message.error(apiMessage(value));
if (value instanceof ApiError && value.status === 409) await load();
} finally { setBusy(false); }
} finally { saveLock.current = false; setBusy(false); }
};
const columns: ColumnsType<Record<string, unknown>> = [
@@ -1847,9 +1977,9 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
{ title: '操作', key: 'actions', fixed: 'right', width: 110, align: 'center', render: (_, row) => canManage ? <Button type="link" onClick={() => openEditor(row)}>编辑授权</Button> : <span className="muted-dash">权限不足</span> },
];
return <div className="resource-tab">
{error && <Alert type="error" showIcon message="用户清单读取失败" description={error} />}
{error && <Alert type="error" showIcon message="用户清单读取失败" description={usersLoaded || optionsLoaded ? `${error};已成功读取的内容仍保留。` : error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
<div className="resource-toolbar"><strong>用户清单</strong><span>{users.length} 个账号</span>{canManage && <Button type="primary" onClick={() => openEditor()}>新建用户</Button>}<Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button></div>
{loading ? <div className="loading-panel"><Spin />正在读取用户与授权范围…</div> : users.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={users} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1210 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有用户" />}
{loading && !usersLoaded ? <div className="loading-panel"><Spin />正在读取用户与授权范围…</div> : usersLoaded ? users.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={users} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1210 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有用户" /> : null}
<Modal className="management-modal" open={Boolean(editing)} title={editing?.id ? '编辑用户授权' : '新建用户'} width={700} confirmLoading={busy} onCancel={() => setEditing(null)} onOk={() => void save()}>
<Alert className="user-management-note" showIcon type="info" message="需至少保留一个启用的系统管理员;未配置产业部的非管理员账号可能没有业务数据访问范围。" />
<Form form={form} layout="vertical">
@@ -1865,21 +1995,22 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
}
function BasisPage({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
const { active } = usePageCache();
const [rules, setRules] = useState<Record<string, unknown>[]>([]);
const [ruleError, setRuleError] = useState('');
const [loading, setLoading] = useState(true);
const load = async () => {
setLoading(true);
try { setRules(unwrapItems(await api.rules()).items); setRuleError(''); }
const [loaded, setLoaded] = useState(false);
const read = useDelayedBusy(); const loading = read.busy;
const load = useCallback(() => read.run(async () => {
try { setRules(unwrapItems(await api.rules()).items); setLoaded(true); setRuleError(''); }
catch (value) { if (!onUnauthorized(value)) setRuleError(apiMessage(value)); }
finally { setLoading(false); }
};
useEffect(() => { void load(); }, []);
}), [onUnauthorized, read.run]);
useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]);
useMaintenanceRefresh(load);
return <div className="management-page">
<PageHeader title="数据与计算依据" description="综合合格率沿用正式指标服务结果;计算规则由服务端统一维护。" actions={<Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>} />
<Alert showIcon type="info" message="综合合格率 = 同一筛选条件下黑片合格率 × 亮片合格率" description="此处说明业务口径。前端只展示服务端正式返回的指标,不用浏览器数据重算或替代正式结果。" />
<div className="basis-grid">
<section className="panel section-panel"><div className="resource-toolbar"><strong>指标规则</strong><span>{rules.length} 条</span></div>{ruleError && <Alert type="error" message={ruleError} />}{loading ? <div className="loading-panel"><Spin /></div> : <DynamicTable items={rules} />}</section>
<section className="panel section-panel"><div className="resource-toolbar"><strong>指标规则</strong><span>{rules.length} 条</span></div>{ruleError && <Alert type="error" showIcon message="指标规则读取失败" description={loaded ? `${ruleError};下方保留上次成功结果。` : ruleError} action={!loaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}{loading && !loaded ? <div className="loading-panel"><Spin /></div> : loaded && <DynamicTable items={rules} />}</section>
</div>
</div>;
}
+4 -2
View File
@@ -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
View File
@@ -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 <>
+5 -2
View File
@@ -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}
+7 -8
View File
@@ -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}>
+194 -179
View File
@@ -1,9 +1,12 @@
import { loadedQueryScope, queryForLocation, readQueryLocation } from './queryLoadingScope';
import { AnimatedMetricText, SmoothTableFrame, useAnimatedMetricText, useRetainedResult } from './QueryResultMotion';
import { trendBarPalette } from './trendBarPalette';
import { getWorkspaceTheme } from './ui-themes';
import { queryScrapWeight, queryTotalScrapWeight, type QueryRateBasis } from './queryMetricValues';
import { BusinessValue } from './BusinessValue';
import { usePageCache } from './pageCache';
import { useDelayedIndicator } from './useDelayedBusy';
import { useResourceVisibility } from './useResourceVisibility';
import { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';
import * as echarts from 'echarts/core';
import { BarChart, LineChart } from 'echarts/charts';
@@ -25,7 +28,7 @@ import {
Tooltip,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { DownloadOutlined, InfoCircleOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import { ArrowLeftOutlined, DownloadOutlined, InfoCircleOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import { ApiError, api, decodeQueryValueList, encodeQueryValueList } from './api';
import type {
DefectMetric,
@@ -47,6 +50,10 @@ import { readableSelectPopup } from './readableSelectPopup';
import { isInternalDataField, readableMetricFormula } from './publicDataDisplay';
import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
import { defectWeightRate } from './trendMetrics';
import { defaultFullMetricFields, metricStageColumnPlan, type MetricStageField } from './metricColumnPlan';
import DefectComposition from './DefectComposition';
import { QueryTrendPanel, QueryTablePanel } from './QueryPanels';
import { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection';
import './query-motion.css';
import { ExtraQueryFilters } from './ExtraQueryFilters';
import { freezeSourceRecordsQuery } from './sourceRecordsContext';
@@ -55,11 +62,10 @@ import { downloadMetricWorkbook } from './metricWorkbook';
echarts.use([BarChart, LineChart, GraphicComponent, GridComponent, LegendComponent, MarkLineComponent, TooltipComponent, SVGRenderer]);
const MONTHS = Array.from({ length: 12 }, (_, index) => `${String(index + 1).padStart(2, '0')}月`);
// 图表为保持坐标交互准确使用局部 zoom,字体需抵消该缩放以匹配页面正文。
// 图表直接沿用页面字号,不再补偿内部缩放。
function queryChartTypography(node: HTMLElement) {
const css = getComputedStyle(node);
const zoom = Number.parseFloat(css.zoom) || 1;
const size = (token: string, fallback: number) => Math.round((Number.parseFloat(css.getPropertyValue(token)) || fallback) / zoom * 10) / 10;
const size = (token: string, fallback: number) => Math.round((Number.parseFloat(css.getPropertyValue(token)) || fallback) * 10) / 10;
return {
fontFamily: css.getPropertyValue('--font-ui').trim() || css.fontFamily,
numericFamily: css.getPropertyValue('--font-numeric').trim() || css.fontFamily,
@@ -151,6 +157,7 @@ function monthNumber(value: number | string): number | null {
return result >= 1 && result <= 12 ? result : null;
}
function fullYearTrend(rows: TrendMetricRow[], year: number, granularity: 'month' | 'quarter' | 'year'): TrendMetricRow[] {
if (granularity === 'year') return rows;
const byPeriod = new Map<string, TrendMetricRow>();
@@ -204,10 +211,6 @@ function defectList(row: MetricRow | undefined, stage: Stage): DefectMetric[] {
return row?.[stage]?.defects || [];
}
function defectsFor(rows: MetricRow[], stage: Stage): string[] {
return Array.from(new Set(rows.flatMap(row => defectList(row, stage).map(item => item.name))));
}
interface ChartTooltipParam {
name?: string | number;
axisValue?: string | number;
@@ -226,16 +229,7 @@ function escapeTooltipText(value: string): string {
}
export function queryFromLocation(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>) };
delete query.releaseId;
return query;
} catch { return {}; }
return readQueryLocation(search);
}
function toApiParams(args: {
@@ -289,7 +283,7 @@ export default function QueryPage({ page, onUnauthorized }: {
onNavigate?: (page: PageKey, query: QueryParams, resultRef?: TopResultRef) => void;
}) {
const { message } = App.useApp();
const { active, initialSearch, refreshKey, onLocationChange } = usePageCache();
const { active, initialSearch, refreshKey, onLocationChange, currentReleaseId } = usePageCache();
const baseView = SCOPE[page] || 'overall';
const [initialQuery] = useState(() => queryFromLocation(initialSearch));
const [viewOverrideState, setViewOverrideState] = useState<{ page: PageKey; view: ViewKind } | undefined>(() => initialQuery.view && initialQuery.view !== baseView ? { page, view: initialQuery.view } : undefined);
@@ -300,10 +294,10 @@ export default function QueryPage({ page, onUnauthorized }: {
const [options, setOptions] = useState<OptionsResponse | null>(null);
const [optionsError, setOptionsError] = useState('');
const [optionsLoading, setOptionsLoading] = useState(true);
const automaticPeriod = useRef(!initialQuery.year && !initialQuery.month && !initialQuery.quarter);
const automaticPeriod = useRef(page !== 'overall' && !initialQuery.year && !initialQuery.month && !initialQuery.quarter);
const defaultMonth = previousCompleteMonth();
const defaultQuarter = previousCompleteQuarter();
const [period, setPeriod] = useState<PeriodKind>(initialQuery.month ? 'month' : initialQuery.quarter ? 'quarter' : initialQuery.year ? 'year' : 'month');
const [period, setPeriod] = useState<PeriodKind>(initialQuery.month ? 'month' : initialQuery.quarter ? 'quarter' : initialQuery.year || page === 'overall' ? 'year' : 'month');
const [year, setYear] = useState(initialQuery.year || (period === 'month' ? defaultMonth.year : period === 'quarter' ? defaultQuarter.year : new Date().getFullYear()));
const [month, setMonth] = useState(initialQuery.month || defaultMonth.month);
const [quarter, setQuarter] = useState(initialQuery.quarter || defaultQuarter.quarter);
@@ -317,11 +311,13 @@ export default function QueryPage({ page, onUnauthorized }: {
const [search, setSearch] = useState(initialQuery.productSearch || '');
const [appliedSearch, setAppliedSearch] = useState(initialQuery.productSearch || '');
const [fullFields, setFullFields] = useState(false);
const [trendFullFields, setTrendFullFields] = useState(() => defaultFullMetricFields(page));
const [defectDisplay, setDefectDisplay] = useState<'weight' | 'rate'>('weight');
const [data, setData] = useState<MetricsResponse | null>(null);
const [dataKey, setDataKey] = useState('');
const [trendData, setTrendData] = useState<TrendMetricRow[]>([]);
const [trendDataKey, setTrendDataKey] = useState('');
const [trendFailure, setTrendFailure] = useState<{ key: string; message: string } | null>(null);
const [trendTarget, setTrendTarget] = useState<number | null>(null);
const [trendTargetKey, setTrendTargetKey] = useState('');
const [trendObject, setTrendObject] = useState('');
@@ -337,6 +333,7 @@ export default function QueryPage({ page, onUnauthorized }: {
const [error, setError] = useState('');
const [errorKey, setErrorKey] = useState('');
const [queryRevision, setQueryRevision] = useState(0);
const [trendRevision, setTrendRevision] = useState(0);
const [selectedRecord, setSelectedRecord] = useState<MetricRow | null>(null);
const [recordsOpen, setRecordsOpen] = useState(false);
const [recordStage, setRecordStage] = useState<Stage>('black');
@@ -358,8 +355,10 @@ export default function QueryPage({ page, onUnauthorized }: {
useEffect(() => {
if (!active) return;
let alive = true;
api.options().then(result => {
const controller = new AbortController();
api.options(controller.signal).then(result => {
if (!alive) return;
setOptions(result);
if (automaticPeriod.current) {
@@ -372,8 +371,8 @@ export default function QueryPage({ page, onUnauthorized }: {
if (onUnauthorized(errorValue)) return;
if (alive) setOptionsError(chooseError(errorValue));
}).finally(() => { if (alive) setOptionsLoading(false); });
return () => { alive = false; };
}, [onUnauthorized, queryRevision]);
return () => { alive = false; controller.abort(); };
}, [active, onUnauthorized, queryRevision]);
const allowedGroups = useMemo(() => {
const parents = new Set(department);
@@ -403,7 +402,7 @@ export default function QueryPage({ page, onUnauthorized }: {
if (product.length && !product.includes(exactProductSearch)) return [EMPTY_PRODUCT_SEARCH];
return [exactProductSearch];
}, [exactProductSearch, product]);
const queryParams = useMemo(() => toApiParams({ year, period, month, quarter, department, group, product: productFilterForQuery, productSearch: view === 'product' ? appliedSearch : undefined, projectGroup, extraFilters, view, includeUnassigned, trendGranularity }), [year, period, month, quarter, department, group, productFilterForQuery, appliedSearch, projectGroup, extraFilters, view, includeUnassigned, trendGranularity]);
const queryParams = useMemo(() => ({ ...toApiParams({ year, period, month, quarter, department, group, product: productFilterForQuery, productSearch: view === 'product' ? appliedSearch : undefined, projectGroup, extraFilters, view, includeUnassigned, trendGranularity }), releaseId: initialQuery.releaseId || currentReleaseId || undefined }), [year, period, month, quarter, department, group, productFilterForQuery, appliedSearch, projectGroup, extraFilters, view, includeUnassigned, trendGranularity, initialQuery.releaseId, currentReleaseId]);
const queryKey = useMemo(() => JSON.stringify(queryParams), [queryParams]);
const drilldownContextKey = JSON.stringify({ view, year, department, group, product, projectGroup, extraFilters, includeUnassigned });
useEffect(() => {
@@ -417,7 +416,6 @@ export default function QueryPage({ page, onUnauthorized }: {
const queryBusy = loading || queryPending;
const metricKeyRef = useRef(metricKey);
metricKeyRef.current = metricKey;
const useSummaryTrend = period === 'year' && !trendObject && trendGranularity === 'month';
const trendParams = useMemo<QueryParams>(() => {
const params = applyTrendObject(queryParams, trendObject, view);
delete params.month;
@@ -435,7 +433,7 @@ export default function QueryPage({ page, onUnauthorized }: {
if (!active) return;
const url = new URL(window.location.href);
if (!['overall', 'department', 'group', 'product'].includes(url.searchParams.get('page') || '')) return;
const bytes = new TextEncoder().encode(JSON.stringify({ query: queryParams }));
const bytes = new TextEncoder().encode(JSON.stringify({ query: queryForLocation(queryParams, initialQuery.releaseId) }));
let binary = '';
for (const byte of bytes) binary += String.fromCharCode(byte);
const context = btoa(binary).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
@@ -445,7 +443,7 @@ export default function QueryPage({ page, onUnauthorized }: {
}, [queryKey, active]);
useEffect(() => {
if (optionsLoading) return;
if (!active || optionsLoading || optionsError) return;
const controller = new AbortController();
setLoading(true);
setError('');
@@ -454,10 +452,6 @@ export default function QueryPage({ page, onUnauthorized }: {
if (controller.signal.aborted || metricKeyRef.current !== metricKey) return;
setData(result);
setDataKey(metricKey);
if (useSummaryTrend && trendKeyRef.current === trendKey) {
setTrendData(Array.isArray(result.trend) ? result.trend : []);
setTrendDataKey(trendKey);
}
setError('');
setErrorKey('');
}).catch(errorValue => {
@@ -467,9 +461,10 @@ export default function QueryPage({ page, onUnauthorized }: {
setErrorKey(metricKey);
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
return () => controller.abort();
}, [metricKey, queryRevision, onUnauthorized, optionsLoading]);
}, [active, metricKey, queryRevision, onUnauthorized, optionsLoading, optionsError]);
useEffect(() => {
if (!active) return;
if (!trendObject || defectQueryKey === queryKey) {
setTrendObjectMetrics(null);
setTrendObjectMetricsLoading(false);
@@ -488,28 +483,26 @@ export default function QueryPage({ page, onUnauthorized }: {
})
.finally(() => { if (!controller.signal.aborted) setTrendObjectMetricsLoading(false); });
return () => controller.abort();
}, [trendObject, defectQueryKey, queryKey, queryRevision, onUnauthorized]);
}, [active, trendObject, defectQueryKey, queryKey, queryRevision, onUnauthorized]);
useEffect(() => {
if (optionsLoading) return;
if (useSummaryTrend) {
setTrendLoading(false);
return;
}
if (!active || optionsLoading || optionsError) return;
setTrendFailure(null);
const controller = new AbortController();
setTrendLoading(true);
api.metrics(trendParams, controller.signal).then(result => {
if (trendKeyRef.current !== trendKey) return;
api.trend(trendParams, controller.signal).then(result => {
if (controller.signal.aborted || trendKeyRef.current !== trendKey) return;
setTrendData(Array.isArray(result.trend) ? result.trend : []);
setTrendDataKey(trendKey);
})
.catch(errorValue => {
if (!controller.signal.aborted && !onUnauthorized(errorValue)) message.error(`趋势加载失败:${chooseError(errorValue)}`);
if (!controller.signal.aborted && !onUnauthorized(errorValue)) setTrendFailure({ key: trendKey, message: chooseError(errorValue) });
}).finally(() => { if (!controller.signal.aborted) setTrendLoading(false); });
return () => controller.abort();
}, [trendKey, useSummaryTrend, queryRevision, onUnauthorized, message, optionsLoading]);
}, [active, trendKey, queryRevision, trendRevision, onUnauthorized, optionsLoading, optionsError]);
useEffect(() => {
if (!active || optionsLoading || optionsError) return;
let alive = true;
setTrendTarget(null);
setTrendTargetKey('');
@@ -528,10 +521,17 @@ export default function QueryPage({ page, onUnauthorized }: {
}
});
return () => { alive = false; };
}, [trendKey, queryRevision, onUnauthorized]);
}, [active, trendKey, queryRevision, trendRevision, onUnauthorized, optionsLoading, optionsError]);
const currentTrendTarget = trendTargetKey === trendKey ? trendTarget : null;
const visibleTrendData = useMemo(() => fullYearTrend(trendDataKey === trendKey ? trendData : [], year, trendGranularity), [trendData, trendDataKey, trendKey, year, trendGranularity]);
const currentTrendError = trendFailure?.key === trendKey ? trendFailure.message : '';
const trendRefreshing = !currentTrendError && (trendLoading || trendDataKey !== trendKey);
const showTrendLoading = useDelayedIndicator(trendRefreshing);
// 只在当前查询返回后替换画面;钻取等待期间保留上一次趋势和目标线。
const retainedTrend = useRetainedResult(trendDataKey === trendKey ? { rows: visibleTrendData, target: currentTrendTarget, query: trendParams } : null);
const renderedTrendData = retainedTrend?.rows || visibleTrendData;
const renderedTrendTarget = retainedTrend ? retainedTrend.target : currentTrendTarget;
const drilledTrendData = useMemo(
() => trendDataKey === trendKey ? visibleTrendData : fullYearTrend([], year, 'month'),
[trendDataKey, trendKey, visibleTrendData, year],
@@ -575,7 +575,7 @@ export default function QueryPage({ page, onUnauthorized }: {
view: drilledProduct ? 'overall' as const : view,
layoutView: drilledProduct ? 'product' as const : view,
period: drilledProduct ? 'year' as const : period,
year, month, quarter, drilledProduct,
year, month, quarter, drilledProduct, paginationScope: JSON.stringify({query:queryParams,drilledProduct,view}),
} : null);
const tableRows = retainedTable?.rows || [];
const tablePeriod = retainedTable?.period || period;
@@ -592,35 +592,9 @@ export default function QueryPage({ page, onUnauthorized }: {
}, []);
const selectTrendPeriod = useCallback((value: number | string) => {
automaticPeriod.current = false;
const raw = String(value);
const quarterMatch = raw.match(/^(\d{4})-Q([1-4])$/);
const yearMonth = raw.match(/^(\d{4})-(\d{1,2})$/);
const yearMatch = raw.match(/^(\d{4})$/);
if (quarterMatch) {
if (period === 'quarter' && year === Number(quarterMatch[1]) && quarter === Number(quarterMatch[2])) {
captureTrendAnchor(); setPeriod('year'); return;
}
if (period !== 'quarter' || year !== Number(quarterMatch[1]) || quarter !== Number(quarterMatch[2])) captureTrendAnchor();
setYear(Number(quarterMatch[1])); setQuarter(Number(quarterMatch[2])); setPeriod('quarter');
} else if (yearMonth) {
if (period === 'month' && year === Number(yearMonth[1]) && month === Number(yearMonth[2])) {
captureTrendAnchor(); setPeriod('year'); return;
}
if (period !== 'month' || year !== Number(yearMonth[1]) || month !== Number(yearMonth[2])) captureTrendAnchor();
setYear(Number(yearMonth[1])); setMonth(Number(yearMonth[2])); setPeriod('month');
} else if (yearMatch) {
if (period !== 'year' || year !== Number(yearMatch[1])) captureTrendAnchor();
setYear(Number(yearMatch[1])); setPeriod('year');
} else {
const selected = monthNumber(value);
if (selected) {
if (period === 'month' && month === selected) {
captureTrendAnchor(); setPeriod('year'); return;
}
if (period !== 'month' || month !== selected) captureTrendAnchor();
setPeriod('month'); setMonth(selected);
}
}
const next = nextTrendPeriod(value, { period, year, month, quarter });
if (next.period !== period || next.year !== year || next.month !== month || next.quarter !== quarter) captureTrendAnchor();
setYear(next.year); setMonth(next.month); setQuarter(next.quarter); setPeriod(next.period);
}, [period, year, month, quarter, captureTrendAnchor]);
useLayoutEffect(() => {
@@ -763,7 +737,7 @@ export default function QueryPage({ page, onUnauthorized }: {
<ExtraQueryFilters key={queryRevision} projectGroup={projectGroup} projectGroups={options?.projectGroupStatus === 'READY' ? options.projectGroups : undefined} onProjectGroup={setProjectGroup} value={extraFilters} onChange={setExtraFilters} onUnauthorized={onUnauthorized} />
<div className="query-toolbar-tail">
<span className={`query-status ${queryBusy || summaryBusy ? 'busy' : currentMetricsError || summaryMetricsError ? 'failed' : ''}`}><i />{queryBusy || summaryBusy ? '正在查询' : currentMetricsError || summaryMetricsError ? '查询失败' : '查询完成'}</span>
<Button type="default" onClick={() => { automaticPeriod.current = false; const previous = defaultQueryMonth(options); const previousQuarter = previousCompleteQuarter(); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod('month'); setTrendGranularity('month'); }}>重置</Button>
<Button type="default" onClick={() => { automaticPeriod.current = false; const previous = defaultQueryMonth(options); const previousQuarter = previousCompleteQuarter(); setViewOverride(); setDrilledProduct(''); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(page === 'overall' ? new Date().getFullYear() : previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod(page === 'overall' ? 'year' : 'month'); setTrendGranularity('month'); }}>重置</Button>
</div>
{organizationSummary.length > 0 && <div className="organization-breadcrumb" aria-label="当前组织路径">
<span>组织路径</span><Button type="link" onClick={() => { setDepartment([]); setGroup([]); setProduct([]); }}>全部组织</Button>
@@ -771,7 +745,7 @@ export default function QueryPage({ page, onUnauthorized }: {
</div>}
</section>
{currentMetricsError && <Alert showIcon type="error" message="质量指标查询失败" description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
{currentMetricsError && <Alert showIcon type="error" message={data ? "更新失败,当前显示上次结果" : "质量指标查询失败"} description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
{drilledProduct && summaryMetricsError && <Alert showIcon type="error" message="当前产品指标查询失败" description={summaryMetricsError} action={<Button size="small" onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
<section className={`metric-strip ${!displayedSummaryData ? 'query-awaiting-data' : ''}`} aria-label="质量指标" aria-busy={summaryBusy} inert={!summaryMetricsData}>
<div className="rate-basis-control"><Segmented size="small" value={rateBasis} options={[{ label: '原口径', value: 'original' }, { label: '去本部报废', value: 'withoutHeadquartersScrap' }]} onChange={value => setRateBasis(value as typeof rateBasis)} aria-label="合格率口径" /></div>
@@ -787,51 +761,39 @@ export default function QueryPage({ page, onUnauthorized }: {
<>
<div className="analysis-stack">
<section className="panel section-panel trend-panel" ref={trendSection} id={active ? 'monthly-trend' : undefined}>
<div className="section-heading-row trend-heading-row">
<SectionHeading title={`${trendGranularity === 'month' ? '月度' : trendGranularity === 'quarter' ? '季度' : '年度'}变化趋势`} />
<Segmented value={trendMode} options={[{ label: '合格率与产量', value: 'production' }, { label: '不良率', value: 'defects' }, { label: `${trendGranularity === 'quarter' ? '季度' : trendGranularity === 'year' ? '年度' : '月度'}数据`, value: 'data' }]} onChange={value => setTrendMode(value as typeof trendMode)} aria-label="趋势视图" />
</div>
<div className="trend-controls">
{trendMode==='data'&&<Segmented value={defectDisplay} options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={value=>setDefectDisplay(value as typeof defectDisplay)} aria-label="趋势不良显示方式"/>}
<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={trendGranularity} options={[{ label: '按月', value: 'month' }, { label: '按季度', value: 'quarter' }, { label: '按年度', value: 'year' }]} onChange={value => setTrendGranularity(value)} aria-label="趋势粒度" /></label>
<label className="query-field trend-object"><span>趋势对象</span><Select {...readableSelectPopup} allowClear placeholder={`当前${scopeName}筛选`} value={trendObject || undefined} options={trendOptions} onChange={setSynchronizedTrendObject} aria-label="趋势对象" />
</label>
{trendMode !== 'data' && <Segmented value={trendStage} options={[{ label: '亮片', value: 'bright' }, { label: '黑片', value: 'black' }]} onChange={value => setTrendStage(value as Stage)} aria-label="趋势阶段" />}
</div>
<div className="trend-chart-shell" aria-busy={trendLoading}>
<QueryTrendPanel panelRef={trendSection} id={active ? 'monthly-trend' : undefined}
mode={trendMode} onMode={setTrendMode} granularity={trendGranularity} onGranularity={setTrendGranularity}
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} fullFields={trendFullFields} onFullFields={setTrendFullFields}
object={trendObject} onObject={setSynchronizedTrendObject}
objects={trendOptions} scopeName={scopeName}
stageSwitch={<Segmented value={trendStage} options={[{ label: '亮片', value: 'bright' }, { label: '黑片', value: 'black' }]} onChange={value => setTrendStage(value as Stage)} aria-label="趋势阶段" />}>
{currentTrendError && <Alert type="warning" showIcon message={retainedTrend ? "趋势更新失败,当前显示上次结果" : "趋势读取失败"} description={retainedTrend ? `${currentTrendError};当前范围:${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : currentTrendError} action={<Button onClick={() => setTrendRevision(value => value + 1)}>重试</Button>} />}
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing || trendDataKey !== trendKey}>
{trendMode === 'data'
? <TrendTable rows={visibleTrendData} defectDisplay={defectDisplay} rateBasis={rateBasis} onMonth={selectTrendPeriod} />
: <TrendChart rows={visibleTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={currentTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
{(trendLoading || (useSummaryTrend && queryBusy)) && <span className="trend-refresh-indicator"><Spin size="small" />正在更新趋势</span>}
? <TrendTable rows={renderedTrendData} defectDisplay={defectDisplay} rateBasis={rateBasis} fullFields={trendFullFields} onMonth={selectTrendPeriod} />
: <TrendChart rows={renderedTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={renderedTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
{showTrendLoading && <span className="trend-refresh-indicator"><Spin size="small" />{retainedTrend ? `正在更新 · 当前显示上次筛选的${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : '正在读取趋势'}</span>}
</div>
<div className="chart-footnote"><span style={{ marginLeft: 'auto' }}>点击期间筛选,再次点击可取消</span></div>
</section>
</QueryTrendPanel>
<section className="panel section-panel table-panel">
<div className="section-heading-row">
<SectionHeading title={tableProduct ? '产品月度质量数据' : page === 'overall' ? `${tablePeriod === 'year' ? '年度月度' : tablePeriod === 'quarter' ? '季度' : '月度'}汇总` : `${scopeName}质量汇总`} subtitle={tableProduct ? `${retainedTable?.year || year} 年 · ${tableProduct} · 重量 / kg 合格率 / %` : '重量 / kg 合格率 / %'} />
<div className="table-tools">
{(queryBusy || !tableReady) && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}
<Input allowClear={!drilledProduct} disabled={Boolean(drilledProduct)} maxLength={view === 'product' ? 256 : undefined} prefix={<SearchOutlined />} placeholder={view === 'product' ? '输入关键词或完整产品名称' : `搜索${view === 'group' ? '业务分组' : '汇总对象'}`} value={drilledProduct || search} onChange={event => setSearch(event.target.value)} aria-label={view === 'product' ? '搜索产品名称并同步筛选指标和趋势' : '搜索汇总对象'} />
<Button type="primary" disabled={Boolean(drilledProduct)} onClick={() => applySearch()} aria-label="开始搜索">搜索</Button>
<Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整字段', value: 'full' }]} onChange={value => setFullFields(value === 'full')} aria-label="字段显示" />
<Segmented value={defectDisplay} options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={value=>setDefectDisplay(value as typeof defectDisplay)} aria-label="不良显示方式" />
{!drilledProduct && (view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else { setGroup([]); setDepartment([]); setViewOverride('department'); } }}>{view === 'product' ? '返回业务分组' : '返回产业部'}</Button>}
{drilledProduct && <Button onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回产品汇总</Button>}
<Button icon={<DownloadOutlined />} aria-label="Excel导出" loading={summaryExporting} disabled={queryBusy || summaryBusy || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length} onClick={async () => {
<QueryTablePanel
heading={<SectionHeading title={tableProduct ? '产品月度质量数据' : page === 'overall' ? `${tablePeriod === 'year' ? '年度月度' : tablePeriod === 'quarter' ? '季度' : '月度'}汇总` : `${scopeName}质量汇总`} subtitle={tableProduct ? `${retainedTable?.year || year} 年 · ${tableProduct} · 重量 / kg 合格率 / %` : '重量 / kg 合格率 / %'} />} busy={queryBusy || !tableReady}
search={drilledProduct || search} onSearchChange={setSearch} onSearch={() => applySearch()} productView={view === 'product'} searchPlaceholder={view === 'group' ? '搜索业务分组' : undefined} searchDisabled={Boolean(drilledProduct)}
fullFields={fullFields} onFullFields={setFullFields} defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay}
returnControls={<>{!drilledProduct && (view !== baseView || view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else if (view === 'group') { setGroup([]); setDepartment([]); setViewOverride('department'); } else { setViewOverride(); } }}>返回上一级</Button>}
{drilledProduct && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回上一级</Button>}</>}
exporting={summaryExporting} exportDisabled={queryBusy || summaryBusy || !tableReady || !summaryMetricsData || Boolean(drilledProduct && (trendLoading || currentTrendError)) || !(drilledProduct ? drilledTrendData : visibleRows).length}
onExport={async () => {
setSummaryExporting(true);
try { await summaryExport.current?.exportExcel(); }
catch (error) { message.error(`导出失败:${chooseError(error)}`); }
finally { setSummaryExporting(false); }
}}>Excel导出</Button>
</div>
</div>
<div className="mobile-scroll-hint">横向滑动查看完整指标</div>
}}>
<SmoothTableFrame busy={queryBusy || !tableReady} blocked={queryBusy || summaryBusy || !tableReady}>
<MetricTable
ref={summaryExport}
paginationScope={retainedTable?.paginationScope}
exportFilename={`${drilledProduct || scopeName}质量汇总-${year}${drilledProduct || period === 'year' ? '' : period === 'month' ? `-${String(month).padStart(2, '0')}` : `-Q${quarter}`}-${fullFields ? '完整字段' : '关键指标'}`}
rows={tableRows}
view={tableView}
@@ -862,7 +824,7 @@ export default function QueryPage({ page, onUnauthorized }: {
}}
/>
</SmoothTableFrame>
</section>
</QueryTablePanel>
<section className="panel section-panel defects-panel" ref={defectsSection} aria-busy={defectsRefreshing} style={{ minHeight: queryBusy && trendAnchorTop.current != null ? defectsHeight.current : undefined }}>
<div className="section-heading-row">
@@ -930,23 +892,15 @@ export function MetricCard({ primary, label, value, note, stage, onClick }: { pr
</button>;
}
export function DefectBreakdown({ items, stage, totalWeight, maximum, onDetail }: { items: DefectMetric[]; stage: Stage; totalWeight?: number | null; maximum: number; onDetail: () => void }) {
return <div className="defect-list">
<div className="defect-header"><span>不良分类</span><span aria-hidden="true" /><span>重量 / kg</span><span>占比</span><span>废率</span></div>
{items.map(item => <button className="defect-row" key={item.name} onClick={onDetail}>
<span className="defect-name">{item.name}</span>
<span className="defect-track"><i className={stage} style={{ width: `${maximum > 0 ? Math.max(0, (item.weight || 0) / maximum * 100) : 0}%` }} /></span>
<span className="defect-weight">{numberText(item.weight)}</span>
<span className="defect-rate">{rateText(item.rate)}</span>
<span className="defect-rate">{rateText(defectWeightRate(item.weight, totalWeight))}</span>
</button>)}
</div>;
export function DefectBreakdown({ items, stage, totalWeight, onDetail }: { items: DefectMetric[]; stage: Stage; totalWeight?: number | null; maximum: number; onDetail: () => void }) {
return <DefectComposition items={items} stage={stage} totalWeight={totalWeight} onDetail={onDetail} />;
}
export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthorized, onlyStage, refreshKey = 0, pending = false }: {
releaseId?: string; query: QueryParams; externalScrapWeight?: number | null; onUnauthorized: (error: unknown) => boolean; onlyStage?: Stage; refreshKey?: number; pending?: boolean;
}) {
const { active } = usePageCache();
const container = useRef<HTMLDivElement>(null);
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
const [responses, setResponses] = useState<{ black: FineDefectTopResponse; bright: FineDefectTopResponse; externalScrapWeight?: number | null } | null>(null);
@@ -967,8 +921,11 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
...(query.includeUnassigned ? { includeUnassigned: true } : {}),
}), [query.year, query.month, query.quarter, query.department, query.group, query.product, query.productSearch, query.projectGroup, query.extraFilters, query.columnFilters, query.includeUnassigned]);
const fineQueryKey = JSON.stringify(fineQuery);
const visible = useResourceVisibility(container, active);
const showLoading = useDelayedIndicator(loading);
useEffect(() => {
if (!active || !visible) return;
if (!releaseId) { setResponses(null); setLoading(false); setError(''); return; }
const controller = new AbortController();
const base = { releaseId, ...fineQuery, mode: 'top', dimension: 'defect', limit: 100 };
@@ -985,7 +942,7 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
})
.finally(() => { if (!controller.signal.aborted) setLoading(false); });
return () => controller.abort();
}, [releaseId, fineQueryKey, onUnauthorized, onlyStage, refreshKey, externalScrapWeight]);
}, [active, visible, releaseId, fineQueryKey, onUnauthorized, onlyStage, refreshKey, externalScrapWeight]);
useEffect(() => {
const refresh = () => setThemeRevision(value => value + 1);
@@ -998,13 +955,18 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
useEffect(() => {
const node = container.current;
if (!node) return;
const instance = echarts.init(node, undefined, { renderer: 'svg' });
if (!node || !active) return;
const instance = echarts.init(node, undefined, { renderer: 'svg', width: node.clientWidth, height: node.clientHeight });
chart.current = instance;
const observer = new ResizeObserver(() => instance.resize());
const observer = new ResizeObserver(() => {
const { clientWidth: width, clientHeight: height } = node;
if (width > 0 && height > 0 && (width !== instance.getWidth() || height !== instance.getHeight())) {
instance.resize({ width, height, animation: { duration: 0 } });
}
});
observer.observe(node);
return () => { observer.disconnect(); instance.dispose(); if (chart.current === instance) chart.current = null; };
}, []);
}, [active]);
const items = useMemo(() => {
if (!responses) return [];
@@ -1032,8 +994,8 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
const styles = getComputedStyle(container.current);
const ink = styles.getPropertyValue('--ink').trim() || '#222222';
const line = styles.getPropertyValue('--line').trim() || '#dfe5ef';
const blue = styles.getPropertyValue('--blue').trim() || '#607ae1';
const teal = styles.getPropertyValue('--teal').trim() || '#008f7d';
const black = styles.getPropertyValue('--defect-black').trim() || '#718797';
const bright = styles.getPropertyValue('--defect-bright').trim() || '#607AE1';
const surface = styles.getPropertyValue('--surface').trim() || '#ffffff';
let accumulated = 0;
const cumulative = items.map(item => {
@@ -1074,15 +1036,15 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
{ type: 'value', name: '累计占比', min: 0, max: 100, nameTextStyle: { color: ink, fontSize }, axisLabel: { color: ink, fontFamily: numericFamily, fontSize, formatter: '{value}%' }, splitLine: { show: false } },
],
series: [
{ id: 'pareto-weight', name: '报废重量', type: 'bar', z: 1, barMaxWidth: 36, data: items.map(item => ({ id: item.key, name: item.label, value: item.weight, itemStyle: { color: item.kind === 'category' ? '#9aa4b2' : item.key.startsWith('black:') ? blue : teal } })) },
{ id: 'pareto-weight', name: '报废重量', type: 'bar', z: 1, barMaxWidth: 36, itemStyle: { color: onlyStage === 'black' ? black : bright }, data: items.map(item => ({ id: item.key, name: item.label, value: item.weight, itemStyle: { color: item.kind === 'category' ? '#9aa4b2' : item.key.startsWith('black:') ? black : bright } })) },
{ id: 'pareto-cumulative', name: '累计占比', type: 'line', z: 10, yAxisIndex: 1, symbol: 'circle', symbolSize: 5, lineStyle: { width: 2, color: '#d58c35' }, itemStyle: { color: '#d58c35', borderColor: surface, borderWidth: 1 }, data: cumulative.map((value, index) => ({ id: items[index].key, name: items[index].label, value })) },
],
};
instance.setOption(option, { replaceMerge: ['series'], lazyUpdate: false });
}, [items, totalWeight, themeRevision]);
}, [items, totalWeight, themeRevision, active]);
return <section className="defect-pareto-section" aria-busy={loading || pending} aria-label={onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '综合报废重量柏拉图'}>
<div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong>{loading && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}</div>
<div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong>{showLoading && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}</div>
{error && <Alert showIcon type="warning" message="细分报废重量读取失败" description={error} />}
{!loading && !releaseId && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有已发布数据版本" />}
{!loading && !error && responses && !items.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前筛选下没有正值细分报废重量" />}
@@ -1111,17 +1073,15 @@ const totalWeightTitle = (label: string) => <span className="query-total-weight-
const rateBasisTitle = (label: string, basis: QueryRateBasis, kind: 'bright' | 'composite', onBasis?: () => void) => <span className="query-total-weight-title query-rate-rule-title"><span className="query-rate-label">{onBasis ? <button className="header-link" onClick={onBasis}>{label}</button> : label}{basis !== 'original' && <small className="query-rate-subtitle">(去本部报废)</small>}</span>{basis !== 'original' && <Tooltip trigger={['hover', 'focus']} title={<div>{kind === 'composite' && <>综合合格率=黑片合格率×亮片合格率。<br /></>}原口径:亮片合格重量÷亮片总重量。<br />去本部报废:(亮片合格重量+本部报废)÷亮片总重量,同时从亮片报废重量中扣除本部报废,总重量不变。<br />当前:去本部报废。计算结果以已发布数据版本及生效规则为准。</div>}><InfoCircleOutlined tabIndex={0} role="img" aria-label={`${kind === 'composite' ? '综合合格率' : '亮片合格率'}计算说明`} /></Tooltip>}</span>;
export function MetricTable({
ref, exportFilename, rows, view, layoutView = view, pageSizeOverride, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, onlyStage, defectDisplay = 'weight', emptyText = '当前条件下暂无数据',
ref, exportFilename, rows, view, layoutView = view, pageSizeOverride, paginationScope, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, onlyStage, defectDisplay = 'weight', emptyText = '当前条件下暂无数据',
}: {
ref?: React.Ref<{ exportExcel: () => Promise<void> }>; exportFilename: string;
rows: MetricRow[]; view: ViewKind; layoutView?: ViewKind; pageSizeOverride?: number; period: PeriodKind; month: number; quarter: number; fullFields: boolean;
rows: MetricRow[]; view: ViewKind; layoutView?: ViewKind; pageSizeOverride?: number; paginationScope?: string; period: PeriodKind; month: number; quarter: number; fullFields: boolean;
rateBasis: 'original' | 'withoutHeadquartersScrap';
onDetail: (row: MetricRow | null, stage: Stage, month?: number) => void; onBasis: () => void; onDrilldown: (row: MetricRow) => void;
emptyText?: string; onlyStage?: Stage; defectDisplay?: 'weight'|'rate';
}) {
const compact = useCompactTable();
const blackDefects = fullFields ? defectsFor(rows, 'black') : [];
const brightDefects = fullFields ? defectsFor(rows, 'bright') : [];
const isOverall = view === 'overall';
const title = (row: MetricRow) => isOverall && period === 'year'
? (monthNumber((row as TrendMetricRow).month) ? MONTHS[monthNumber((row as TrendMetricRow).month)! - 1] : row.label)
@@ -1151,16 +1111,21 @@ export function MetricTable({
return <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={defectDisplay === 'rate' ? rateText(defectWeightRate(value?.weight,stageValue(row,stage,'totalWeight'))) : numberText(value?.weight ?? null)} /></Button>;
},
}));
const brightDetailColumns: ColumnsType<MetricRow> = defectColumns('bright', brightDefects);
if (fullFields && rateBasis === 'original') {
const diffusionIndex = brightDetailColumns.findIndex(column => column.key === 'bright-defect-扩散废');
brightDetailColumns.splice(diffusionIndex < 0 ? brightDetailColumns.length : diffusionIndex + 1, 0,
numeric('本部报废', 'bright', 'headquartersScrapWeight'));
}
const fieldLabels: Record<MetricStageField, string> = {
totalWeight: '总重量', qualifiedWeight: '合格重量', scrapWeight: '报废重量',
headquartersScrapWeight: '本部报废', rate: '合格率',
};
const stageColumns = (stage: Stage): ColumnsType<MetricRow> => metricStageColumnPlan(rows, stage, fullFields, rateBasis).map(column => {
if (column.kind === 'defect') return defectColumns(stage, [column.name])[0];
const metricColumn = numeric(fieldLabels[column.field], stage, column.field);
return stage === 'bright' && column.field === 'rate'
? { ...metricColumn, render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={rateText(visibleStageRate(row, 'bright', rateBasis))} /></Button> }
: metricColumn;
});
const allColumns: ColumnsType<MetricRow> = [
{ title: isOverall ? period === 'year' ? '月份' : '统计期间' : view === 'group' ? '产业部 / 业务分组' : view === 'product' ? '产品规格' : view === 'projectGroup' ? '项目组' : view === 'department' ? '产业部' : '对象', key: 'object', dataIndex: 'label', fixed: 'left', width: compact ? isOverall ? 100 : 180 : isOverall ? 120 : layoutView === 'product' ? (fullFields ? 240 : 300) : layoutView === 'group' ? (fullFields ? 220 : 260) : (fullFields ? 180 : 220), render: (_: unknown, row) => <span className="object-cell">{view === 'department' || view === 'group' || view === 'product' ? <Button type="link" className="object-drilldown" style={{ userSelect: 'text', WebkitUserSelect: 'text' }} onClick={() => { if (window.getSelection()?.isCollapsed !== false) onDrilldown(row); }}>{title(row)} <span>›</span></Button> : <strong>{title(row)}</strong>}{view === 'group' && row.department && <small>{row.department}</small>}</span> },
{ key: 'stage-black', title: <span className="stage-heading black"><i />黑片</span>, children: [numeric('总重量', 'black', 'totalWeight'), numeric('合格重量', 'black', 'qualifiedWeight'), numeric('报废重量', 'black', 'scrapWeight'), ...defectColumns('black', blackDefects), numeric('合格率', 'black', 'rate')] },
{ key: 'stage-bright', title: <span className="stage-heading bright"><i />亮片</span>, children: [numeric('总重量', 'bright', 'totalWeight'), numeric('合格重量', 'bright', 'qualifiedWeight'), numeric('报废重量', 'bright', 'scrapWeight'), ...brightDetailColumns, { ...numeric('合格率', 'bright', 'rate'), render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={rateText(visibleStageRate(row, 'bright', rateBasis))} /></Button> }] },
{ key: 'stage-black', title: <span className="stage-heading black"><i />黑片</span>, children: stageColumns('black') },
{ key: 'stage-bright', title: <span className="stage-heading bright"><i />亮片</span>, children: stageColumns('bright') },
{ title: rateBasisTitle('综合合格率', rateBasis, 'composite', onBasis), key: 'compositeRate', dataIndex: 'compositeRate', align: 'center', fixed: compact ? undefined : 'right', width: 120, className: 'combined-column', render: (_: number | null, row: MetricRow) => <button className="combined-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={rateText(visibleCompositeRate(row, rateBasis))} /></button> },
{ title: '操作', key: 'actions', fixed: compact ? undefined : 'right', width: 96, align: 'center', render: (_: unknown, row) => (row as TrendMetricRow).noData ? <span>—</span> : <Button type="link" onClick={() => openRow(row, onlyStage || 'black')}>来源明细</Button> },
];
@@ -1182,9 +1147,9 @@ export function MetricTable({
const dataSource = rows.map((row, index) => ({ ...row, key: row.key || `${title(row)}-${index}` }));
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(SUMMARY_PAGE_SIZE);
const effectivePage = pageSizeOverride == null ? currentPage : 1;
const effectivePage = pageSizeOverride == null ? Math.min(currentPage, Math.max(1, Math.ceil(rows.length / pageSize))) : 1;
const effectivePageSize = pageSizeOverride ?? pageSize;
useEffect(() => setCurrentPage(1), [rows]);
useEffect(() => setCurrentPage(1), [paginationScope ?? rows]);
const columnWidth = (column: ColumnsType<MetricRow>[number]): number => {
if ('children' in column && column.children?.length) {
return column.children.reduce((total, child) => total + columnWidth(child), 0);
@@ -1196,7 +1161,7 @@ export function MetricTable({
const displayColumns = compact ? columns.flatMap(column => 'children' in column && column.children ? column.children : [column]) : columns;
const pageRows = dataSource.slice((effectivePage - 1) * effectivePageSize, effectivePage * effectivePageSize);
return <div className="metric-table-scroll"><Table<MetricRow> size="small" bordered tableLayout="fixed" columns={displayColumns} dataSource={pageRows} pagination={false} scroll={scroll} rowKey="key" locale={{ emptyText }} />
{pageSizeOverride == null && <MetricTablePagination current={currentPage} total={dataSource.length} pageSize={pageSize} onChange={(nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); }} />}
{pageSizeOverride == null && <MetricTablePagination current={effectivePage} total={dataSource.length} pageSize={pageSize} onChange={(nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); }} />}
</div>;
}
@@ -1212,7 +1177,9 @@ function trendBarWidth(chartWidth: number, count: number): number {
}
export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod, onMonth, onlyStage }: { rows: TrendMetricRow[]; mode: 'production' | 'defects'; stage: Stage; rateBasis: 'original' | 'withoutHeadquartersScrap'; targetRate: number | null; selectedPeriod?: string; onMonth: (value: number | string) => void; onlyStage?: Stage }) {
const { active } = usePageCache();
const container = useRef<HTMLDivElement>(null);
const visible = useResourceVisibility(container, active);
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
const onMonthRef = useRef(onMonth);
const rowsRef = useRef(rows);
@@ -1260,10 +1227,12 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
}, []);
useEffect(() => {
if (!container.current || !hasRows) return;
const instance = echarts.init(container.current, undefined, { renderer: 'svg' });
if (!container.current || !hasRows || !visible) return;
const instance = echarts.init(container.current, undefined, { renderer: 'svg', width: container.current.clientWidth, height: container.current.clientHeight });
chart.current = instance;
graphicIds.current.clear();
selectionReady.current = false;
setBarMasks([]);
instance.on('click', params => {
if (params.componentType !== 'series' && params.componentType !== 'xAxis') return;
const currentRows = rowsRef.current;
@@ -1278,8 +1247,9 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
const observer = new ResizeObserver(() => {
if (!container.current) return;
const { clientWidth, clientHeight } = container.current;
if (clientWidth <= 0 || clientHeight <= 0) return;
if (clientWidth !== instance.getWidth() || clientHeight !== instance.getHeight()) {
instance.resize();
instance.resize({ width: clientWidth, height: clientHeight, animation: { duration: 0 } });
if (modeRef.current === 'production') {
const barWidth = trendBarWidth(instance.getWidth(), rowsRef.current.length);
instance.setOption({ series: [{ id: 'qualified-weight', barWidth }, { id: 'scrap-weight', barWidth }] });
@@ -1289,7 +1259,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
});
observer.observe(container.current);
return () => { observer.disconnect(); instance.dispose(); chart.current = null; };
}, [hasRows, refreshBarMasks]);
}, [hasRows, refreshBarMasks, visible]);
useEffect(() => {
const instance = chart.current;
@@ -1301,10 +1271,13 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
const bars = trendBarPalette(getWorkspaceTheme(document.documentElement.dataset.workspaceTheme).id);
const barColor = bars.qualified;
const teal = css.getPropertyValue('--teal').trim() || '#008f7d';
const blackLine = css.getPropertyValue('--defect-black').trim() || '#718797';
const brightLine = css.getPropertyValue('--defect-bright').trim() || blue;
const line = css.getPropertyValue('--line').trim() || '#dfe5ef';
const surface = css.getPropertyValue('--surface').trim() || '#ffffff';
const labels = rows.map(row => row.periodLabel || String(row.month));
const barData = (field: 'qualifiedWeight' | 'scrapWeight') => rows.map(row => ({
id: String(row.period ?? row.month),
value: hasStageRows(row, stage) ? stageValue(row, stage, field, rateBasis) : null,
itemStyle: { color: field === 'qualifiedWeight'
? (String(row.period ?? row.month) === selectedPeriod ? bars.selectedQualified : bars.qualified)
@@ -1320,7 +1293,11 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
})].join('<br/>');
};
const base: echarts.EChartsCoreOption = {
animation: false,
animation: !window.matchMedia('(prefers-reduced-motion: reduce)').matches,
animationDuration: 520,
animationEasing: 'cubicOut',
animationDurationUpdate: 520,
animationEasingUpdate: 'cubicOut',
textStyle: { fontFamily, color: ink, fontSize },
grid: { left: 65, right: mode === 'production' ? 67 : 32, top: 70, bottom: 38 },
legend: { type: 'scroll', top: 0, left: 9, right: 9, itemWidth: 14, itemHeight: 7, itemGap: 20, textStyle: { color: ink, fontFamily, fontSize, fontWeight: 500 } },
@@ -1328,18 +1305,19 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
xAxis: { type: 'category', data: labels, triggerEvent: true, axisLine: { lineStyle: { color: line } }, axisLabel: { color: ink, fontFamily, fontSize, margin: 12 }, axisTick: { show: false } },
};
let option: echarts.EChartsCoreOption;
const pointStyle = { z: 10, symbol: 'circle', symbolSize: 5, showSymbol: true, emphasis: { focus: 'none' as const, scale: 1.35 }, connectNulls: false };
const pointStyle = { smooth: 0.15, smoothMonotone: 'x' as const, z: 10, symbol: 'circle', symbolSize: 5, showSymbol: true, emphasis: { focus: 'none' as const, scale: 1.35 }, connectNulls: false };
if (mode === 'production') {
const rates = [...rows.flatMap(row => [visibleCompositeRate(row, rateBasis), visibleStageRate(row, 'black'), visibleStageRate(row, 'bright', rateBasis)]).filter((value): value is number => value != null).map(value => value * 100), ...(targetRate == null ? [] : [targetRate])];
const minRate = rates.length ? Math.max(0, Math.floor(Math.min(...rates) - 2)) : 0;
const maxRate = rates.length ? Math.max(100, Math.ceil(Math.max(...rates) + 1)) : 100;
const stageName = stage === 'black' ? '黑片' : '亮片';
const barWidth = trendBarWidth(instance.getWidth(), rows.length);
const ratePoints = { ...pointStyle, symbol: 'emptyCircle', symbolSize: 6 };
const targetLine = targetRate == null ? {} : { markLine: {
silent: true,
symbol: 'none',
lineStyle: { color: '#c47a47', width: 1.5, type: 'dashed' as const },
label: { show: true, formatter: `综合率目标 ${targetRate.toFixed(2)}%`, position: 'insideEndTop' as const, color: '#a55d30', fontSize },
label: { show: true, formatter: `综合合格率目标 ${targetRate.toFixed(2)}%`, position: 'insideEndTop' as const, color: '#a55d30', fontSize },
data: [{ yAxis: targetRate }],
} };
option = {
@@ -1351,9 +1329,9 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
series: [
{ id: 'qualified-weight', name: `${stageName}合格重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: barColor }, emphasis: { itemStyle: { color: bars.hoverQualified } }, data: barData('qualifiedWeight') },
{ id: 'scrap-weight', name: `${stageName}报废重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: bars.scrap }, emphasis: { itemStyle: { color: bars.hoverScrap } }, data: barData('scrapWeight') },
{ id: 'composite-rate', name: '综合合格率', type: 'line', yAxisIndex: 1, ...pointStyle, ...targetLine, lineStyle: { width: 2.5, color: blue }, itemStyle: { color: blue, borderColor: surface, borderWidth: 1.5 }, data: rows.map(row => rateNumber(visibleCompositeRate(row, rateBasis))) },
{ id: 'black-rate', name: '黑片合格率', type: 'line', yAxisIndex: 1, ...pointStyle, lineStyle: { width: 1.8, color: '#9278bf' }, itemStyle: { color: '#9278bf', borderColor: surface, borderWidth: 1 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'black'))) },
{ id: 'bright-rate', name: '亮片合格率', type: 'line', yAxisIndex: 1, ...pointStyle, lineStyle: { width: 1.8, color: teal }, itemStyle: { color: teal, borderColor: surface, borderWidth: 1 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'bright', rateBasis))) },
{ id: 'composite-rate', name: '综合合格率', type: 'line', yAxisIndex: 1, ...ratePoints, ...targetLine, symbolSize: 7, emphasis: { ...pointStyle.emphasis, scale: 1.15 }, lineStyle: { width: 3.2, color: teal, cap: 'round', join: 'round' }, itemStyle: { color: teal, borderColor: teal, borderWidth: 2 }, data: rows.map(row => rateNumber(visibleCompositeRate(row, rateBasis))) },
{ id: 'black-rate', name: '黑片合格率', type: 'line', yAxisIndex: 1, ...ratePoints, lineStyle: { width: 2.6, color: blackLine, cap: 'round', join: 'round' }, itemStyle: { color: blackLine, borderColor: blackLine, borderWidth: 2 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'black'))) },
{ id: 'bright-rate', name: '亮片合格率', type: 'line', yAxisIndex: 1, ...ratePoints, lineStyle: { width: 2.6, color: brightLine, cap: 'round', join: 'round' }, itemStyle: { color: brightLine, borderColor: brightLine, borderWidth: 2 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'bright', rateBasis))) },
],
};
} else {
@@ -1371,7 +1349,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
}
instance.setOption(option, { replaceMerge: ['series', 'yAxis'], lazyUpdate: false });
refreshBarMasks();
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod]);
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod, active, visible]);
const dimmedPeriod = selectedPeriod === lineSelectedPeriod ? undefined : selectedPeriod;
@@ -1415,25 +1393,57 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
</div>;
}
function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight', showMonthLinks = true }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; defectDisplay?: 'weight'|'rate'; showMonthLinks?: boolean }) {
export function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight', onlyStage, fullFields = false }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; defectDisplay?: 'weight'|'rate'; onlyStage?: Stage; fullFields?: boolean }) {
const compact = useCompactTable();
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(SUMMARY_PAGE_SIZE);
useEffect(() => setCurrentPage(1), [rows]);
const stageLabel = (stage: Stage) => stage === 'black' ? '黑片' : '亮片';
const metricLabels: Record<MetricStageField, string> = {
totalWeight: '总重量', qualifiedWeight: '合格重量', scrapWeight: '报废重量',
headquartersScrapWeight: '本部报废', rate: '合格率',
};
const stageColumns = (stage: Stage): ColumnsType<TrendMetricRow> => metricStageColumnPlan(rows, stage, fullFields, rateBasis).map(column => {
const prefix = stageLabel(stage);
if (column.kind === 'defect') {
return {
title: `${prefix}${defectDisplay === 'rate' ? defectRateLabel(column.name) : column.name}${defectDisplay === 'rate' ? '' : ' / kg'}`,
key: `${stage}-defect-${column.name}`, align: 'center', width: fullFields ? 130 : 160,
render: (_: unknown, row: TrendMetricRow) => {
const value = row[stage].defects.find(item => item.name === column.name)?.weight ?? null;
return defectDisplay === 'rate' ? rateText(defectWeightRate(value, row[stage].totalWeight)) : numberText(value);
},
};
}
const field = column.field;
const baseLabel = `${prefix}${metricLabels[field]}`;
const title = field === 'totalWeight' && stage === 'black'
? totalWeightTitle(`${baseLabel} / kg`)
: field === 'rate' && stage === 'bright'
? rateBasisTitle(baseLabel, rateBasis, 'bright')
: `${defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? defectRateLabel(baseLabel) : baseLabel}${field === 'rate' || defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? '' : ' / kg'}`;
const width = field === 'rate' ? stage === 'bright' && rateBasis !== 'original' ? 194 : stage === 'black' ? 130 : 180 : fullFields ? 130 : 160;
return {
title, dataIndex: [stage, field], key: `${stage}-${field}`, align: 'center', width,
className: field === 'rate' ? `rate-cell ${stage}` : 'weight-cell',
render: (_: unknown, row: TrendMetricRow) => {
if (field === 'rate') return rateText(visibleStageRate(row, stage, stage === 'bright' ? rateBasis : 'original'));
if (field === 'scrapWeight') {
const value = queryScrapWeight(row[stage], stage, rateBasis);
return defectDisplay === 'rate' ? rateText(defectWeightRate(value, row[stage].totalWeight)) : numberText(value);
}
if (field === 'headquartersScrapWeight') {
const value = row.bright.headquartersScrapWeight ?? null;
return defectDisplay === 'rate' ? rateText(defectWeightRate(value, row.bright.totalWeight)) : numberText(value);
}
return numberText(row[stage][field]);
},
};
});
const columns: ColumnsType<TrendMetricRow> = [
{ title: '统计期间', dataIndex: 'month', key: 'month', align: 'center', fixed: 'left', width: 130, render: (_: unknown, row) => <Button type="link" onClick={() => onMonth(row.month)}>{row.periodLabel || String(row.month)}</Button> },
{ title: totalWeightTitle('黑片总重量 / kg'), dataIndex: ['black', 'totalWeight'], key: 'blackTotal', align: 'center', width: 160, render: value => numberText(value) },
{ title: '黑片合格重量 / kg', dataIndex: ['black', 'qualifiedWeight'], key: 'blackQualified', align: 'center', width: 160, render: value => numberText(value) },
{ title: defectDisplay === 'rate' ? '黑片报废率' : '黑片报废重量 / kg', dataIndex: ['black', 'scrapWeight'], key: 'blackScrap', align: 'center', width: 160, render: (_: unknown, row: TrendMetricRow) => defectDisplay === 'rate' ? rateText(defectWeightRate(row.black.scrapWeight,row.black.totalWeight)) : numberText(row.black.scrapWeight) },
{ title: '黑片合格率', dataIndex: ['black', 'rate'], key: 'blackRate', align: 'center', width: 130, className: 'rate-cell black', render: (_: number | null, row: TrendMetricRow) => rateText(visibleStageRate(row, 'black')) },
{ title: '亮片总重量 / kg', dataIndex: ['bright', 'totalWeight'], key: 'brightTotal', align: 'center', width: 160, render: value => numberText(value) },
{ title: '亮片合格重量 / kg', dataIndex: ['bright', 'qualifiedWeight'], key: 'brightQualified', align: 'center', width: 160, render: value => numberText(value) },
{ title: defectDisplay === 'rate' ? '亮片报废率' : '亮片报废重量 / kg', dataIndex: ['bright', 'scrapWeight'], key: 'brightScrap', align: 'center', width: 160, render: (_: unknown, row: TrendMetricRow) => defectDisplay === 'rate' ? rateText(defectWeightRate(queryScrapWeight(row.bright,'bright',rateBasis),row.bright.totalWeight)) : numberText(queryScrapWeight(row.bright,'bright',rateBasis)) },
{ title: rateBasisTitle('亮片合格率', rateBasis, 'bright'), dataIndex: ['bright', 'rate'], key: 'brightRate', align: 'center', width: rateBasis === 'original' ? 180 : 194, className: 'rate-cell bright', render: (_: number | null, row: TrendMetricRow) => rateText(visibleStageRate(row, 'bright', rateBasis)) },
...stageColumns('black'), ...stageColumns('bright'),
{ title: rateBasisTitle('综合合格率', rateBasis, 'composite'), dataIndex: 'compositeRate', key: 'compositeRate', align: 'center', width: 120, fixed: compact ? undefined : 'right', className: 'combined-column', render: (_: number | null, row: MetricRow) => rateText(visibleCompositeRate(row, rateBasis)) },
];
return rows.length ? <div className="metric-table-scroll trend-data-table"><Table size="small" bordered tableLayout="fixed" columns={columns} dataSource={rows} rowKey={row => String(row.month)} pagination={{ current: currentPage, pageSize, showSizeChanger: rows.length > SUMMARY_PAGE_SIZE, pageSizeOptions: SUMMARY_PAGE_SIZE_OPTIONS, showTotal: (total, range) => `显示 ${range[0]}–${range[1]} 行,共 ${total} 个月`, onChange: (nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); } }} scroll={{ x: columns.reduce((total, column) => total + Number(column.width || 0), 0) }} />
{showMonthLinks && <div className="trend-month-links">{rows.map(row => <Button key={row.key} type="link" onClick={() => onMonth(row.month)}>{row.periodLabel || row.month}汇总</Button>)}</div>}
const visibleColumns = onlyStage ? columns.filter(column => column.key === 'month' || String(column.key).startsWith(onlyStage)) : columns;
return rows.length ? <div className="metric-table-scroll trend-data-table"><Table size="small" bordered tableLayout="fixed" columns={visibleColumns} dataSource={rows} rowKey={row => String(row.month)} pagination={false} scroll={{ x: visibleColumns.reduce((total, column) => total + Number(column.width || 0), 0) }} />
</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前数据未返回趋势" />;
}
@@ -1444,7 +1454,7 @@ export function RecordsDrawer({
query: QueryParams; month?: number; onUnauthorized: (error: unknown) => boolean; lockedStage?: boolean;
}) {
const { message } = App.useApp();
const { refreshKey } = usePageCache();
const { active, refreshKey } = usePageCache();
const recordPages = useRef(new Map<string, RecordsResponse>());
const [page, setPage] = useState(1);
const [response, setResponse] = useState<{ key: string; data: RecordsResponse } | null>(null);
@@ -1469,14 +1479,16 @@ export function RecordsDrawer({
const result = response?.key === requestKey ? response.data : null;
const error = failure?.key === requestKey ? failure.message : '';
const fetching = loading || !result && !error;
const retainedResult = useRetainedResult(result);
const showRecordLoading = useDelayedIndicator(fetching && open);
useEffect(() => {
if (!open) return;
if (!open || !active) return;
const cached = recordPages.current.get(requestKey);
if (cached) { setResponse({ key: requestKey, data: cached }); setFailure(null); setLoading(false); return; }
const controller = new AbortController();
setLoading(true);
setResponse(null); setFailure(null);
setFailure(null);
api.records(requestParams, controller.signal).then(value => {
if (controller.signal.aborted) return;
const lastPage = Math.max(1, Math.ceil(value.total / value.pageSize));
@@ -1492,7 +1504,7 @@ export function RecordsDrawer({
if (!onUnauthorized(errorValue)) setFailure({ key: requestKey, message: chooseError(errorValue) });
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
return () => controller.abort();
}, [open, requestKey, revision, onUnauthorized]);
}, [open, active, requestKey, revision, onUnauthorized]);
const visibleRawFields = selectedColumns ?? rawFields.slice(0, 8);
const exportRecords = async () => {
@@ -1560,7 +1572,7 @@ export function RecordsDrawer({
];
return <Drawer className="source-records-drawer" open={open} onClose={onClose} width={Math.min(1120, window.innerWidth)} title={<div className="drawer-title">来源明细 <small>{row?.label || (month ? MONTHS[month - 1] : '当前筛选条件')}</small></div>} destroyOnClose>
<div className="drawer-controls"><Segmented disabled={lockedStage} value={stage} options={[{ label: '黑片', value: 'black' }, { label: '亮片', value: 'bright' }]} onChange={value => { onStage(value as Stage); setPage(1); setRawFields([]); setField(undefined); setFieldSearch(''); setSelectedColumns(undefined); setSort(undefined); }} aria-label="明细阶段" /><span>{result ? `共 ${result.total} 条来源记录 · 已载入 ${rawFields.length} 个原始字段` : '按当前查询条件获取原始来源行'}</span><Button size="small" icon={<DownloadOutlined />} loading={exporting} onClick={exportRecords} title={lockedStage ? '导出当前阶段和筛选范围的全部来源明细' : '导出当前查询范围全部来源明细,含黑片和亮片两个工作表'}>导出明细 Excel</Button></div>
<div className="drawer-controls"><Segmented disabled={lockedStage} value={stage} options={[{ label: '黑片', value: 'black' }, { label: '亮片', value: 'bright' }]} onChange={value => { onStage(value as Stage); setPage(1); setRawFields([]); setField(undefined); setFieldSearch(''); setSelectedColumns(undefined); setSort(undefined); }} aria-label="明细阶段" /><span>{result ? `共 ${result.total} 条来源记录 · 已载入 ${rawFields.length} 个原始字段` : '按当前查询条件获取原始来源行'}</span><Button size="small" icon={<DownloadOutlined />} loading={exporting} disabled={fetching || !result || !!error} onClick={exportRecords} title={lockedStage ? '导出当前阶段和筛选范围的全部来源明细' : '导出当前查询范围全部来源明细,含黑片和亮片两个工作表'}>导出明细 Excel</Button></div>
<div className="record-query-tools">
<label><span>字段检索</span><Select {...readableSelectPopup} allowClear showSearch optionFilterProp="label" placeholder="选择原始字段" value={field} options={rawFields.map(name => ({ label: name, value: name }))} onChange={value => { setField(value); setPage(1); }} /></label>
<Input allowClear disabled={!field} prefix={<SearchOutlined />} placeholder={field ? `搜索字段:${field}` : '先选择检索字段'} value={fieldSearch} onChange={event => { setFieldSearch(event.target.value); setPage(1); }} />
@@ -1572,8 +1584,11 @@ export function RecordsDrawer({
]} onChange={value => { setSort(value); setPage(1); }} /></label>
<Segmented value={direction} options={[{ label: '升序', value: 'asc' }, { label: '降序', value: 'desc' }]} onChange={value => { setDirection(value as 'asc' | 'desc'); setPage(1); }} aria-label="排序方向" />
</div>
{error && <Alert type="error" showIcon message="来源明细加载失败" description={error} action={<Button size="small" onClick={() => setRevision(value => value + 1)}>重试</Button>} />}
{fetching ? <div className="loading-panel"><Spin />正在读取来源行…</div> : result?.rows.length ? <Table size="small" bordered columns={fixedColumns} dataSource={result.rows} rowKey="id" pagination={false} scroll={{ x: 1800 + visibleRawFields.length * 180 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={error ? '来源记录加载失败' : '当前条件没有来源记录'} />}
{error && <Alert type="error" showIcon message={retainedResult ? "更新失败,当前显示上次结果" : "来源明细加载失败"} description={error} action={<Button size="small" onClick={() => setRevision(value => value + 1)}>重试</Button>} />}
{showRecordLoading && <div role="status">{retainedResult ? '正在更新,当前显示上次来源结果' : <><Spin size="small" />正在读取来源行…</>}</div>}
<div aria-busy={fetching} inert={!result || !!error}>
{retainedResult?.rows.length ? <Table size="small" bordered columns={fixedColumns} dataSource={retainedResult.rows} rowKey="id" pagination={false} scroll={{ x: 1800 + visibleRawFields.length * 180 }} /> : !fetching && !error && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前条件没有来源记录" />}
</div>
{result && result.total > result.pageSize && <Pagination className="records-pagination" current={page} pageSize={result.pageSize} total={result.total} showTotal={total => `共 ${total} 条`} onChange={next => setPage(next)} />}
</Drawer>;
}
+57
View File
@@ -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>;
}
+2 -2
View File
@@ -55,13 +55,13 @@ export function SmoothTableFrame({ children, busy, blocked }: { children: ReactN
useLayoutEffect(() => {
const node = content.current;
if (!node) return;
const measure = () => setHeight(node.offsetHeight);
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) setHeight(content.current.offsetHeight); }, [children]);
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>;
+91 -35
View File
@@ -1,71 +1,98 @@
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 { 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()]);if(automaticPeriod.current){const available=defaultQueryMonth(choices);setYear(available.year);setMonth(available.month);automaticPeriod.current=false;}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 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)=>{if(!applied)return;automaticPeriod.current=false;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=()=>{automaticPeriod.current=false;setApplied(draft);setRevision(v=>v+1);};
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 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 displayedQuery = displayed?.query || applied;
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);}};
@@ -74,19 +101,23 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
{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=>{automaticPeriod.current=false;setPeriod(v as PeriodKind);}}/>
<label className="query-field query-period-field"><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"><span>月份</span><Select aria-label="月份" value={month} onChange={v=>{automaticPeriod.current=false;setMonth(v);}} 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={v=>{automaticPeriod.current=false;setQuarter(v);}} options={[1,2,3,4].map(v=>({label:`第${v}季度`,value:v}))}/></label>}
<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)}/>
@@ -94,17 +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="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}/>}<div className="trend-chart-shell" aria-busy={trendLoading}>{trendMode==='data'?<MetricTable exportFilename={`${label}月度趋势-${year}`} rows={displayedTrend} 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={displayedTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod}/>}{trendLoading&&<span className="trend-refresh-indicator"><Spin size="small"/>正在更新趋势</span>}</div><div className="chart-footnote"><span>指标由来源分量汇总,使用当前生效公式。</span><span>点击期间筛选</span></div></section>
<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>
<SmoothTableFrame busy={loading||!current} blocked={!current||loading}><MetricTable ref={exporter} exportFilename={`${label}产品汇总-${year}`} rows={sortedRows} view="product" period={displayedQuery?.month?'month':displayedQuery?.quarter?'quarter':'year'} month={displayedQuery?.month||month} quarter={displayedQuery?.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);}}/></SmoothTableFrame>
</section>
<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="不良具体构成" subtitle={`${label} · 占比为分类报废内占比;废率为该类重量 ÷ 总重量`}/></div>
<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>
{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>
{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}/>}
+7 -2
View File
@@ -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));
+24 -15
View File
@@ -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}/> }] : []),
+9 -3
View File
@@ -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}}
+5 -1
View File
@@ -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 {
+13
View File
@@ -136,3 +136,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';
}
+69
View File
@@ -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 }));
}
+10 -3
View File
@@ -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('、')}),请重新打开这条分析后再导出。`);
}
}
+20 -4
View File
@@ -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
View File
@@ -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. */
+20
View File
@@ -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; } }
+26
View File
@@ -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 });
}
+17
View File
@@ -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 };
}
+35
View File
@@ -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;
}
+6 -1
View File
@@ -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. */
+35
View File
@@ -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(' · ');
}
+457
View File
@@ -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;
}
+12
View File
@@ -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));
}
+29
View File
@@ -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 };
}
+9 -4
View File
@@ -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); }
}
+17 -17
View File
@@ -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; }
@@ -78,7 +78,7 @@ button { color: inherit; }
.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; overflow-anchor: none; }
.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-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); }
}
+23
View File
@@ -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;
}
+8
View File
@@ -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;
+1 -1
View File
@@ -17,7 +17,7 @@
body, button, input, textarea, select { font-family: var(--font-ui); }
/* 查询区在既有缩放下保留可读正文,避免指标与明细的字号反差过大。 */
/* 查询区保留统一的可读正文,避免指标与明细的字号反差过大。 */
.query-page {
--font-control: 13px;
--font-table: 13px;
+48 -33
View File
@@ -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 };
}
+30
View File
@@ -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 };
}
+18
View File
@@ -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;
}
+20
View File
@@ -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]);
}
+76
View File
@@ -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();
},
};
}
+15 -7
View File
@@ -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; }
+1
View File
@@ -0,0 +1 @@
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>AI原文与运行状态验收</title></head><body><div id="root"></div><script type="module" src="./analysis-original.tsx"></script></body></html>
+43
View File
@@ -0,0 +1,43 @@
// Local acceptance fixture: all requests are intercepted; no model, API or database writes.
import React from 'react';
import {createRoot} from 'react-dom/client';
import {App,ConfigProvider} from 'antd';
import ManagementPages from '../src/ManagementPages';
import '../src/styles.css';
import '../src/workspace-finish.css';
const user={id:'original-fixture',username:'fixture',displayName:'本地验收',roles:['SYSTEM_ADMIN'],departments:[],groups:[]};
const modelAnswer='## 结论\n\n本期合格率下降,两个阶段的变化机制不同。完整模型正文必须保留。\n\n### 总体与阶段\n\n黑片合格率从97.58%降至97.27%,变化为 -0.30 pp。\n\n| 阶段 | 变化 |\n| --- | --- |\n| 黑片 | -0.30 pp |\n\n表格之后继续解释投入规模与报废规模,不能因为增加图表就丢掉这段。[Q11111111]\n\n### 下一步\n\n上述是统计线索,仍需现场核实生产原因。';
const loadingCase=new URLSearchParams(location.search).get('loadingCase');
if(loadingCase)history.replaceState({},'',`${location.pathname}?page=analysis&sessionId=fixture-session&loadingCase=${encodeURIComponent(loadingCase)}`);
let question=loadingCase?'为什么合格率下降?':'',status=loadingCase?'PARTIAL':'QUEUED',createdAt='',startedAt='',finishedAt='';let timeline:Record<string,unknown>[]=loadingCase?[{kind:'assistant',sequence:1,text:modelAnswer}]:[];
const visual={id:'stage-change',type:'column',title:'黑片合格率变化',subtitle:'',unit:'pp',metric:'rate_drop_pp',stage:'black',categories:[{key:'black',label:'黑片'}],series:[{key:'rateDrop',label:'合格率降幅',values:[.30]}],evidenceRefs:['Q11111111'],requiredFields:['black_good_weight','black_total_weight'],scope:{year:2026,month:9,releaseId:'fixture'},period:{year:2026,month:9},comparisonPeriod:{year:2026,month:8},originTurnId:'fixture-turn',coverage:{totalRows:1,returnedRows:1,truncated:false}};
const saved=()=>({id:'fixture-turn',sessionId:'fixture-session',question,status,createdAt,startedAt,finishedAt,executionMode:'native_agent',plan:{timeline},answer:'已取得本轮统计结果,答案整理尚未完整完成。',readingSummary:{version:1,lead:'已取得本轮统计结果,答案整理尚未完整完成。',evidence:[],notices:[],evidenceRefs:['Q11111111']},queryEvidenceRefs:['Q11111111'],visualSchemaVersion:1,visualState:'ready',visuals:[visual],stopReason:'evidence_incomplete'});
const json=(value:unknown)=>new Response(JSON.stringify(value),{headers:{'Content-Type':'application/json'}});
window.fetch=async(input,init)=>{
const path=new URL(String(input),location.origin).pathname;
if(path==='/api/auth/csrf')return json({token:'fixture'});
if(path==='/api/options'){if(loadingCase)await new Promise(r=>setTimeout(r,45000));return json({years:[2026],departments:[],groups:[],products:[],projectGroups:[]});}
if(path==='/api/analysis/sessions'&&init?.method==='POST'){await new Promise(r=>setTimeout(r,1500));return json({session:{id:'fixture-session'}});}
if(path==='/api/analysis/sessions'){if(loadingCase)await new Promise(r=>setTimeout(r,45000));return loadingCase==='error'?new Response('{}',{status:403}):json({items:question?[{id:'fixture-session',title:question,activeTurnStatus:status}]:[]});}
if(path==='/api/analysis/sessions/fixture-session/turns'&&init?.method==='POST'){
question=JSON.parse(String(init.body)).question;createdAt=new Date().toISOString();await new Promise(r=>setTimeout(r,300));return json({turn:{id:'fixture-turn',sessionId:'fixture-session',status,createdAt}});
}
if(path==='/api/analysis/sessions/fixture-session/turns')return json({items:[{id:'fixture-turn',status,createdAt,startedAt,finishedAt}]});
if(path==='/api/analysis/sessions/fixture-session'){if(loadingCase==='body')await new Promise(r=>setTimeout(r,30000));return json({id:'fixture-session',context:{year:2026},turns:status==='PARTIAL'?[saved()]:[]});}
if(path==='/api/analysis/turns/fixture-turn'||path.endsWith('/snapshot'))return json(saved());
if(path.endsWith('/events')){
const encoder=new TextEncoder();let closed=false;const timers:ReturnType<typeof setTimeout>[]=[];
const stream=new ReadableStream({start(controller){
let eventId=0;const send=(event:string,data:unknown)=>{if(!closed)controller.enqueue(encoder.encode(`id: ${++eventId}\nevent: ${event}\ndata: ${JSON.stringify(data)}\n\n`));};
send('progress',{status:'QUEUED'});
timers.push(setTimeout(()=>{status='RUNNING';startedAt=new Date().toISOString();send('progress',{status,message:'正在理解本轮目标和连续追问…'});},300));
timers.push(setTimeout(()=>{timeline=[{kind:'tool_start',sequence:1,tool:'read',toolCallId:'read-1',label:'核对正式指标',status:'running'}];send('tool_started',{timeline,step:timeline[0]});},800));
timers.push(setTimeout(()=>{timeline.push({kind:'tool_result',sequence:2,tool:'read',toolCallId:'read-1',label:'核对正式指标',status:'completed'});send('tool_completed',{timeline,step:timeline[1]});},6000));
timers.push(setTimeout(()=>{status='PARTIAL';finishedAt=new Date().toISOString();timeline.push({kind:'assistant',sequence:3,text:modelAnswer});send('partial',{status,result:saved()});if(!closed){closed=true;controller.close();}},30000));
init?.signal?.addEventListener('abort',()=>{if(!closed){closed=true;controller.close();}timers.forEach(clearTimeout);},{once:true});
},cancel(){closed=true;timers.forEach(clearTimeout);}});
return new Response(stream,{headers:{'Content-Type':'text/event-stream'}});
}
return json({items:[]});
};
createRoot(document.getElementById('root')!).render(<ConfigProvider><App><main style={{padding:18,maxWidth:1500,margin:'auto'}}><ManagementPages page="analysis" user={user} onUnauthorized={()=>false} onNavigate={()=>{}}/></main></App></ConfigProvider>);
@@ -0,0 +1,62 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import ts from 'typescript';
import React from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {analysisStreamStatus,analysisIsRunning,acceptAnalysisEvent,settledAnalysisTurn} from '../src/analysisConversationState.ts';
const source=fs.readFileSync(new URL('../src/ManagementPages.tsx',import.meta.url),'utf8');
const compile=code=>ts.transpileModule(code,{fileName:'status.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
const tick=()=>new Promise(resolve=>setImmediate(resolve));
const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return{promise,resolve};};
const isObjectRecord=v=>!!v&&typeof v==='object'&&!Array.isArray(v);
const finalStatuses=new Set(['COMPLETED','PARTIAL','FAILED','CANCELLED','NEEDS_CLARIFICATION']);
function fixture(){
let lastTurn={id:'t1',question:'q',status:'QUEUED',createdAt:'2026-11-02T01:00:00Z'},onEvent,reads=0;
const stream=deferred(),firstRead=deferred(),secondRead=deferred();
const env={mounted:{current:true},streamController:{current:null},subscriptionGeneration:{current:0},sessionId:'s1',eventCursors:{current:{}},ANALYSIS_FINAL_STATUSES:finalStatuses,
setLastTurn:next=>lastTurn=typeof next==='function'?next(lastTurn):next,writeAnalysisLocation(){},setActiveTurnId(){},setBusy(){},setRetryQuestion(){},setTurns(){},setError(){},loadSessions:async()=>{},onUnauthorized:()=>false,apiMessage:e=>e.message,
isObjectRecord,analysisStreamStatus,analysisIsRunning,acceptAnalysisEvent,settledAnalysisTurn,collectionItems:value=>value.items||[],modelThinkingEntries:()=>[],mergeModelThinking:()=>[]};
const api={analysisTurnEvents:async(_id,options)=>{onEvent=options.onEvent;return stream.promise;},analysisSessionTurns:()=>{reads++;return reads===1?firstRead.promise:secondRead.promise;}};
const code=source.slice(source.indexOf(' const followTurn = async'),source.indexOf('\n useEffect(() => {\n if (!active || restoreStarted.current)'));
const follow=new Function('api',...Object.keys(env),compile(code+'\nreturn followTurn;'))(api,...Object.values(env));
const work=follow('t1','q','s1');
return{get:()=>lastTurn,reads:()=>reads,switchTurn(){env.subscriptionGeneration.current++;lastTurn={id:'other',status:'RUNNING'};},emit(event,data){onEvent({id:String(Math.random()),event,data});},firstRead,secondRead,async close(){env.streamController.current?.abort();stream.resolve();await work;}};
}
test('tool step events keep the whole turn running and terminal status does not regress',()=>{
assert.equal(analysisStreamStatus('RUNNING','tool_started',undefined),'RUNNING');
assert.equal(analysisStreamStatus('RUNNING','tool_completed','completed'),'RUNNING');
assert.equal(analysisStreamStatus('RUNNING','completed','COMPLETED'),'COMPLETED');
assert.equal(analysisStreamStatus('COMPLETED','progress','RUNNING'),'COMPLETED');
});
test('actual event subscriber keeps status live and fills the server clock without re-entering',async()=>{
const ui=fixture();assert.equal(ui.reads(),1);
ui.emit('progress',{status:'RUNNING'});
ui.firstRead.resolve({items:[{id:'t1',createdAt:'2026-11-02T01:00:00Z',startedAt:''}]});await tick();
assert.equal(ui.reads(),2,'a running event during an initial queued timing read schedules one non-overlapping follow-up');
ui.secondRead.resolve({items:[{id:'t1',startedAt:'2026-11-02T01:00:05Z'}]});await tick();
ui.emit('tool_started',{step:{status:'running'}});
assert.equal(ui.get().status,'RUNNING');assert.equal(ui.get().startedAt,'2026-11-02T01:00:05Z');
ui.emit('tool_completed',{step:{status:'completed'}});assert.equal(ui.get().status,'RUNNING');
assert.equal(ui.reads(),2);await ui.close();
});
test('late timing metadata cannot update a different selected turn',async()=>{
const ui=fixture();ui.switchTurn();await ui.close();ui.firstRead.resolve({items:[{id:'t1',startedAt:'2026-11-02T01:00:05Z'}]});await tick();
assert.equal(ui.get().startedAt,undefined);
});
test('metadata renders a waiting clock immediately and a spinning running clock after server start',()=>{
const code=source.slice(source.indexOf('function AnalysisTurnMetadata('),source.indexOf('\nfunction isObjectRecord('));
const Metadata=new Function('React','useState','useEffect','analysisIsRunning','isObjectRecord','LoadingOutlined',compile(code+'\nreturn AnalysisTurnMetadata;'))(React,initial=>[initial,()=>{}],()=>{},analysisIsRunning,isObjectRecord,props=>React.createElement('i',props));
const now=Date.now();
const waiting=renderToStaticMarkup(React.createElement(Metadata,{turn:{_uiSubmittedAt:new Date(now-30000).toISOString()},status:'SUBMITTING',compact:true}));
assert.match(waiting,/提交中/);assert.match(waiting,/已等待 30秒/);
const running=renderToStaticMarkup(React.createElement(Metadata,{turn:{startedAt:new Date(now-10000).toISOString()},status:'RUNNING',compact:true}));
assert.match(running,/已运行 10秒/);assert.match(running,/analysis-runtime-spinner/);
});
test('partial remains a backend state without an extra partial label in conversation metadata',()=>{
const code=source.slice(source.indexOf('function AnalysisTurnMetadata('),source.indexOf('\nfunction isObjectRecord('));
const Metadata=new Function('React','useState','useEffect','analysisIsRunning','isObjectRecord','LoadingOutlined',compile(code+'\nreturn AnalysisTurnMetadata;'))(React,initial=>[initial,()=>{}],()=>{},analysisIsRunning,isObjectRecord,()=>null);
const html=renderToStaticMarkup(React.createElement(Metadata,{turn:{durationMs:6000},status:'PARTIAL',compact:true}));
assert.doesNotMatch(html,/部分完成/);assert.match(html,/运行时长 6秒/);
});
@@ -0,0 +1,77 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import ts from 'typescript';
import {analysisComposerState} from '../src/analysisScope.ts';
const source=fs.readFileSync(new URL('../src/ManagementPages.tsx',import.meta.url),'utf8');
const tick=()=>new Promise(resolve=>setImmediate(resolve));
const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return{promise,resolve};};
function restoreFixture({sessionId='',turnId='',link=false}={}){
const list=deferred(),opens=[];let effect,loading=true;
const env={active:true,restoreStarted:{current:false},mounted:{current:true},navigationGeneration:{current:0},initialSessionId:sessionId,initialTurnId:turnId,initialLink:{present:link},user:{id:'u'},
useEffect:fn=>{effect=fn;},setHistoryLoading:v=>{loading=v;},setSessions(){},setSessionsLoaded(){},setSessionsLoading(){},collectionItems:v=>v.items||[],
loadSessions:async()=>(await list.promise).items,api:{analysisSessions:()=>list.promise,analysisTurn:async()=>({sessionId:'linked-session'})},defaultAnalysisSession:(_u,items)=>items[0]?.id,
openSession:async(...args)=>{opens.push(args);loading=false;return true;},onUnauthorized:()=>false,setError(){},apiMessage:e=>e.message};
const marker=' useEffect(() => {\n if (!active || restoreStarted.current)';const start=source.indexOf(marker);const end=source.indexOf('\n useEffect(() => {',start+marker.length);
const code=ts.transpileModule(source.slice(start,end),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
new Function(...Object.keys(env),code)(...Object.values(env));effect();
return{list,opens,get loading(){return loading;}};
}
test('an explicit history link loads its body without waiting for the unrelated session list',async()=>{
const ui=restoreFixture({sessionId:'requested-session'});await tick();assert.deepEqual(ui.opens,[['requested-session',undefined]]);
ui.list.resolve({items:[]});await tick();
});
test('a turn link can resolve its session while the session list is still pending',async()=>{
const ui=restoreFixture({turnId:'requested-turn'});await tick();assert.deepEqual(ui.opens,[['linked-session','requested-turn']]);
ui.list.resolve({items:[]});await tick();
});
test('default history selection still waits for the list before choosing a session',async()=>{
const ui=restoreFixture();await tick();assert.equal(ui.opens.length,0);ui.list.resolve({items:[{id:'recent'}]});await tick();assert.deepEqual(ui.opens,[['recent',undefined]]);
});
function listFixture(){
const read=deferred();let reads=0,state={busy:false,loaded:false,items:[],error:''};
const env={mounted:{current:true},active:true,sessionReadRequest:{current:null},setSessionsLoading:v=>{state.busy=v;},setSessions:v=>{state.items=v;},setSessionsLoaded:v=>{state.loaded=v;},setSessionsError:v=>{state.error=v;},onUnauthorized:()=>false,apiMessage:e=>e.message,collectionItems:v=>v.items||[],api:{analysisSessions:()=>{reads++;return read.promise;}}};
const start=source.indexOf(' const loadSessions = async');const end=source.indexOf('\n const retrySessions =',start);
const code=ts.transpileModule(source.slice(start,end)+'\nreturn loadSessions;',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
return{read,state,reads:()=>reads,load:new Function(...Object.keys(env),code)(...Object.values(env))};
}
test('session-list reads are shared, and failure stays within the list resource',async()=>{
const ui=listFixture();const a=ui.load(),b=ui.load();assert.equal(ui.reads(),1);assert.equal(ui.state.busy,true);
ui.read.resolve({items:[{id:'recent'}]});assert.deepEqual(await a,[{id:'recent'}]);await b;assert.equal(ui.state.loaded,true);assert.equal(ui.state.busy,false);
ui.read.resolve({items:[]});
});
test('a failed list read ends its own loading state and cannot masquerade as an empty successful list',async()=>{
const ui=listFixture();const work=ui.load();ui.read.resolve(Promise.reject(new Error('list unavailable')));assert.equal(await work,undefined);
assert.equal(ui.state.busy,false);assert.equal(ui.state.loaded,false);assert.equal(ui.state.error,'list unavailable');
});
test('ordinary and explicit historical conversations never download the unused options resource',()=>{
const start=source.indexOf(' useEffect(() => {\n if (!active || !initialLink.present');assert.notEqual(start,-1);
const end=source.indexOf('\n\n',start);const code=ts.transpileModule(source.slice(start,end),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
for(const [present,session,turn] of [[false,'',''],[false,'s',''],[true,'s',''],[true,'','t']]){
let reads=0;const env={useEffect:fn=>fn(),active:true,initialLink:{present},initialSessionId:session,initialTurnId:turn,optionsRequestStarted:{current:false},optionsRead:{run:()=>{reads++;}},onUnauthorized:()=>false};
new Function(...Object.keys(env),code)(...Object.values(env));assert.equal(reads,0);
}
});
function retryFixture(sessionId='',turnId=''){
const list=deferred(),opens=[],navigationGeneration={current:0},state={historyLoading:false};
const env={sessionId,navigationGeneration,pendingTurnLink:{current:turnId},mounted:{current:true},initialLink:{present:false},user:{id:'u'},setHistoryLoading:v=>{state.historyLoading=v;},loadSessions:()=>list.promise,api:{analysisTurn:async()=>({sessionId:'target-session'})},openSession:async(id,focus)=>opens.push([id,focus]),defaultAnalysisSession:(_u,items)=>items[0]?.id,onUnauthorized:()=>false,setError(){},apiMessage:e=>e.message};
const start=source.indexOf(' const retrySessions = async');const end=source.indexOf('\n useEffect(',start);
const code=ts.transpileModule(source.slice(start,end)+'\nreturn retrySessions;',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
return{list,opens,state,navigationGeneration,retry:new Function(...Object.keys(env),code)(...Object.values(env))};
}
test('retrying a linked history does not wait for a slow list',async()=>{
const ui=retryFixture('selected');await ui.retry();assert.deepEqual(ui.opens,[['selected',undefined]]);ui.list.resolve([]);
});
test('default-list retry cannot navigate over a newer user selection',async()=>{
const ui=retryFixture();const work=ui.retry();ui.navigationGeneration.current++;ui.list.resolve([{id:'old-default'}]);await work;assert.deepEqual(ui.opens,[]);
});
test('retry of a turn-only link re-resolves the requested turn instead of opening an unrelated default',async()=>{
const ui=retryFixture('','requested-turn');ui.list.resolve([{id:'unrelated-default'}]);await ui.retry();assert.deepEqual(ui.opens,[['target-session','requested-turn']]);
});
test('default-history retry locks sending until its target resolves, so a late list cannot replace a new submission',async()=>{
const ui=retryFixture();const work=ui.retry();assert.equal(ui.state.historyLoading,true);
assert.equal(analysisComposerState(false,false,ui.state.historyLoading,'新问题').sendDisabled,true);
ui.list.resolve([{id:'default'}]);await work;assert.equal(ui.state.historyLoading,false);
});
@@ -0,0 +1,44 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { originalAnalysisBody, originalAnalysisSections } from '../src/analysisOriginalBody.ts';
const original='## 结论\n\n合格率下降来自两个不同的阶段。\n\n### 总体与阶段\n\n先说明投入规模。\n\n| 阶段 | 变化 |\n| --- | --- |\n| 黑片 | -0.30 pp |\n\n表格之后的完整解释不能挪走。[Q11111111]\n\n### 组织维度\n\n国内与海外结构不同。\n\n### 局限\n\n不能据此认定生产根因。';
const legacy=()=>({status:'PARTIAL',result:{executionMode:'native_agent',answer:'已取得本轮统计结果,答案整理尚未完整完成。\n\n正式统计表',readingSummary:{lead:'已取得本轮统计结果,答案整理尚未完整完成。'}},plan:{timeline:[{kind:'assistant',text:'先进行查询。'},{kind:'tool_start',sequence:1},{kind:'tool_result',sequence:2},{kind:'assistant',sequence:3,text:original}]}});
test('legacy native fallback restores the entire final model body instead of another summary',()=>{
const body=originalAnalysisBody(legacy());assert.equal(body.source,'timeline');assert.equal(body.answer,original);
assert.doesNotMatch(body.answer,/已取得本轮统计结果/);
});
test('new saved original body wins over an 8000-character transcript and remains complete',()=>{
const data=legacy();const answer='正文'.repeat(6000);data.result.answer=answer;delete data.result.readingSummary;
data.plan.timeline.at(-1).text=answer.slice(0,8000)+'…';assert.equal(originalAnalysisBody(data).answer,answer);
});
test('a capped historical transcript cannot masquerade as the complete original body',()=>{
const data=legacy();data.plan.timeline.at(-1).text='原'.repeat(8000);
assert.deepEqual(originalAnalysisBody(data),{answer:'',source:'unavailable'});
});
test('a failed native result with no formal evidence still renders its saved original body',()=>{
assert.deepEqual(originalAnalysisBody({status:'FAILED',result:{executionMode:'native_agent',answer:original,results:[],answerQuality:{dataComplete:false}}}),{answer:original,source:'saved'});
});
test('earlier assistant progress, redacted answers, and unavailable originals are never promoted',()=>{
const data=legacy();data.plan.timeline.pop();assert.deepEqual(originalAnalysisBody(data),{answer:'',source:'unavailable'});
data.result.answer='';data.plan.timeline.push({kind:'assistant',text:original});assert.equal(originalAnalysisBody(data).answer,'');
delete data.result.executionMode;assert.equal(originalAnalysisBody(data),null);
});
test('original Markdown lines, table placement and scope caveats stay in their exact order',()=>{
const parts=originalAnalysisSections(original,[]);assert.equal(parts.map(p=>p.markdown).join('\n'),original);
assert.ok(parts[1].markdown.indexOf('| 黑片')<parts[1].markdown.indexOf('表格之后'));
assert.match(parts.at(-1).markdown,/不能据此认定生产根因/);
});
test('figures are inserted after the associated complete chapter without removing prose or tables',()=>{
const visual={id:'stage',title:'阶段合格率',metric:'black_rate',type:'column',evidenceRefs:['Q11111111']};
const sections=originalAnalysisSections(original,[visual]);assert.equal(sections[1].visuals[0],visual);
assert.equal(sections.flatMap(s=>s.visuals).length,1);assert.equal(sections.map(s=>s.markdown).join('\n'),original);
});
test('alternate historical evidence fallback also recovers native prose',()=>{
const data=legacy();data.result.readingSummary.lead='现有证据不足以支持本轮完整分析,已保留可核验统计结果。';assert.equal(originalAnalysisBody(data).answer,original);
});
test('black and bright figures cannot be attached to the opposite stage chapter',()=>{
const body='## 黑片阶段\n\n黑片完整解释。\n\n## 亮片阶段\n\n亮片完整解释。';
const figures=[{id:'black',type:'column',stage:'black',metric:'black_rate',evidenceRefs:[]},{id:'bright',type:'column',stage:'bright',metric:'bright_rate',evidenceRefs:[]}];
const sections=originalAnalysisSections(body,figures);assert.equal(sections[0].visuals[0].id,'black');assert.equal(sections[1].visuals[0].id,'bright');
});
@@ -274,17 +274,17 @@ test('history proof and lineage in model-controlled task fields cannot authorize
assert.deepEqual(selectedHistoryIds(turn), []);
});
test('running process starts folded, stays open after a user opens it, closes on completion, and ignores late running status', () => {
test('running process starts open, honors manual collapse, and closes on completion', () => {
const harness = hookHarness();
const turn = { id: 'process-turn', status: 'RUNNING', steps: [{ tool: 'read', label: '读取数据', status: 'running' }] };
let element = harness.render(turn);
assert.equal(element.type, 'details');
assert.equal(element.props.open, false);
assert.equal(element.props.open, true);
element.props.onToggle({ currentTarget: { open: true } });
element.props.onToggle({ currentTarget: { open: false } });
turn.steps = [...turn.steps, { tool: 'mcp_call', label: '查询质量数据', status: 'running' }];
element = harness.render(turn);
assert.equal(element.props.open, true);
assert.equal(element.props.open, false);
turn.status = 'COMPLETED';
turn.steps = [...turn.steps, { tool: 'mcp_call', label: '查询质量数据', status: 'completed' }];
@@ -293,5 +293,5 @@ test('running process starts folded, stays open after a user opens it, closes on
turn.status = 'RUNNING';
element = harness.render(turn);
assert.equal(element.props.open, false);
assert.equal(element.props.open, true);
});
+7 -3
View File
@@ -1,3 +1,4 @@
import { originalAnalysisBody, originalAnalysisSections } from '../src/analysisOriginalBody.ts';
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
@@ -22,7 +23,9 @@ const turn = (readingSummary = summary()) => ({ id: 'turn', question: '9月合
releaseId: 'release', visuals: [chart], queryEvidenceRefs: ['Q11111111', 'Q22222222'], readingSummary,
} });
let OriginalContent=()=>null;
function component(source, name, bindings) {
bindings={originalAnalysisBody,AnalysisOriginalContent:props=>React.createElement(OriginalContent,props),...bindings};
const cleaned = source.replace(/^import .*;\n/gm, '').replace(/^export /gm, '');
return new Function('React', ...Object.keys(bindings), ts.transpileModule(`${cleaned}\nreturn ${name};`, {
fileName: `${name}.tsx`, compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React },
@@ -30,6 +33,7 @@ function component(source, name, bindings) {
}
const markdownSource = readFileSync(new URL('../src/AiMarkdown.tsx', import.meta.url), 'utf8');
const AiMarkdown = component(markdownSource, 'AiMarkdown', { sanitizeAnalysisDisplayText, analysisEvidenceParts });
OriginalContent=component(readFileSync(new URL('../src/AnalysisOriginalContent.tsx',import.meta.url),'utf8'),'AnalysisOriginalContent',{AiMarkdown,originalAnalysisSections});
test('conclusion layout separates the lead, findings and table titles without rewriting checked facts', () => {
const content = '9月综合合格率**95.13%**,较8月的**95.57%**下降**0.44个百分点**。主要来自**黑片阶段**,正式影响为**-0.30个百分点**;亮片影响**-0.15个百分点**。\n\n'
@@ -81,7 +85,7 @@ const visibleSummary = html => html.match(/<div class="ai-markdown[^"]*">([\s\S]
test('comparison readout uses the checked change, preserving rounded stage values and explicit scope', () => {
const sentence='汽车交通2026年9月黑片合格率**97.27%**,较8月的**97.58%**下降**0.30个百分点**。';
const value=checkedConclusionComparison(sentence);
assert.equal(value.change,'0.30'); assert.equal(value.currentLabel,'汽车交通2026年9月');
assert.equal(value.change,'-0.30'); assert.equal(value.currentLabel,'汽车交通2026年9月');
assert.equal(value.previousLabel,'8月'); assert.equal(value.current,'97.27%'); assert.equal(value.previous,'97.58%');
for (const invalid of ['9月合格率95.13%。','9月合格率95.13%,较8月95.57%。','9月合格率101.00%,较8月95.57%下降0.44个百分点。']) assert.equal(checkedConclusionComparison(invalid),null);
assert.equal(checkedConclusionComparison('9月合格率0.00%,较8月95.57%下降95.57个百分点。').current,'0.00%');
@@ -93,7 +97,7 @@ test('conclusion chapters put each authorized figure beside its cited topic, wit
'**重点规格**:甲规格报废增加128.45 kg。[Q11111111]']});
const figures=[{...chart,id:'department',metric:'rate_drop_pp',dimension:'department',evidenceRefs:['Q22222222']},{...chart,id:'product',metric:'scrap_delta',dimension:'product'}];
const document=buildConclusionDocument(buildAnalysisReadingModel('',[],data.question,data).reading,figures);
assert.equal(document.comparison.change,'0.44');
assert.equal(document.comparison.change,'-0.44');
assert.deepEqual(document.sections.find(x=>x.title==='产业部变化').visuals.map(v=>v.id),['department']);
assert.deepEqual(document.sections.find(x=>x.title==='重点规格').visuals.map(v=>v.id),['product']);
assert.deepEqual(document.sections.flatMap(x=>x.visuals.map(v=>v.id)),['department','product']);
@@ -109,7 +113,7 @@ test('reference-style cards and chapters keep chat/report values, figures and or
data.result.answer=data.result.readingSummary.lead+'\n\n'+data.result.readingSummary.evidence[0];
for(const html of [renderChat(data),renderReport(data)]) {
assert.match(html,/analysis-comparison-current[^>]*><span>2026年9月<\/span><strong>95.13%<\/strong>/);
assert.match(html,/下降 0.44/); assert.match(html,/95.57%/);
assert.match(html,/-0.44/); assert.match(html,/95.57%/);
assert.equal((html.match(/<table>/g)||[]).length,1);
assert.doesNotMatch(html,/Q11111111|Q22222222|关键依据|数据依据|analysis-full-appendix/);
}
+4 -3
View File
@@ -158,10 +158,10 @@ test('settled process is collapsed, with the original records retained inside',(
assert.doesNotMatch(html,/<details class="analysis-process-history analysis-agent-process" open/);
}
});
test('running process stays folded by default while retaining its current records inside',()=>{
test('running process is expanded by default while retaining its current records inside',()=>{
const html=renderToStaticMarkup(React.createElement(Process,{turn:processTurn('RUNNING')}));
assert.match(html,/读取数据/);assert.match(html,/<details class="analysis-process-history analysis-agent-process"/);
assert.doesNotMatch(html,/<details class="analysis-process-history analysis-agent-process" open/);
assert.match(html,/<details class="analysis-process-history analysis-agent-process" open/);
});
test('a submitted follow-up rearms following only when its own turn is rendered',()=>{
@@ -329,7 +329,8 @@ test('agent process interleaves thoughts, tool calls and text with one runtime h
]};
const html=renderToStaticMarkup(React.createElement(Process,{turn,metadata:React.createElement('span',null,'运行时长 25秒')}));
assert.equal((html.match(/运行时长/g)||[]).length,1);
const positions=['先核对范围','我来查询两个期间。','读取数据','再整理结果'].map(value=>html.indexOf(value));
assert.doesNotMatch(html,/我来查询两个期间。/);
const positions=['先核对范围','读取数据','再整理结果'].map(value=>html.indexOf(value));
assert.ok(positions.every((p,i)=>p>=0&&(!i||p>positions[i-1])));
assert.equal((html.match(/class="analysis-thinking-block"/g)||[]).length,2);
for(const hidden of ['model-hidden','任务理解','整理结论','analysis-thinking-heading','展示接口实际返回'])assert.ok(!html.includes(hidden),hidden);
+18 -2
View File
@@ -182,7 +182,7 @@ test('unknown 503 submission renders recovery notice without claiming a queued o
await ui.submit('question with unknown outcome');
assert.equal(ui.get().attempt.uncertain,true);
const html=renderDraft(ui.get().lastTurn);
assert.match(html,/提交结果暂未确认,请重试上一问恢复原任务/);
assert.doesNotMatch(html,/提交结果暂未确认/);
assert.doesNotMatch(html,/排队中|正在准备分析|仍在运行/);
assert.equal(ui.get().lastTurn.status,undefined);
});
@@ -192,7 +192,23 @@ test('an explicit 400 rejection renders an unsuccessful draft without a running
await ui.submit('rejected question');
assert.equal(ui.get().attempt,null);
const html=renderDraft(ui.get().lastTurn);
assert.match(html,/本次提交未成功,请检查错误提示后重试/);
assert.doesNotMatch(html,/本次提交未成功/);
assert.doesNotMatch(html,/排队中|正在准备分析|仍在运行|恢复原任务/);
assert.equal(ui.get().lastTurn.status,undefined);
});
test('a fresh submission immediately carries waiting status and a clock before acceptance',async()=>{
const pending=deferred();const ui=fixture({startAnalysisTurn:()=>pending.promise});
const work=ui.submit('即时状态');assert.equal(ui.get().lastTurn.status,'SUBMITTING');
assert.ok(Number.isFinite(Date.parse(ui.get().lastTurn._uiSubmittedAt)));
pending.resolve({turn:{id:'accepted',status:'RUNNING'}});await work;
assert.ok(Number.isFinite(Date.parse(ui.get().lastTurn._uiSubmittedAt)));
});
test('retry starts a fresh waiting clock without displaying the old body or plan clock',async()=>{
const response=deferred();const ui=fixture({retryAnalysisTurn:()=>response.promise,analysisTurn:async()=>({id:'old',status:'QUEUED'})});
const work=ui.retryTurn({id:'old',status:'PARTIAL',answer:'old text',createdAt:'2020-01-01T00:00:00Z',startedAt:'2020-01-01T00:00:01Z',plan:{startedAt:'2020-01-01T00:00:01Z'}});
assert.equal(ui.get().lastTurn.status,'SUBMITTING');assert.equal(ui.get().lastTurn.answer,undefined);assert.equal(ui.get().lastTurn.plan,undefined);
response.resolve({turn:{id:'old',sessionId:'session-1',status:'QUEUED'}});await work;
});
@@ -28,11 +28,19 @@ function fixture({ authorize=async()=>{}, load }={}) {
useCallback(fn){cursor++;return fn;},
useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))queued.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});},
};
hooks.useDelayedIndicator=(active,delayMs=150)=>{
const [visible,setVisible]=hooks.useState(false);
hooks.useEffect(()=>{
if(!active){setVisible(false);return;}
setVisible(false);const timer=setTimeout(()=>setVisible(true),delayMs);return()=>clearTimeout(timer);
},[active,delayMs]);
return active&&visible;
};
const source=fs.readFileSync(new URL('../src/AnalysisVisuals.tsx',import.meta.url),'utf8');
const componentSource=source.slice(source.indexOf('export function AnalysisVisualCard('),source.indexOf('export function AnalysisVisuals(')).replace('export function','function');
const body=ts.transpileModule(componentSource,{fileName:'component.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
const Component=new Function('React','hooks','runtime',`
const {useState,useRef,useEffect,useCallback}=hooks;
const {useState,useRef,useEffect,useCallback,useDelayedIndicator}=hooks;
const Button='Button',Dropdown='Dropdown',Tag='Tag',Modal='Modal',TableOutlined='TableOutlined',DownloadOutlined='DownloadOutlined',MoreOutlined='MoreOutlined',ChartDataTable='ChartDataTable';
const document={visibilityState:'visible',documentElement:{},addEventListener(){},removeEventListener(){}};
const documentIsHidden=()=>false,visualTheme=()=>({}),visualPeriodSummary=()=>'',visualScopeSummary=()=>'',chartSummary=v=>v.title,analysisVisualTypeLabel=()=>'',visualUnitLabel=()=>'';
@@ -15,6 +15,7 @@ import {
visualUnitLabel,
} from '../src/analysisVisualsModel.ts';
import { buildAnalysisNarrative } from '../src/analysisReportModel.ts';
import { buildConclusionDocument, checkedConclusionComparison } from '../src/analysisConclusionModel.ts';
function visual(overrides = {}) {
return {
@@ -305,6 +306,64 @@ test('negative percentage point changes remain signed and keep a zero baseline',
assert.equal(formatVisualValue(0.5, 'pp'), '+0.5 pp');
});
test('legacy rate-drop charts normalize once and chat tables and exports use current minus prior', () => {
const legacy = visual({
id: 'legacy-rate-drop', type: 'bar', title: '业务分组合格率降幅线索', subtitle: '8月 → 9月',
unit: 'pp', metric: 'rate_drop_pp', dimension: 'group', sectionKey: 'group',
categories: [{ key: 'g1', label: '分组一' }, { key: 'g2', label: '分组二' }],
series: [{ key: 'rate_drop_pp', label: '合格率变化(pp)', values: [2.5, -4] }],
evidenceRefs: ['evidence-1'], requiredFields: ['black_good_weight', 'black_total_weight'],
scope: { department: '工业电机' }, period: { label: '2026-09' }, comparisonPeriod: { label: '2026-08' },
coverage: { totalRows: 2, returnedRows: 2, truncated: false },
note: '条形末端显示具体变化:正值为下降,负值为改善,单位是百分点。本图只按率降幅排序,未纳入投入规模。',
});
const model = parseAnalysisVisuals([legacy], 1).visuals[0];
assert.deepEqual(model.series[0].values, [-2.5, 4]);
assert.match(model.note, /本期减比较期/);
assert.match(model.note, /仍按率降幅排序|只按率降幅排序/);
assert.deepEqual(parseAnalysisVisuals([model], 1).visuals[0].series[0].values, [-2.5, 4]);
const legacyNotes = [
'正值表示合格率下降,负值表示改善;百分点取自正式分组率差。',
'正值表示综合合格率下降,负值表示改善;按正式综合率比较,不作为生产根因。',
undefined,
];
for (const [index, note] of legacyNotes.entries()) {
const snapshot = { ...legacy, id: `legacy-rate-drop-${index}`, note };
const normalized = parseAnalysisVisuals([snapshot], 1).visuals[0];
assert.deepEqual(normalized.series[0].values, [-2.5, 4]);
assert.match(normalized.note, /本期减比较期/);
assert.deepEqual(parseAnalysisVisuals([normalized], 1).visuals[0].series[0].values, [-2.5, 4]);
}
const chart = buildAnalysisVisualOption(model);
assert.deepEqual(chart.series[0].data, [-2.5, 4]);
const table = renderVisualTableHtml(legacy);
assert.match(table, /-2\.5 pp/);
assert.match(table, /\+4 pp/);
const exported = buildAnalysisVisualExportOption(model, 1280, 'report');
assert.deepEqual(exported.option.series[0].data, [-2.5, 4]);
const modern = { ...legacy, id: 'current-rate-drop', note: '正值表示本期合格率上升,负值表示下降;变化值为本期减比较期。',
series: [{ ...legacy.series[0], values: [-2.5, 4] }] };
assert.deepEqual(parseAnalysisVisuals([modern], 1).visuals[0].series[0].values, [-2.5, 4]);
const reading = { lead: '分组变化', evidence: [], notices: [], evidenceRefs: ['evidence-1'],
hasAppendix: false, fullAnswer: '### 业务分组变化\n\n合格率有变化。[evidence-1]', visualCount: 1 };
const conclusion = buildConclusionDocument(reading, [model]);
assert.deepEqual(conclusion.sections.find(section => section.title === '业务分组变化').visuals[0].series[0].values, [-2.5, 4]);
});
test('checked conclusion comparisons give declines negative pp and increases positive pp', () => {
const down = checkedConclusionComparison('9月综合合格率95.13%,较8月的95.57%下降0.44个百分点。');
const up = checkedConclusionComparison('9月综合合格率95.57%,较8月的95.13%上升0.44个百分点。');
assert.equal(down.change, '-0.44');
assert.equal(up.change, '+0.44');
assert.equal(down.direction, '下降');
assert.equal(up.direction, '上升');
assert.equal(checkedConclusionComparison('9月综合合格率95.13%,较8月的95.57%上升0.44个百分点。'), null);
});
test('non-finite and out-of-range ratio values degrade to a table while retaining zero and null', () => {
const parsed = parseAnalysisVisuals([visual({ series: [{ key: 'r', label: '率', values: [0, Number.NaN] }] })]);
assert.equal(parsed.visuals.length, 1);
+2 -2
View File
@@ -6,10 +6,10 @@ const json = (value: unknown) => new Response(JSON.stringify(value), {headers:{'
window.fetch = async (target) => {
const url = new URL(String(target), location.origin);
if(url.pathname==='/api/auth/me')return json({user:{id:'local-fixture',username:'admin',displayName:'admin',roles:['SYSTEM_ADMIN'],departments:[],groups:[]}});
if(url.pathname==='/api/workspace/state')return json({authRevision:'fixture',dataRevision:'fixture'});
if(url.pathname==='/api/workspace/state')return json({authRevision:'fixture',dataRevision:'fixture',currentReleaseId:'fixture-release'});
if(url.pathname==='/api/options')return json({years:[2026],departments:['工业电机产业部'],groups:['工业电机-VCM'],groupDepartments:{'工业电机-VCM':'工业电机产业部'},products,projectGroupStatus:'READY',projectGroups:[],releases:[{id:'fixture-release',name:'本地验收',status:'PUBLISHED'}]});
if(url.pathname==='/api/filter-fields')return json([]);
if(url.pathname==='/api/metrics') {
if(url.pathname==='/api/metrics'||url.pathname==='/api/metrics/trend') {
const view=url.searchParams.get('view');
const product=url.searchParams.get('product');
let visible=product?rows.filter(r=>r.product===product):rows;
@@ -0,0 +1,43 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import ts from 'typescript';
import React from 'react';
function fixture() {
const source=fs.readFileSync(process.env.QUERY_CHART_SOURCE || new URL('../src/QueryPage.tsx',import.meta.url),'utf8');
const end=source.includes('export function TrendTable(')?source.indexOf('export function TrendTable('):source.indexOf('function TrendTable(');
const code=source.slice(source.indexOf('export function TrendChart('),end).replace('export function','function');
const slots=new Map(),effects=new Map(),observers=[],charts=[];let cursor=0,dirty=false,queued=[],active=true,visible=true;
const node={clientWidth:900,clientHeight:380};
const hooks={useRef(initial){const i=cursor++;if(!slots.has(i))slots.set(i,{current:initial});return slots.get(i);},useState(initial){const i=cursor++;if(!slots.has(i))slots.set(i,initial);return [slots.get(i),v=>{const next=typeof v==='function'?v(slots.get(i)):v;if(!Object.is(next,slots.get(i))){slots.set(i,next);dirty=true;}}];},useCallback(fn,deps){const i=cursor++;const old=slots.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))slots.set(i,{fn,deps});return slots.get(i).fn;},useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))queued.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});}};
hooks.useLayoutEffect=hooks.useEffect;
const ec={init(_node,_theme,opts){const c={opts,options:[],resizes:[],disposed:false,getWidth:()=>c.opts.width??100,getHeight:()=>c.opts.height??380,on(){},resize(o){c.resizes.push(o);},setOption(o){c.options.push(o);},convertToPixel:()=>0,dispose(){c.disposed=true;}};charts.push(c);return c;}};
const prelude=`const {useRef,useState,useEffect,useLayoutEffect,useCallback}=hooks;
const usePageCache=()=>({active:getActive()}),useResourceVisibility=()=>getActive()&&getVisible();
const Empty=Object.assign('Empty',{PRESENTED_IMAGE_SIMPLE:'simple'});
const MutationObserver=class{observe(){}disconnect(){}},ResizeObserver=class{constructor(fn){this.fn=fn;observers.push(this)}observe(){}disconnect(){this.disconnected=true}};
const document={documentElement:{dataset:{}}},window={matchMedia:()=>({matches:false,addEventListener(){},removeEventListener(){}})};
const queryChartTypography=()=>({fontFamily:'sans',numericFamily:'sans',fontSize:12,tooltipFontSize:12});
const getComputedStyle=()=>({getPropertyValue:()=>''}),getWorkspaceTheme=()=>({id:'light'}),trendBarPalette=()=>({qualified:'#607ae1',scrap:'#d58c35'});
const trendBarWidth=()=>32,hasStageRows=()=>true,stageValue=(r,s,f)=>r[s][f],visibleCompositeRate=()=>.95,visibleStageRate=()=>.97,rateNumber=v=>v*100,numberText=String,escapeTooltipText=String,defectWeightRate=()=>0;
`;
const compiled=ts.transpileModule(prelude+code+'\nreturn TrendChart;',{fileName:'motion.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
const Component=new Function('React','hooks','echarts','getActive','getVisible','observers',compiled)(React,hooks,ec,()=>active,()=>visible,observers);
const stage={qualifiedWeight:90,scrapWeight:10,totalWeight:100,defects:[]};const props={rows:[{month:1,black:stage,bright:stage}],mode:'production',stage:'bright',rateBasis:'original',targetRate:null,onMonth(){}};
function attach(t){if(!t||typeof t!=='object')return;if(t.props?.ref)t.props.ref.current=node;React.Children.forEach(t.props?.children,attach);}
function render(){let n=0;do{cursor=0;dirty=false;queued=[];attach(Component(props));queued.forEach(f=>f());assert.ok(++n<10);}while(dirty);}
return {charts,node,render,setVisible(v){visible=v;render();},setActive(v){active=v;render();},resize(){for(const o of observers)if(!o.disconnected)o.fn();},unmount(){effects.forEach(e=>e.cleanup?.());}};
}
test('visible entry uses the actual chart size and enables native vertical bar growth',()=>{
const f=fixture();f.render();const c=f.charts[0];assert.equal(c.opts.width,900);assert.equal(c.opts.height,380);
const o=c.options.find(o=>o.series);assert.ok(o.animationDuration>0);assert.equal(o.xAxis.type,'category');assert.equal(o.yAxis[0].type,'value');assert.ok(o.series.filter(s=>s.type==='bar').every(s=>s.yAxisIndex===0));f.unmount();
});
test('cached page reentry creates a fresh vertical reveal and never resizes a hidden chart to zero',()=>{
const f=fixture();f.render();f.node.clientWidth=0;f.resize();assert.equal(f.charts[0].resizes.length,0);
f.setActive(false);assert.equal(f.charts[0].disposed,true);assert.equal(f.charts.length,1);
f.node.clientWidth=900;f.setActive(true);assert.equal(f.charts.length,2);assert.equal(f.charts[1].opts.width,900);assert.ok(f.charts[1].options.find(o=>o.series).animationDuration>0);f.unmount();
});
test('offscreen chart defers initialization until its region becomes visible',()=>{
const f=fixture();f.setVisible(false);assert.equal(f.charts.length,0);f.setVisible(true);assert.equal(f.charts.length,1);f.unmount();
});
@@ -19,6 +19,8 @@ function fixture(){
const Spin='Spin',Alert='Alert',Empty=Object.assign('Empty',{PRESENTED_IMAGE_SIMPLE:'simple'});
const MutationObserver=class{observe(){}disconnect(){}},ResizeObserver=class{observe(){}disconnect(){}};
const document={documentElement:{}},window={matchMedia:()=>({matches:false,addEventListener(){},removeEventListener(){}})};
const usePageCache=()=>({active:true});
const useResourceVisibility=()=>true,useDelayedIndicator=value=>value;
const queryChartTypography=()=>({fontFamily:'sans',numericFamily:'sans',fontSize:12,tooltipFontSize:12});
const getComputedStyle=()=>({getPropertyValue:()=>''}),escapeTooltipText=v=>v,numberText=v=>String(v),chooseError=e=>e.message;
class ApiError extends Error{};

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