优化:按分析章节整合图表解读与完整报告导出
This commit is contained in:
@@ -27,6 +27,14 @@ releaseId、发布版本号、候选发布状态、Story ID/slug/version 仅作
|
||||
|
||||
## 输出与收尾
|
||||
|
||||
报告与聊天均按“结论—对应图表—解释—依据”的阅读关系组织内容。平台会将图表插入相应语义章节,不再在末尾统一堆放。根据本轮真实问题选择章节:整体比较、阶段变化、产业部变化、业务分组变化、正式报废类别、具体缺陷、重点产品/规格、交叉核查、下一步;不强制窄范围问答套整套章节。章节标题保留对应业务词,并用简短判断说明本节要点;图表由平台提供,正文不要写“见下图”或虚构图号。
|
||||
|
||||
整体变化先用简短摘要说清变化方向、主要阶段和优先核查线索,再展开各节。每节先写一到三句解释已确认的现象及实际含义,必要时附一张紧凑数据表,不只连续抄表、不在“重点关注”重复全部数字。阶段数学影响沿用 stageDecomposition 的服务端结果,不能把阶段自身率变化当作对综合率贡献,也不把数学拆解称现场生产根因。亮片报废下降而投入下降更多时,要明确解释合格率仍可能下降。
|
||||
|
||||
常规整体分析的重点规格优先结合报废增量、当前规模、率变化和分阶段有效投入确定核查优先级。单按合格率降幅返回的小批量、0率或阶段缺失规格,另列“极端率变化线索”,不能只因降幅大就称整体主要原因;两期分母未查清时不推断停产、退出或全批报废。用户明确只看降幅排名时保留真实排名与批量背景。不得自设未授权的最低批量阈值或忽略小批量的安全/质量异常。
|
||||
|
||||
组织、规格和具体缺陷之间的关系只写实际交叉查询已经核对的联系;没有交叉证据时保持各自范围,不把两个独立排名拼成因果链。最后只列能执行的优先核查问题,分清已确认现象与待验证原因,不编造责任人、完成期限或闭环结果。所有图文继续复用同一轮证据;不要为了报告样式重复查询、重新计算核心指标或自动生成故事。
|
||||
|
||||
工具结果足以回答后,立即用最终答复收尾,不继续写研究过程。即使有部分工具失败,也要交代已确认的结果和具体缺口,不陷入重复尝试或无限思考。不得声称工具失败时完成了对应分析。
|
||||
|
||||
按问题组织答案,不套用固定两张TOP表。整体变化应清楚呈现:总体与阶段判断、各产业部变化、各业务分组变化、报废大类与具体缺陷、重点产品/规格、按优先级排列的关注方向与核查行动。产业部和业务分组分别呈现,较少时逐项列出,多时可分组简述但不遗漏重要恶化与改善;不要让读者从TOP规格推测组织情况。产品、缺陷的重点之间说明已核对的联系。简短追问只回答新增问题。必要内容优先,避免重复与冗长导致截断,不以1000字限制牺牲已要求的分析角度。长规格名保留原文。TOP规格严格取工具rank=1至5,不能把其他关注规格替换进入TOP5;额外关注对象另列一句。表格最多4列,报废增量、当前重量与率可择要,投入只有在分阶段核对后再表述。每张表就近标注真实证据编号及排序口径。
|
||||
|
||||
+100
-6
@@ -19,14 +19,15 @@ import tools.jackson.databind.json.JsonMapper;
|
||||
public final class AnalysisVisualSnapshotAccess {
|
||||
public static final int SCHEMA_VERSION = 1;
|
||||
public static final int MAX_SNAPSHOT_BYTES = 256 * 1024;
|
||||
private static final int MAX_VISUALS = 3;
|
||||
private static final int MAX_VISUALS = 12;
|
||||
private static final int MAX_CATEGORIES = 36;
|
||||
private static final int MAX_SERIES = 1;
|
||||
private static final int MAX_TEXT_BYTES = 2048;
|
||||
private static final Pattern SAFE_KEY = Pattern.compile("[A-Za-z0-9][A-Za-z0-9_.:-]{0,119}");
|
||||
private static final Pattern SAFE_EVIDENCE_REF = Pattern.compile("[A-Za-z0-9:_-]{1,160}");
|
||||
private static final Set<String> CHART_KEYS = Set.of("id", "type", "title", "subtitle", "unit", "categories", "series",
|
||||
"evidenceRefs", "requiredFields", "scope", "period", "comparisonPeriod", "stage", "metric", "coverage", "note", "originTurnId");
|
||||
"evidenceRefs", "requiredFields", "scope", "period", "comparisonPeriod", "stage", "metric", "coverage", "note",
|
||||
"originTurnId", "sectionKey", "dimension");
|
||||
private static final Set<String> SCOPE_KEYS = Set.of("year", "month", "quarter", "department", "group", "product",
|
||||
"projectGroup", "view", "includeUnassigned", "releaseId", "extraFilters", "stage", "category", "defect");
|
||||
private static final Set<String> PERIOD_KEYS = Set.of("start", "end", "label", "granularity", "year", "month", "quarter");
|
||||
@@ -122,12 +123,18 @@ public final class AnalysisVisualSnapshotAccess {
|
||||
|
||||
String id = text(input.get("id"), 120, true);
|
||||
if (!SAFE_KEY.matcher(id).matches()) return null;
|
||||
String type = enumText(input.get("type"), Set.of("bar", "line", "column", "area", "heatmap", "donut", "pareto"));
|
||||
String type = enumText(input.get("type"), Set.of("bar", "line", "column", "area", "heatmap", "donut", "pareto", "waterfall"));
|
||||
String title = text(input.get("title"), 200, false);
|
||||
String subtitle = input.containsKey("subtitle") ? text(input.get("subtitle"), 400, false) : null;
|
||||
String unit = enumText(input.get("unit"), Set.of("ratio", "kg", "pp", "count"));
|
||||
String metric = enumText(input.get("metric"), metricNames());
|
||||
String origin = text(input.get("originTurnId"), 64, true);
|
||||
String sectionKey = input.containsKey("sectionKey")
|
||||
? enumText(input.get("sectionKey"), Set.of("overview", "stage", "department", "group", "product",
|
||||
"category_black", "category_bright", "defect_black", "defect_bright", "trend", "composition")) : null;
|
||||
String dimension = input.containsKey("dimension")
|
||||
? enumText(input.get("dimension"), Set.of("department", "group", "product", "category", "defect")) : null;
|
||||
if (input.containsKey("sectionKey") && sectionKey == null || input.containsKey("dimension") && dimension == null) return null;
|
||||
if (turnId == null || !turnId.equals(origin)) return null;
|
||||
|
||||
MetricSemantics semantics = semantics(metric, input.get("stage"));
|
||||
@@ -152,12 +159,14 @@ public final class AnalysisVisualSnapshotAccess {
|
||||
Map<String, Object> coverage = normalizeCoverage(input.get("coverage"), requiredFields, semantics.stage(), type);
|
||||
if (coverage == null) return null;
|
||||
if (!validCompositionChart(type, metric, unit, semantics, categories, series, coverage, comparisonPeriod)
|
||||
|| !validPeriodChart(type, metric, semantics, period, comparisonPeriod, categories, series)) return null;
|
||||
|| !validPeriodChart(type, metric, semantics, period, comparisonPeriod, categories, series)
|
||||
|| !validWaterfallChart(type, metric, unit, semantics, categories, series, coverage, period, comparisonPeriod)) return null;
|
||||
if (!allowedFields.contains("*") && !allowedFields.containsAll(requiredFields)) return null;
|
||||
Map<String, Object> scope = normalizeScope(input.get("scope"), visibleExtraFilterKeys, expectedScope);
|
||||
Object scopedStage = scope == null ? null : scope.get("stage");
|
||||
if (scope == null || scopedStage != null && !"all".equals(scopedStage)
|
||||
&& (semantics.stage() == null || !semantics.stage().equals(scopedStage))) return null;
|
||||
if (!validChapterMetadata(sectionKey, dimension, type, metric, semantics, scope, period)) return null;
|
||||
if (semantics.sourceDefect() && !sourceDefectScopeMatches(scope, semantics.stage(), categories)) return null;
|
||||
String note = input.containsKey("note") ? text(input.get("note"), 500, false) : null;
|
||||
|
||||
@@ -171,6 +180,8 @@ public final class AnalysisVisualSnapshotAccess {
|
||||
if (semantics.stage() != null) result.put("stage", semantics.stage());
|
||||
result.put("metric", metric); result.put("coverage", coverage);
|
||||
if (note != null) result.put("note", note);
|
||||
if (sectionKey != null) result.put("sectionKey", sectionKey);
|
||||
if (dimension != null) result.put("dimension", dimension);
|
||||
result.put("originTurnId", turnId);
|
||||
return result;
|
||||
}
|
||||
@@ -219,7 +230,8 @@ public final class AnalysisVisualSnapshotAccess {
|
||||
"bright_headquarters_scrap", "bright_plating_scrap", "bright_material_scrap",
|
||||
"bright_processing_scrap", "bright_diffusion_scrap", "current_scrap_weight",
|
||||
"source_defect_weight").contains(metric) && decimal.signum() < 0) return null;
|
||||
if ("rate_drop_pp".equals(metric) && decimal.abs().compareTo(BigDecimal.valueOf(100)) > 0) return null;
|
||||
if (Set.of("rate_drop_pp", "composite_impact_pp").contains(metric)
|
||||
&& decimal.abs().compareTo(BigDecimal.valueOf(100)) > 0) return null;
|
||||
numbers.add(decimal);
|
||||
}
|
||||
}
|
||||
@@ -409,6 +421,86 @@ public final class AnalysisVisualSnapshotAccess {
|
||||
return sum.signum() > 0;
|
||||
}
|
||||
|
||||
private static boolean validWaterfallChart(String type, String metric, String unit, MetricSemantics semantics,
|
||||
List<Map<String, Object>> categories,
|
||||
List<Map<String, Object>> series,
|
||||
Map<String, Object> coverage,
|
||||
Map<String, Object> period,
|
||||
Map<String, Object> comparisonPeriod) {
|
||||
if (!"waterfall".equals(type)) return !"composite_impact_pp".equals(metric);
|
||||
if (!"composite_impact_pp".equals(metric) || !"pp".equals(unit) || semantics.stage() != null
|
||||
|| !Set.of("black_good_weight", "black_total_weight", "bright_good_weight", "bright_total_weight")
|
||||
.equals(semantics.requiredFields())
|
||||
|| !List.of("black", "bright", "total").equals(
|
||||
categories.stream().map(item -> item.get("key")).toList())
|
||||
|| series.size() != 1 || comparisonPeriod == null || samePeriod(period, comparisonPeriod)) return false;
|
||||
Object totalRaw = coverage.get("totalRows"), returnedRaw = coverage.get("returnedRows");
|
||||
if (!(totalRaw instanceof Number total) || !(returnedRaw instanceof Number returned)
|
||||
|| total.longValue() != 3 || returned.longValue() != 3 || !Boolean.FALSE.equals(coverage.get("truncated"))) return false;
|
||||
Object raw = series.getFirst().get("values");
|
||||
if (!(raw instanceof List<?> values) || values.size() != 3) return false;
|
||||
BigDecimal[] points = new BigDecimal[3];
|
||||
for (int index = 0; index < values.size(); index++) {
|
||||
points[index] = decimal(values.get(index));
|
||||
if (points[index] == null || points[index].abs().compareTo(BigDecimal.valueOf(100)) > 0) return false;
|
||||
}
|
||||
BigDecimal tolerance = new BigDecimal("0.000001");
|
||||
return points[0].add(points[1]).subtract(points[2]).abs().compareTo(tolerance) <= 0;
|
||||
}
|
||||
|
||||
private static boolean samePeriod(Map<String, Object> period, Map<String, Object> comparisonPeriod) {
|
||||
if (period.keySet().stream().anyMatch(Set.of("start", "end", "granularity")::contains)
|
||||
|| comparisonPeriod.keySet().stream().anyMatch(Set.of("start", "end", "granularity")::contains)) {
|
||||
return period.get("start") != null && period.get("start").equals(comparisonPeriod.get("start"))
|
||||
&& java.util.Objects.equals(period.get("end"), comparisonPeriod.get("end"))
|
||||
&& java.util.Objects.equals(period.get("granularity"), comparisonPeriod.get("granularity"));
|
||||
}
|
||||
return java.util.Objects.equals(period.get("year"), comparisonPeriod.get("year"))
|
||||
&& java.util.Objects.equals(period.get("month"), comparisonPeriod.get("month"))
|
||||
&& java.util.Objects.equals(period.get("quarter"), comparisonPeriod.get("quarter"));
|
||||
}
|
||||
|
||||
private static boolean validChapterMetadata(String section, String dimension, String type, String metric,
|
||||
MetricSemantics semantics, Map<String, Object> scope,
|
||||
Map<String, Object> period) {
|
||||
if (section == null && dimension == null) return true; // schema-1 snapshots created before chapter metadata
|
||||
boolean grouped = Set.of("bar", "column").contains(type);
|
||||
boolean sourceMetric = Set.of("source_defect_weight", "source_defect_delta_weight").contains(metric)
|
||||
&& semantics.sourceDefect();
|
||||
if (dimension != null && section == null) {
|
||||
return switch (dimension) {
|
||||
case "department", "group", "product" -> grouped
|
||||
&& Set.of("current_scrap_weight", "scrap_delta", "rate_drop_pp").contains(metric);
|
||||
case "category" -> sourceMetric && (grouped || Set.of("donut", "pareto").contains(type));
|
||||
case "defect" -> sourceMetric && grouped;
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
return switch (section) {
|
||||
case "overview" -> dimension == null && (("composite_rate".equals(metric) && Set.of("bar", "column").contains(type))
|
||||
|| "composite_impact_pp".equals(metric) && "waterfall".equals(type));
|
||||
case "stage" -> dimension == null && Set.of("black_rate", "bright_rate").contains(metric)
|
||||
&& semantics.stage() != null && semantics.stage().equals(metric.substring(0, metric.indexOf('_')))
|
||||
&& grouped;
|
||||
case "department" -> "department".equals(dimension) && grouped
|
||||
&& Set.of("current_scrap_weight", "scrap_delta", "rate_drop_pp").contains(metric);
|
||||
case "group" -> "group".equals(dimension) && grouped
|
||||
&& Set.of("current_scrap_weight", "scrap_delta", "rate_drop_pp").contains(metric);
|
||||
case "product" -> "product".equals(dimension) && grouped
|
||||
&& Set.of("current_scrap_weight", "scrap_delta", "rate_drop_pp").contains(metric);
|
||||
case "category_black", "category_bright" -> "category".equals(dimension) && grouped && sourceMetric
|
||||
&& semantics.stage().equals("category_black".equals(section) ? "black" : "bright");
|
||||
case "defect_black", "defect_bright" -> "defect".equals(dimension) && grouped && sourceMetric
|
||||
&& semantics.stage().equals("defect_black".equals(section) ? "black" : "bright");
|
||||
case "trend" -> dimension == null && Set.of("line", "area", "heatmap").contains(type)
|
||||
&& Set.of("composite_rate", "black_rate", "bright_rate", "current_scrap_weight").contains(metric)
|
||||
&& period.containsKey("start") && period.containsKey("end") && period.containsKey("granularity");
|
||||
case "composition" -> "category".equals(dimension) && Set.of("donut", "pareto").contains(type)
|
||||
&& "source_defect_weight".equals(metric) && semantics.sourceDefect();
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean validPeriodChart(String type, String metric, MetricSemantics semantics, Map<String, Object> period,
|
||||
Map<String, Object> comparisonPeriod,
|
||||
List<Map<String, Object>> categories,
|
||||
@@ -555,6 +647,8 @@ public final class AnalysisVisualSnapshotAccess {
|
||||
: new MetricSemantics("pp", stage,
|
||||
stage.equals("black") ? Set.of("black_good_weight", "black_total_weight")
|
||||
: Set.of("bright_good_weight", "bright_total_weight"), false);
|
||||
case "composite_impact_pp" -> stage == null ? new MetricSemantics("pp", null,
|
||||
Set.of("black_good_weight", "black_total_weight", "bright_good_weight", "bright_total_weight"), false) : null;
|
||||
case "source_defect_weight", "source_defect_delta_weight" -> stage == null ? null
|
||||
: new MetricSemantics("kg", stage, Set.of(), true);
|
||||
default -> null;
|
||||
@@ -564,7 +658,7 @@ public final class AnalysisVisualSnapshotAccess {
|
||||
private static Set<String> metricNames() {
|
||||
Set<String> result = new LinkedHashSet<>(WEIGHT_METRICS);
|
||||
result.addAll(Set.of("composite_rate", "black_rate", "bright_rate", "scrap_delta", "rate_drop_pp",
|
||||
"current_scrap_weight", "source_defect_weight", "source_defect_delta_weight"));
|
||||
"current_scrap_weight", "source_defect_weight", "source_defect_delta_weight", "composite_impact_pp"));
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
+93
-3
@@ -131,9 +131,79 @@ class AnalysisVisualSnapshotAccessTest {
|
||||
((List<Map<String, Object>>) wrongSeries.get("series")).getFirst().put("key", "bright_rate");
|
||||
assertEquals("failed", normalize(List.of(wrongSeries), RATE_FIELDS, SCOPE).state());
|
||||
|
||||
List<Map<String, Object>> tooMany = new ArrayList<>();
|
||||
for (int i = 0; i < 4; i++) tooMany.add(chart("black_rate", "ratio", "black", List.of(), List.of(0.9, 0.95), "v1-" + i));
|
||||
assertEquals("failed", normalize(tooMany, RATE_FIELDS, SCOPE).state());
|
||||
List<Map<String, Object>> maximum = new ArrayList<>();
|
||||
for (int i = 0; i < 12; i++) maximum.add(chart("black_rate", "ratio", "black", List.of(), List.of(0.9, 0.95), "v1-" + i));
|
||||
assertEquals("ready", normalize(maximum, RATE_FIELDS, SCOPE).state());
|
||||
maximum.add(chart("black_rate", "ratio", "black", List.of(), List.of(0.9, 0.95), "v1-overflow"));
|
||||
assertEquals("failed", normalize(maximum, RATE_FIELDS, SCOPE).state());
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsReconciledMathOnlyWaterfallAndRejectsForgedDecompositionShapes() {
|
||||
Set<String> allFields = Set.of("black_good_weight", "black_total_weight", "bright_good_weight", "bright_total_weight");
|
||||
Map<String, Object> valid = waterfallChart();
|
||||
AnalysisVisualSnapshotAccess.Snapshot accepted = normalize(List.of(valid), allFields, SCOPE);
|
||||
assertEquals("ready", accepted.state());
|
||||
assertEquals("overview", accepted.visuals().getFirst().get("sectionKey"));
|
||||
assertEquals(allFields, Set.copyOf((List<String>) accepted.visuals().getFirst().get("requiredFields")));
|
||||
|
||||
Map<String, Object> wrongSum = waterfallChart();
|
||||
wrongSum.put("series", List.of(Map.of("key", "composite_impact_pp", "label", "影响", "values", List.of(-0.3, -0.14, -0.5))));
|
||||
Map<String, Object> wrongKeys = waterfallChart();
|
||||
wrongKeys.put("categories", List.of(Map.of("key", "black", "label", "黑片"),
|
||||
Map.of("key", "total", "label", "总计"), Map.of("key", "bright", "label", "亮片")));
|
||||
Map<String, Object> missingComparisonPeriod = waterfallChart();
|
||||
missingComparisonPeriod.remove("comparisonPeriod");
|
||||
Map<String, Object> wrongChapter = waterfallChart();
|
||||
wrongChapter.put("sectionKey", "stage");
|
||||
Map<String, Object> wrongDimension = waterfallChart();
|
||||
wrongDimension.put("dimension", "product");
|
||||
Map<String, Object> nullPoint = waterfallChart();
|
||||
nullPoint.put("series", List.of(Map.of("key", "composite_impact_pp", "label", "影响", "values", java.util.Arrays.asList(-0.3, null, -0.44))));
|
||||
|
||||
for (Map<String, Object> invalid : List.of(wrongSum, wrongKeys, missingComparisonPeriod, wrongChapter, wrongDimension, nullPoint))
|
||||
assertEquals("failed", normalize(List.of(invalid), allFields, SCOPE).state());
|
||||
}
|
||||
|
||||
@Test
|
||||
void chapterMetadataMustMatchTheChartMeaningWhileLegacySnapshotsRemainValid() {
|
||||
Map<String, Object> valid = chart("black_rate", "ratio", "black", List.of(), List.of(0.9, 0.95));
|
||||
valid.put("sectionKey", "stage");
|
||||
AnalysisVisualSnapshotAccess.Snapshot accepted = normalize(List.of(valid), RATE_FIELDS, SCOPE);
|
||||
assertEquals("ready", accepted.state());
|
||||
assertEquals("stage", accepted.visuals().getFirst().get("sectionKey"));
|
||||
|
||||
Map<String, Object> legacy = chart("black_rate", "ratio", "black", List.of(), List.of(0.9, 0.95));
|
||||
assertEquals("ready", normalize(List.of(legacy), RATE_FIELDS, SCOPE).state());
|
||||
|
||||
Map<String, Object> wrongDimension = chart("black_rate", "ratio", "black", List.of(), List.of(0.9, 0.95));
|
||||
wrongDimension.put("sectionKey", "stage");
|
||||
wrongDimension.put("dimension", "product");
|
||||
Map<String, Object> unknownSection = chart("black_rate", "ratio", "black", List.of(), List.of(0.9, 0.95));
|
||||
unknownSection.put("sectionKey", "root_cause");
|
||||
assertEquals("failed", normalize(List.of(wrongDimension), RATE_FIELDS, SCOPE).state());
|
||||
assertEquals("failed", normalize(List.of(unknownSection), RATE_FIELDS, SCOPE).state());
|
||||
}
|
||||
|
||||
@Test
|
||||
void formalCategoryAndSpecificDefectSectionsRequireMatchingStageAndDimension() {
|
||||
String formalField = "black_responsibility_scrap";
|
||||
Map<String, Object> category = sourceDefectChart("black", formalField, List.of(formalField));
|
||||
category.put("sectionKey", "category_black");
|
||||
category.put("dimension", "category");
|
||||
assertEquals("ready", normalize(List.of(category), Set.of(formalField), SCOPE).state());
|
||||
|
||||
Map<String, Object> rawDetail = sourceDefectChart("black", "责废其他重量", List.of("责废其他重量"));
|
||||
rawDetail.put("sectionKey", "defect_black");
|
||||
rawDetail.put("dimension", "defect");
|
||||
assertEquals("ready", normalize(List.of(rawDetail), Set.of("责废其他重量"), SCOPE).state());
|
||||
|
||||
Map<String, Object> wrongCategoryStage = new LinkedHashMap<>(category);
|
||||
wrongCategoryStage.put("sectionKey", "category_bright");
|
||||
Map<String, Object> wrongDetailDimension = new LinkedHashMap<>(rawDetail);
|
||||
wrongDetailDimension.put("dimension", "category");
|
||||
assertEquals("failed", normalize(List.of(wrongCategoryStage), Set.of(formalField), SCOPE).state());
|
||||
assertEquals("failed", normalize(List.of(wrongDetailDimension), Set.of("责废其他重量"), SCOPE).state());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -220,6 +290,11 @@ class AnalysisVisualSnapshotAccessTest {
|
||||
Map<String, Object> pareto = categoryShareChart("pareto", keys, List.of(3.0, 2.0, 1.0));
|
||||
assertEquals("ready", normalize(List.of(pareto), Set.copyOf(keys), SCOPE).state());
|
||||
|
||||
Map<String, Object> taggedDonut = categoryShareChart("donut", keys, List.of(1.0, 2.0, 3.0));
|
||||
taggedDonut.put("sectionKey", "composition");
|
||||
taggedDonut.put("dimension", "category");
|
||||
assertEquals("ready", normalize(List.of(taggedDonut), Set.copyOf(keys), SCOPE).state());
|
||||
|
||||
Map<String, Object> unsorted = categoryShareChart("pareto", keys, List.of(2.0, 3.0, 1.0));
|
||||
Map<String, Object> negative = categoryShareChart("donut", keys, List.of(2.0, -1.0, 1.0));
|
||||
Map<String, Object> missing = categoryShareChart("donut", keys, java.util.Arrays.asList(2.0, null, 1.0));
|
||||
@@ -345,4 +420,19 @@ class AnalysisVisualSnapshotAccessTest {
|
||||
chart.put("series", List.of(Map.of("key", "source_defect_weight", "label", "来源细分重量", "values", List.of(1.25))));
|
||||
return chart;
|
||||
}
|
||||
|
||||
private static Map<String, Object> waterfallChart() {
|
||||
Set<String> fields = Set.of("black_good_weight", "black_total_weight", "bright_good_weight", "bright_total_weight");
|
||||
Map<String, Object> chart = chart("composite_impact_pp", "pp", null, List.copyOf(fields),
|
||||
List.of(-0.3, -0.14, -0.44), "waterfall-v1");
|
||||
chart.put("type", "waterfall");
|
||||
chart.put("sectionKey", "overview");
|
||||
chart.put("categories", List.of(Map.of("key", "black", "label", "黑片数学影响"),
|
||||
Map.of("key", "bright", "label", "亮片数学影响"), Map.of("key", "total", "label", "合计")));
|
||||
chart.put("series", List.of(Map.of("key", "composite_impact_pp", "label", "数学影响(pp)",
|
||||
"values", List.of(-0.3, -0.14, -0.44))));
|
||||
chart.put("comparisonPeriod", Map.of("year", 2026, "month", 8, "label", "2026-08", "granularity", "month"));
|
||||
chart.put("coverage", Map.of("totalRows", 3, "returnedRows", 3, "truncated", false));
|
||||
return chart;
|
||||
}
|
||||
}
|
||||
|
||||
+288
-65
@@ -17,7 +17,7 @@ from typing import Any
|
||||
|
||||
|
||||
VISUAL_SCHEMA_VERSION = 1
|
||||
MAX_VISUALS = 3
|
||||
MAX_VISUALS = 12
|
||||
MAX_BODY_BYTES = 256 * 1024
|
||||
MAX_RANK_ROWS = 10
|
||||
MAX_TREND_POINTS = 36
|
||||
@@ -51,7 +51,7 @@ _CONTROL = re.compile(r"[\x00-\x1f\x7f]")
|
||||
_EXPLICIT_CHART = re.compile(
|
||||
r"图表|画图|绘图|可视化|趋势图|柱状图|柱形图|竖向柱|纵向柱|折线图|条形图|横条图|"
|
||||
r"横向柱|水平柱|面积图|面积趋势|热力图|热图|环状图|环形图|环状|环形|甜甜圈|饼图|"
|
||||
r"构成|占比|排名图|柏拉图|帕累托|pareto"
|
||||
r"构成|占比|排名图|柏拉图|帕累托|pareto|瀑布图|waterfall"
|
||||
)
|
||||
_NO_CHART = re.compile(r"不画图|不要(?:绘图|图表?|可视化|配图)|不需要(?:绘图|图表?|可视化|配图)|无需(?:绘图|图表|配图)|只要(?:文字|文本)|仅需(?:文字|文本)")
|
||||
_HORIZONTAL_BAR = re.compile(r"横向条形图|横条图|横向柱|水平条形图|水平柱|horizontal\s+bar", re.IGNORECASE)
|
||||
@@ -60,6 +60,7 @@ _AREA_CHART = re.compile(r"面积图|面积趋势|area\s+chart", re.IGNORECASE)
|
||||
_HEATMAP_CHART = re.compile(r"热力图|热图|heat\s*map", re.IGNORECASE)
|
||||
_DONUT_CHART = re.compile(r"环状图|环形图|环状|环形|甜甜圈|饼图|构成|占比|donut|doughnut|pie\s+chart", re.IGNORECASE)
|
||||
_PARETO_CHART = re.compile(r"柏拉图|帕累托|pareto", re.IGNORECASE)
|
||||
_WATERFALL_CHART = re.compile(r"瀑布图|waterfall", re.IGNORECASE)
|
||||
_LINE_CHART = re.compile(r"折线图|折线趋势|line\s+chart", re.IGNORECASE)
|
||||
_BAR_CHART = re.compile(r"条形图|bar\s+chart", re.IGNORECASE)
|
||||
_NEGATED_STYLE_PREFIX = re.compile(r"(?:不要|不用|无需|不需要|不画|不想要)\s*(?:使用|用|画)?\s*$")
|
||||
@@ -211,6 +212,18 @@ def _chart_scope(filters: dict[str, Any], release_id: str, period: dict[str, Any
|
||||
return clean
|
||||
|
||||
|
||||
def _scope_caption(scope: dict[str, Any]) -> str | None:
|
||||
labels = (("department", "产业部"), ("group", "业务分组"), ("product", "产品"),
|
||||
("category", "类别"), ("defect", "具体缺陷"))
|
||||
parts = []
|
||||
for key, label in labels:
|
||||
value = _safe_text(scope.get(key), limit=80)
|
||||
if value:
|
||||
parts.append(f"{label}:{value}")
|
||||
caption = ",".join(parts)
|
||||
return caption[:200] if caption else None
|
||||
|
||||
|
||||
def _period(value: Any) -> tuple[dict[str, int] | None, str | None, tuple[int, int, int] | None]:
|
||||
if not isinstance(value, dict):
|
||||
return None, None, None
|
||||
@@ -298,6 +311,8 @@ def _chart(
|
||||
metric: str,
|
||||
coverage: dict[str, Any],
|
||||
note: str | None = None,
|
||||
section_key: str | None = None,
|
||||
dimension: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
chart: dict[str, Any] = {
|
||||
"type": chart_type,
|
||||
@@ -319,6 +334,11 @@ def _chart(
|
||||
chart["comparisonPeriod"] = comparison_period
|
||||
if stage in ("black", "bright"):
|
||||
chart["stage"] = stage
|
||||
if section_key in {"overview", "stage", "department", "group", "product", "category_black",
|
||||
"category_bright", "defect_black", "defect_bright", "trend", "composition"}:
|
||||
chart["sectionKey"] = section_key
|
||||
if dimension in {"department", "group", "product", "category", "defect"}:
|
||||
chart["dimension"] = dimension
|
||||
if note:
|
||||
chart["note"] = note[:240]
|
||||
identity = dict(chart)
|
||||
@@ -388,16 +408,18 @@ def _comparison_charts(document: dict[str, Any], result: dict[str, Any], turn_id
|
||||
{"key": "comparison", "label": comparison_label},
|
||||
{"key": "current", "label": current_label},
|
||||
]
|
||||
asked_black, asked_bright = "黑片" in question, "亮片" in question
|
||||
explicit_stage_only = (asked_black or asked_bright) and not re.search(r"综合|总体", question)
|
||||
asked_black = bool(re.search(r"黑片.{0,8}(?:合格率|不良率|率)|(?:合格率|不良率|率).{0,8}黑片", question))
|
||||
asked_bright = bool(re.search(r"亮片.{0,8}(?:合格率|不良率|率)|(?:合格率|不良率|率).{0,8}亮片", question))
|
||||
broad_overall = bool(re.search(r"原因|整体分析|总体分析|整体|总体|不良率|综合质量", question))
|
||||
explicit_stage_only = (asked_black or asked_bright) and not re.search(r"综合|总体|整体", question)
|
||||
metrics: list[tuple[str, str | None, str, Any, Any, str]] = []
|
||||
if not explicit_stage_only:
|
||||
metrics.append(("composite_rate", None, "综合合格率", comparison.get("compositeRate"), current.get("compositeRate"), "composite_rate"))
|
||||
stage_changes = result.get("stageRateChangesPP")
|
||||
requested_stages = []
|
||||
if asked_black:
|
||||
if asked_black or broad_overall and not explicit_stage_only:
|
||||
requested_stages.append(("black", "黑片合格率", "black_rate"))
|
||||
if asked_bright:
|
||||
if asked_bright or broad_overall and not explicit_stage_only:
|
||||
requested_stages.append(("bright", "亮片合格率", "bright_rate"))
|
||||
for stage, label, metric in requested_stages:
|
||||
old_side, now_side = comparison.get(stage), current.get(stage)
|
||||
@@ -433,6 +455,136 @@ def _comparison_charts(document: dict[str, Any], result: dict[str, Any], turn_id
|
||||
stage=stage,
|
||||
metric=metric,
|
||||
coverage={"totalRows": 2, "returnedRows": 2, "truncated": False},
|
||||
section_key="overview" if metric == "composite_rate" else "stage",
|
||||
))
|
||||
return charts
|
||||
|
||||
|
||||
def _comparison_waterfall(document: dict[str, Any], result: dict[str, Any], turn_id: str,
|
||||
question: str) -> dict[str, Any] | None:
|
||||
"""Use the service's balanced decomposition for math-only attribution."""
|
||||
if result.get("kind") != "quality_comparison" or not re.search(
|
||||
r"原因|整体分析|总体分析|拆解|分解|归因|为什么", question):
|
||||
return None
|
||||
release_id = _release_id(document, result)
|
||||
scope, _ = _scope(result.get("filterBinding"))
|
||||
current, comparison = result.get("current"), result.get("comparison")
|
||||
delta, decomposition = result.get("delta"), result.get("stageDecomposition")
|
||||
if (release_id is None or scope is None or not isinstance(current, dict)
|
||||
or not isinstance(comparison, dict) or not isinstance(delta, dict)
|
||||
or delta.get("available") is not True or not isinstance(decomposition, dict)
|
||||
or decomposition.get("status") != "available"):
|
||||
return None
|
||||
period, current_label, _ = _period(current.get("period"))
|
||||
comparison_period, comparison_label, _ = _period(comparison.get("period"))
|
||||
if (period is None or comparison_period is None or period == comparison_period
|
||||
or not _scope_compatible(scope, release_id, period=period)):
|
||||
return None
|
||||
values = []
|
||||
for field in ("blackContributionToCompositePP", "brightContributionToCompositePP", "sumPP"):
|
||||
value, valid = _finite_number(decomposition.get(field))
|
||||
if not valid or value is None or abs(value) > 100:
|
||||
return None
|
||||
values.append(value)
|
||||
reported_delta, delta_valid = _finite_number(delta.get("percentagePoints"))
|
||||
if not delta_valid or reported_delta is None or abs(reported_delta) > 100:
|
||||
return None
|
||||
if not math.isclose(values[0] + values[1], values[2], rel_tol=1e-10, abs_tol=1e-6):
|
||||
return None
|
||||
if not math.isclose(values[2], reported_delta, rel_tol=1e-10, abs_tol=1e-6):
|
||||
return None
|
||||
refs = [_evidence_ref(document)] if _evidence_ref(document) else []
|
||||
return _chart(
|
||||
turn_id=turn_id,
|
||||
chart_type="waterfall",
|
||||
title="综合合格率变化的数学影响拆解",
|
||||
subtitle=f"{comparison_label} → {current_label};展示两阶段对正式综合率变化的数学影响。",
|
||||
unit="pp",
|
||||
categories=[
|
||||
{"key": "black", "label": "黑片数学影响"},
|
||||
{"key": "bright", "label": "亮片数学影响"},
|
||||
{"key": "total", "label": "合计"},
|
||||
],
|
||||
series=[{"key": "composite_impact_pp", "label": "对综合合格率变化的数学影响(pp)", "values": values}],
|
||||
evidence_refs=refs,
|
||||
required_fields=["black_good_weight", "black_total_weight", "bright_good_weight", "bright_total_weight"],
|
||||
scope=_chart_scope(scope, release_id, period),
|
||||
period=period,
|
||||
comparison_period=comparison_period,
|
||||
metric="composite_impact_pp",
|
||||
coverage={"totalRows": 3, "returnedRows": 3, "truncated": False},
|
||||
note="仅为正式合格率变化的数学拆解,不代表生产根因。",
|
||||
section_key="overview",
|
||||
)
|
||||
|
||||
|
||||
def _comparison_category_delta_charts(document: dict[str, Any], result: dict[str, Any], turn_id: str,
|
||||
question: str) -> list[dict[str, Any]]:
|
||||
if (result.get("kind") != "quality_comparison"
|
||||
or not re.search(r"原因|整体分析|总体分析|报废类别|类别增减|正式类别", question)):
|
||||
return []
|
||||
release_id = _release_id(document, result)
|
||||
scope, _ = _scope(result.get("filterBinding"))
|
||||
current, comparison = result.get("current"), result.get("comparison")
|
||||
if release_id is None or scope is None or not isinstance(current, dict) or not isinstance(comparison, dict):
|
||||
return []
|
||||
current_period, current_label, _ = _period(current.get("period"))
|
||||
comparison_period, comparison_label, _ = _period(comparison.get("period"))
|
||||
if (current_period is None or comparison_period is None or current_period == comparison_period
|
||||
or scope.get("category") not in (None, "") or scope.get("defect") not in (None, "")):
|
||||
return []
|
||||
charts: list[dict[str, Any]] = []
|
||||
for stage in ("black", "bright"):
|
||||
if not _scope_compatible(scope, release_id, period=current_period, stage=stage):
|
||||
continue
|
||||
now_side, old_side = current.get(stage), comparison.get(stage)
|
||||
if not isinstance(now_side, dict) or not isinstance(old_side, dict):
|
||||
continue
|
||||
now_defs, old_defs = now_side.get("defects"), old_side.get("defects")
|
||||
expected = _DEFECT_FIELDS[stage]
|
||||
if not isinstance(now_defs, list) or not isinstance(old_defs, list):
|
||||
continue
|
||||
|
||||
def read_formal(items: list[Any]) -> dict[str, float] | None:
|
||||
parsed: dict[str, float] = {}
|
||||
for item in items:
|
||||
if not isinstance(item, dict):
|
||||
return None
|
||||
label = _safe_text(item.get("name"), limit=80)
|
||||
field = expected.get(label) if label is not None else None
|
||||
weight, valid = _valid_weight(item.get("weight"))
|
||||
if field is None or not valid or weight is None or field in parsed:
|
||||
return None
|
||||
parsed[field] = weight
|
||||
return parsed
|
||||
|
||||
now_values, old_values = read_formal(now_defs), read_formal(old_defs)
|
||||
if (now_values is None or old_values is None or set(now_values) != set(expected.values())
|
||||
or set(old_values) != set(expected.values()) or sum(now_values.values()) + sum(old_values.values()) <= 0):
|
||||
continue
|
||||
ordered = list(expected.items())
|
||||
labels, fields = [item[0] for item in ordered], [item[1] for item in ordered]
|
||||
values = [now_values[field] - old_values[field] for field in fields]
|
||||
stage_label = "黑片" if stage == "black" else "亮片"
|
||||
charts.append(_chart(
|
||||
turn_id=turn_id,
|
||||
chart_type="bar",
|
||||
title=f"{stage_label}正式报废类别重量增减",
|
||||
subtitle=f"{comparison_label} → {current_label};按正式类别逐项相减,正负方向均保留。",
|
||||
unit="kg",
|
||||
categories=[{"key": field, "label": label} for field, label in zip(fields, labels)],
|
||||
series=[{"key": "source_defect_delta_weight", "label": "报废重量增减(kg)", "values": values}],
|
||||
evidence_refs=[_evidence_ref(document)] if _evidence_ref(document) else [],
|
||||
required_fields=fields,
|
||||
scope=_chart_scope(scope, release_id, current_period, view="overall", stage=stage),
|
||||
period=current_period,
|
||||
comparison_period=comparison_period,
|
||||
stage=stage,
|
||||
metric="source_defect_delta_weight",
|
||||
coverage={"totalRows": len(fields), "returnedRows": len(fields), "truncated": False},
|
||||
note="展示正式报废类别各自的期间增减,不代表总体合格率贡献。",
|
||||
section_key=f"category_{stage}",
|
||||
dimension="category",
|
||||
))
|
||||
return charts
|
||||
|
||||
@@ -501,6 +653,8 @@ def _formal_donut_chart(
|
||||
coverage={"totalRows": count, "returnedRows": count, "truncated": False,
|
||||
"shareBasis": "displayed_categories"},
|
||||
note="占比按本图已列类别重量合计计算,不代表正式报废总量占比。",
|
||||
section_key="composition",
|
||||
dimension="category",
|
||||
)
|
||||
|
||||
|
||||
@@ -592,6 +746,8 @@ def _share_chart_from_top_chart(chart: dict[str, Any], document: dict[str, Any],
|
||||
result_chart["requiredFields"] = [category["key"] for category in categories]
|
||||
result_chart["coverage"] = {"totalRows": len(categories), "returnedRows": len(categories),
|
||||
"truncated": False, "shareBasis": "displayed_categories"}
|
||||
result_chart["sectionKey"] = "composition"
|
||||
result_chart["dimension"] = "category"
|
||||
result_chart.pop("id", None)
|
||||
result_chart["id"] = _visual_id(turn_id, result_chart)
|
||||
return result_chart
|
||||
@@ -718,11 +874,13 @@ def _change_chart(document: dict[str, Any], result: dict[str, Any], turn_id: str
|
||||
"returnedRows": len(selected),
|
||||
"truncated": truncated or len(selected) < len(row_info),
|
||||
}
|
||||
scope_caption = _scope_caption(scope)
|
||||
return _chart(
|
||||
turn_id=turn_id,
|
||||
chart_type="bar",
|
||||
title=title,
|
||||
subtitle=f"{comparison_label} → {current_label};按接口返回排名,展示前 {len(selected)} 项。",
|
||||
subtitle=(f"范围 {scope_caption};" if scope_caption else "")
|
||||
+ f"{comparison_label} → {current_label};按接口返回排名,展示前 {len(selected)} 项。",
|
||||
unit=unit,
|
||||
categories=categories,
|
||||
series=[{"key": metric, "label": label, "values": values}],
|
||||
@@ -736,6 +894,8 @@ def _change_chart(document: dict[str, Any], result: dict[str, Any], turn_id: str
|
||||
metric=metric,
|
||||
coverage=coverage,
|
||||
note=note,
|
||||
section_key={"product": "product", "group": "group", "department": "department"}[result["dimension"]],
|
||||
dimension=result["dimension"],
|
||||
)
|
||||
|
||||
|
||||
@@ -967,6 +1127,10 @@ def _top_chart(document: dict[str, Any], result: dict[str, Any], turn_id: str) -
|
||||
coverage={"totalRows": groups, "returnedRows": selected,
|
||||
"truncated": len(categories) < groups or len(categories) > MAX_RANK_ROWS},
|
||||
note=note,
|
||||
section_key=(f"category_{stage}" if dimension == "category" else
|
||||
{"product": "product", "group": "group", "department": "department"}.get(dimension, "group")),
|
||||
dimension=("group" if dimension == "projectGroup" else
|
||||
dimension if dimension in ("product", "group", "department", "category") else None),
|
||||
)
|
||||
|
||||
|
||||
@@ -1156,11 +1320,13 @@ def _fine_defect_chart(document: dict[str, Any], result: dict[str, Any], turn_id
|
||||
"returnedRows": len(categories),
|
||||
"truncated": truncated or len(categories) < len(source_rows),
|
||||
}
|
||||
scope_caption = _scope_caption(scope)
|
||||
return _chart(
|
||||
turn_id=turn_id,
|
||||
chart_type="bar",
|
||||
title=f"{stage_label}{title}",
|
||||
subtitle=(f"{comparison_label} → {period_label};" if comparison_label else f"{period_label};")
|
||||
subtitle=(f"范围 {scope_caption};" if scope_caption else "")
|
||||
+ (f"{comparison_label} → {period_label};" if comparison_label else f"{period_label};")
|
||||
+ "按来源字段排序,缺失增量保留为空。",
|
||||
unit=unit,
|
||||
categories=categories[:MAX_RANK_ROWS],
|
||||
@@ -1176,6 +1342,8 @@ def _fine_defect_chart(document: dict[str, Any], result: dict[str, Any], turn_id
|
||||
coverage={**coverage, "returnedRows": min(len(categories), MAX_RANK_ROWS),
|
||||
"truncated": coverage["truncated"] or len(categories) > MAX_RANK_ROWS},
|
||||
note=note,
|
||||
section_key=f"defect_{result['stage']}",
|
||||
dimension="defect",
|
||||
)
|
||||
|
||||
|
||||
@@ -1289,6 +1457,7 @@ def _trend_chart_from_points(
|
||||
stage=stage,
|
||||
metric=metric,
|
||||
coverage={"totalRows": len(expanded), "returnedRows": len(expanded), "truncated": False},
|
||||
section_key="trend",
|
||||
))
|
||||
if re.search(r"重量|报废|废品|kg|公斤", question, re.IGNORECASE):
|
||||
weight_stages = [("black", "黑片报废重量"), ("bright", "亮片报废重量")]
|
||||
@@ -1326,6 +1495,7 @@ def _trend_chart_from_points(
|
||||
metric=metric,
|
||||
coverage={"totalRows": len(expanded), "returnedRows": len(expanded), "truncated": False},
|
||||
note="黑片与亮片分开;不合并为单阶段投入分母。",
|
||||
section_key="trend",
|
||||
))
|
||||
return charts
|
||||
|
||||
@@ -1437,6 +1607,7 @@ def _requested_chart_type(question: str) -> str | None:
|
||||
for pattern, chart_type in (
|
||||
(_COLUMN_CHART, "column"), (_AREA_CHART, "area"), (_HEATMAP_CHART, "heatmap"),
|
||||
(_DONUT_CHART, "donut"), (_LINE_CHART, "line"), (_BAR_CHART, "bar"),
|
||||
(_WATERFALL_CHART, "waterfall"),
|
||||
):
|
||||
match = first_unnegated(pattern)
|
||||
if match:
|
||||
@@ -1500,52 +1671,68 @@ def _chart_end_rank(chart: dict[str, Any]) -> tuple[int, int, int]:
|
||||
|
||||
|
||||
def _candidate_priority(chart: dict[str, Any], kind: str, dimension: str | None, question: str) -> int:
|
||||
wants_trend = "趋势" in question
|
||||
if chart.get("type") == "line":
|
||||
if re.search(r"重量|报废|废品|kg|公斤", question, re.IGNORECASE) and chart.get("metric") == "current_scrap_weight":
|
||||
"""Choose chapter-relevant views without letting incidental rankings lead."""
|
||||
metric = chart.get("metric")
|
||||
section = chart.get("sectionKey")
|
||||
requested_dimension = None
|
||||
if re.search(r"产品|规格", question):
|
||||
requested_dimension = "product"
|
||||
elif "分组" in question:
|
||||
requested_dimension = "group"
|
||||
elif re.search(r"产业部|部门", question):
|
||||
requested_dimension = "department"
|
||||
broad_cause = bool(re.search(r"原因|分析|拆解|分解|归因", question))
|
||||
explicit_rate_rank = bool(re.search(r"率降幅|合格率变化排名|率下降排名|排名.*合格率", question))
|
||||
if metric == "current_scrap_weight" and re.search(r"重量|报废|废品|kg|公斤", question, re.IGNORECASE):
|
||||
return 0 if "趋势" in question else 3
|
||||
scope = chart.get("scope") if isinstance(chart.get("scope"), dict) else {}
|
||||
scope_specificity = sum(scope.get(key) not in (None, "", [], {}) for key in (
|
||||
"department", "group", "product", "category", "defect"
|
||||
))
|
||||
|
||||
if chart.get("type") in ("donut", "pareto") or section == "composition":
|
||||
return 0
|
||||
if not wants_trend:
|
||||
return 6
|
||||
return {"composite_rate": 0, "black_rate": 1, "bright_rate": 2}.get(chart.get("metric"), 6)
|
||||
if kind == "quality_comparison":
|
||||
# A stage mentioned as the scope of a defect question should not displace
|
||||
# the explicitly requested product and defect charts from the three slots.
|
||||
if (chart.get("metric") != "composite_rate"
|
||||
and re.search(r"综合|总体", question)
|
||||
and re.search(r"产品|规格", question)
|
||||
and re.search(r"缺陷", question)):
|
||||
if chart.get("type") in ("line", "area", "heatmap") or section == "trend":
|
||||
if "趋势" in question:
|
||||
return {"composite_rate": 0, "black_rate": 1, "bright_rate": 2,
|
||||
"current_scrap_weight": 3}.get(metric, 5)
|
||||
return 8
|
||||
return 1 if wants_trend else (0 if chart.get("metric") == "composite_rate" else 1)
|
||||
if kind == "quality_changes":
|
||||
requested_dimension = None
|
||||
if re.search(r"产品|规格", question):
|
||||
requested_dimension = "product"
|
||||
elif "分组" in question:
|
||||
requested_dimension = "group"
|
||||
elif re.search(r"产业部|部门", question):
|
||||
requested_dimension = "department"
|
||||
base = {"product": 10, "group": 20, "department": 30}.get(dimension, 40)
|
||||
if requested_dimension == dimension:
|
||||
base = 4
|
||||
if re.search(r"合格率|降幅|下降", question) and chart.get("metric") == "rate_drop_pp":
|
||||
base -= 1
|
||||
if re.search(r"报废|增量|重量", question) and chart.get("metric") in ("scrap_delta", "current_scrap_weight"):
|
||||
base -= 1
|
||||
return base
|
||||
if metric == "composite_rate" and section == "overview":
|
||||
return 0
|
||||
if metric == "composite_impact_pp":
|
||||
return 1 if broad_cause else 5
|
||||
if section == "stage":
|
||||
return 2 if broad_cause or re.search(r"黑片|亮片|阶段", question) else 6
|
||||
if metric == "rate_drop_pp":
|
||||
if explicit_rate_rank:
|
||||
return 2
|
||||
if broad_cause:
|
||||
return {"department": 3, "group": 4}.get(section, 20)
|
||||
return {"department": 7, "group": 8}.get(section, 20)
|
||||
if section == "product" or kind == "quality_top" and dimension == "product":
|
||||
if requested_dimension == "product":
|
||||
return 3 if metric in ("scrap_delta", "current_scrap_weight") else 4
|
||||
return 4 if metric in ("scrap_delta", "current_scrap_weight") else 10
|
||||
if section == "department" or kind == "quality_top" and dimension == "department":
|
||||
return 4 if metric in ("scrap_delta", "current_scrap_weight") else 6
|
||||
if section == "group" or kind == "quality_top" and dimension in ("group", "projectGroup"):
|
||||
return 5 if metric in ("scrap_delta", "current_scrap_weight") else 7
|
||||
if section in ("category_black", "category_bright"):
|
||||
return 5 if broad_cause or re.search(r"报废类别|类别增减|正式类别", question) else 9
|
||||
if section in ("defect_black", "defect_bright"):
|
||||
# 优先阶段汇总;局部追查图保留自身筛选范围,仍可作为补充视图。
|
||||
return 6 + min(scope_specificity, 3) + (0 if broad_cause else 2)
|
||||
if kind == "quality_top":
|
||||
requested_dimension = None
|
||||
if re.search(r"产品|规格", question):
|
||||
requested_dimension = "product"
|
||||
elif "分组" in question:
|
||||
requested_dimension = "group"
|
||||
elif re.search(r"产业部|部门", question):
|
||||
requested_dimension = "department"
|
||||
elif "项目组" in question:
|
||||
requested_dimension = "projectGroup"
|
||||
return 4 if requested_dimension == dimension else 12
|
||||
if kind == "quality_fine_defects":
|
||||
return 5 if re.search(r"缺陷|责废|料废|外废|加工废|镀废", question) else 15
|
||||
return 25
|
||||
return 4 if requested_dimension == dimension else 10
|
||||
return 12
|
||||
|
||||
|
||||
def _chart_selection_key(chart: dict[str, Any]) -> str:
|
||||
semantic = {key: chart.get(key) for key in (
|
||||
"type", "sectionKey", "dimension", "metric", "stage", "scope", "period", "comparisonPeriod",
|
||||
"categories", "series",
|
||||
)}
|
||||
return json.dumps(semantic, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
|
||||
|
||||
|
||||
def _finalize(charts: list[dict[str, Any]], turn_id: str, *, unavailable: bool = False) -> dict[str, Any]:
|
||||
@@ -1581,7 +1768,7 @@ def _finalize(charts: list[dict[str, Any]], turn_id: str, *, unavailable: bool =
|
||||
|
||||
|
||||
def build_visuals(evidence: list[dict[str, Any]], question: str, turn_id: str) -> dict[str, Any]:
|
||||
"""Return up to three safe chart snapshots from full trusted evidence docs.
|
||||
"""Return up to twelve safe chart snapshots from full trusted evidence docs.
|
||||
|
||||
The function is intentionally non-fatal: exceptions return a short error state
|
||||
so a caller can preserve the already completed textual analysis.
|
||||
@@ -1610,6 +1797,11 @@ def build_visuals(evidence: list[dict[str, Any]], question: str, turn_id: str) -
|
||||
dimension = result.get("dimension") if isinstance(result.get("dimension"), str) else None
|
||||
for chart in _comparison_charts(document, result, safe_turn_id, text_question):
|
||||
candidates.append((_candidate_priority(chart, kind, dimension, text_question), kind, dimension, chart))
|
||||
waterfall = _comparison_waterfall(document, result, safe_turn_id, text_question)
|
||||
if waterfall is not None:
|
||||
candidates.append((_candidate_priority(waterfall, kind, dimension, text_question), kind, dimension, waterfall))
|
||||
for chart in _comparison_category_delta_charts(document, result, safe_turn_id, text_question):
|
||||
candidates.append((_candidate_priority(chart, kind, dimension, text_question), kind, dimension, chart))
|
||||
for chart in _comparison_category_charts(document, result, safe_turn_id, text_question):
|
||||
candidates.append((_candidate_priority(chart, kind, dimension, text_question), kind, dimension, chart))
|
||||
for chart in _metrics_category_charts(document, result, safe_turn_id, text_question):
|
||||
@@ -1641,31 +1833,62 @@ def build_visuals(evidence: list[dict[str, Any]], question: str, turn_id: str) -
|
||||
continue
|
||||
styled_candidates.append((priority, kind, dimension, chart))
|
||||
candidates = styled_candidates
|
||||
candidates.sort(key=lambda item: (item[0], tuple(-part for part in _chart_end_rank(item[3])), item[3].get("id", "")))
|
||||
stage_order = {"black": 0, "bright": 1, None: 2}
|
||||
metric_order = {"composite_rate": 0, "black_rate": 1, "bright_rate": 2,
|
||||
"scrap_delta": 3, "source_defect_delta_weight": 4}
|
||||
def scope_depth(chart):
|
||||
scope = chart.get("scope") if isinstance(chart.get("scope"), dict) else {}
|
||||
return sum(scope.get(key) not in (None, "", [], {}) for key in ("department", "group", "product", "category", "defect"))
|
||||
|
||||
comparisons = [chart for _, _, _, chart in candidates if chart.get("metric") == "composite_rate" and chart.get("sectionKey") == "overview"]
|
||||
primary_depth = min((scope_depth(chart) for chart in comparisons), default=0)
|
||||
def chapter_priority(item):
|
||||
chart = item[3]
|
||||
# 产品追查比较不能挤占主体分析的类别、组织和缺陷图。
|
||||
extra_scope = max(0, scope_depth(chart) - primary_depth)
|
||||
section = chart.get("sectionKey", "")
|
||||
penalty = 20 * extra_scope if section in ("overview", "stage") or section.startswith("category_") else 0
|
||||
return item[0] + penalty
|
||||
|
||||
candidates.sort(key=lambda item: (
|
||||
chapter_priority(item), tuple(-part for part in _chart_end_rank(item[3])),
|
||||
stage_order.get(item[3].get("stage"), 3),
|
||||
metric_order.get(item[3].get("metric"), 10),
|
||||
item[3].get("sectionKey", ""), item[3].get("id", ""),
|
||||
))
|
||||
primary_chapters = []
|
||||
additional_views = []
|
||||
chapter_keys = set()
|
||||
for item in candidates:
|
||||
chart = item[3]
|
||||
section = chart.get("sectionKey")
|
||||
chapter_key = (section, chart.get("metric") if section in ("overview", "stage", "trend") else None,
|
||||
chart.get("type") if section == "composition" else None,
|
||||
chart.get("stage") if section == "composition" else None)
|
||||
if chapter_key in chapter_keys:
|
||||
additional_views.append(item)
|
||||
else:
|
||||
chapter_keys.add(chapter_key)
|
||||
primary_chapters.append(item)
|
||||
# 先覆盖各个可用章节,再分配同章不同范围的补充视图。
|
||||
candidates = primary_chapters + additional_views
|
||||
charts: list[dict[str, Any]] = []
|
||||
selected_ids: set[str] = set()
|
||||
selected_dimensions: set[str] = set()
|
||||
selected_defect_stages: set[str] = set()
|
||||
selected_semantics: set[str] = set()
|
||||
selected_share_stages: set[tuple[str, str]] = set()
|
||||
for _, kind, dimension, chart in candidates:
|
||||
chart_id = chart.get("id")
|
||||
if not isinstance(chart_id, str) or chart_id in selected_ids:
|
||||
continue
|
||||
semantic_key = _chart_selection_key(chart)
|
||||
if semantic_key in selected_semantics:
|
||||
continue
|
||||
share_stage = (chart.get("type"), chart.get("stage"))
|
||||
if chart.get("type") in ("donut", "pareto") and share_stage in selected_share_stages:
|
||||
continue
|
||||
if kind == "quality_changes" and dimension in selected_dimensions:
|
||||
continue
|
||||
if kind == "quality_fine_defects":
|
||||
stage = chart.get("stage")
|
||||
if stage in selected_defect_stages:
|
||||
continue
|
||||
charts.append(chart)
|
||||
selected_ids.add(chart_id)
|
||||
if kind == "quality_changes" and dimension:
|
||||
selected_dimensions.add(dimension)
|
||||
if kind == "quality_fine_defects" and chart.get("stage"):
|
||||
selected_defect_stages.add(chart["stage"])
|
||||
selected_semantics.add(semantic_key)
|
||||
if chart.get("type") in ("donut", "pareto"):
|
||||
selected_share_stages.add(share_stage)
|
||||
if len(charts) >= MAX_VISUALS:
|
||||
|
||||
@@ -47,32 +47,39 @@ def build_report(evidence):
|
||||
def fact(label,text,evidence_ref,kind):
|
||||
row={'id':'F'+str(len(facts)+1),'kind':kind,'label':label,'text':text,'evidenceRef':evidence_ref}
|
||||
facts.append(row);return row
|
||||
def table(title,headers,rows,evidence_ref,notice=''):
|
||||
def bound_lead(entries):
|
||||
return ' '.join(item['text']+'['+item['evidenceRef']+']' for item in entries)
|
||||
def table(title,headers,rows,evidence_ref,notice='',lead=''):
|
||||
if not rows:return
|
||||
sections.append('### '+title+'\n\n| '+' | '.join(headers)+' |\n| '+' | '.join(['---']*len(headers))+' |\n'
|
||||
sections.append('### '+title+'\n\n'+(lead+'\n\n' if lead else '')+'| '+' | '.join(headers)+' |\n| '+' | '.join(['---']*len(headers))+' |\n'
|
||||
+'\n'.join('| '+' | '.join(cell(v) for v in row)+' |' for row in rows)+'\n\n['+evidence_ref+']'+(' '+notice if notice else ''))
|
||||
delta=(result.get('delta') or {}).get('percentagePoints')
|
||||
headline=f'综合合格率:{a}{shown(previous.get("compositeRate"),True)}→{b}{shown(current.get("compositeRate"),True)},{change_text(delta)}。[{ref}]'
|
||||
fact('综合合格率',headline.split('。[')[0]+'。',ref,'overall')
|
||||
rows=[['综合合格率',shown(previous.get('compositeRate'),True),shown(current.get('compositeRate'),True),shown(delta,signed=True)+' pp' if number(delta) is not None else '不可比']]
|
||||
stage_leads=[]
|
||||
for stage,label in (('black','黑片'),('bright','亮片')):
|
||||
now=current.get(stage) or {};before=previous.get(stage) or {};rate_delta=(result.get('stageRateChangesPP') or {}).get(stage)
|
||||
rows.append([label+'合格率',shown(before.get('rate'),True),shown(now.get('rate'),True),shown(rate_delta,signed=True)+' pp' if number(rate_delta) is not None else '不可比'])
|
||||
fact(label+'合格率',f'{label}合格率:{shown(before.get("rate"),True)}→{shown(now.get("rate"),True)},{change_text(rate_delta)}。',ref,'stage')
|
||||
stage_fact=fact(label+'合格率',f'{label}合格率:{shown(before.get("rate"),True)}→{shown(now.get("rate"),True)},{change_text(rate_delta)}。',ref,'stage')
|
||||
if all(number(value) is not None for value in (before.get('rate'),now.get('rate'),rate_delta)):stage_leads.append(stage_fact)
|
||||
for key,name in (('totalWeight','投入重量'),('scrapWeight','报废重量')):
|
||||
rows.append([label+name,shown(before.get(key)),shown(now.get(key)),shown(difference(now.get(key),before.get(key)),signed=True)])
|
||||
table('总体与阶段',['指标',a,b,'变化'],rows,ref,'重量单位:kg;率变化单位:百分点(pp)。')
|
||||
rows=[]
|
||||
table('总体与阶段',['指标',a,b,'变化'],rows,ref,'重量单位:kg;率变化单位:百分点(pp)。',bound_lead(stage_leads))
|
||||
rows=[];category_leads=[]
|
||||
for stage,label in (('black','黑片'),('bright','亮片')):
|
||||
candidates=[]
|
||||
now=current.get(stage) or {};before=previous.get(stage) or {}
|
||||
old={x['name']:x.get('weight') for x in before.get('defects',[])}
|
||||
for item in now.get('defects',[]):
|
||||
name=item['name'];weight=item.get('weight');delta=difference(weight,old.get(name))
|
||||
rows.append([label+'·'+name,shown(old.get(name)),shown(weight),shown(delta,signed=True)])
|
||||
fact(label+'·'+name,f'{label}{name}:{shown(old.get(name))}→{shown(weight)} kg,增减{shown(delta,signed=True)} kg。',ref,'category')
|
||||
entry=fact(label+'·'+name,f'{label}{name}:{shown(old.get(name))}→{shown(weight)} kg,增减{shown(delta,signed=True)} kg。',ref,'category')
|
||||
if number(delta) is not None:candidates.append((abs(number(delta)),entry))
|
||||
if stage=='bright' and now.get('headquartersScrapWeight') is not None:
|
||||
rows.append(['亮片·本部报废',shown(before.get('headquartersScrapWeight')),shown(now.get('headquartersScrapWeight')),shown(difference(now.get('headquartersScrapWeight'),before.get('headquartersScrapWeight')),signed=True)])
|
||||
table('正式报废类别',['类别',a+'(kg)',b+'(kg)','增减(kg)'],rows,ref)
|
||||
if candidates:category_leads.append(max(candidates,key=lambda item:item[0])[1])
|
||||
table('正式报废类别',['类别',a+'(kg)',b+'(kg)','增减(kg)'],rows,ref,lead=('本次已列类别的变化线索:'+bound_lead(category_leads)) if category_leads else '')
|
||||
for document in evidence:
|
||||
q=document['result'];reference=document['evidenceRef']
|
||||
if q.get('kind')!='quality_changes':continue
|
||||
@@ -82,23 +89,26 @@ def build_report(evidence):
|
||||
rate_name=stage_name+'合格率' if stage_name else '综合率'
|
||||
weight_name=stage_name+'报废增量' if stage_name else '两阶段报废增量'
|
||||
if dimension in ('group','department') and same:
|
||||
rows=[]
|
||||
rows=[];leaders=[]
|
||||
for item in q.get('rows',[]):
|
||||
now=item.get('current') or {};before=item.get('comparison') or {};drop=number(item.get('rateDrop'));delta=-drop*100 if drop is not None else None
|
||||
label=str(item.get('label') or item.get('key'))
|
||||
rows.append([label,shown(before.get('rate'),True)+'→'+shown(now.get('rate'),True),shown(delta,signed=True) if delta is not None else '不可比',shown(item.get('scrapDelta'),signed=True)])
|
||||
fact(label,f'{label}:{rate_name}{shown(before.get("rate"),True)}→{shown(now.get("rate"),True)},{change_text(delta)};{weight_name}{shown(item.get("scrapDelta"),signed=True)} kg。',reference,'group')
|
||||
entry=fact(label,f'{label}:{rate_name}{shown(before.get("rate"),True)}→{shown(now.get("rate"),True)},{change_text(delta)};{weight_name}{shown(item.get("scrapDelta"),signed=True)} kg。',reference,'group')
|
||||
if drop is not None:leaders.append((drop,entry))
|
||||
lead=bound_lead([max(leaders,key=lambda item:(item[0]>0,abs(item[0])))[1]]) if leaders else ''
|
||||
table(stage_name+('业务分组变化' if dimension=='group' else '产业部变化'),['范围',rate_name+':比较期→本期','变化(pp)',weight_name+'(kg)'],rows,reference,
|
||||
'报废重量为两阶段描述,不作为单一阶段投入。' if not stage_name else '')
|
||||
'报废重量为两阶段描述,不作为单一阶段投入。' if not stage_name else '',('本次返回的组织中,'+lead) if lead else '')
|
||||
elif dimension=='product' and same:
|
||||
rows=[]
|
||||
rows=[];product_leads=[]
|
||||
for item in q.get('rows',[])[:5]:
|
||||
now=item.get('current') or {};before=item.get('comparison') or {};label=str(item.get('label') or item.get('key'))
|
||||
rows.append([label,shown(now.get('scrapWeight')),shown(item.get('scrapDelta'),signed=True),shown(before.get('rate'),True)+'→'+shown(now.get('rate'),True)])
|
||||
fact(label,f'{label}:{stage_name}报废{shown(before.get("scrapWeight"))}→{shown(now.get("scrapWeight"))} kg,增量{shown(item.get("scrapDelta"),signed=True)} kg;{rate_name}{shown(before.get("rate"),True)}→{shown(now.get("rate"),True)}。',reference,'product')
|
||||
entry=fact(label,f'{label}:{stage_name}报废{shown(before.get("scrapWeight"))}→{shown(now.get("scrapWeight"))} kg,增量{shown(item.get("scrapDelta"),signed=True)} kg;{rate_name}{shown(before.get("rate"),True)}→{shown(now.get("rate"),True)}。',reference,'product')
|
||||
product_leads.append(entry)
|
||||
order={'scrap_delta':'报废增量','current_scrap':'当前报废重量','rate_drop':'合格率降幅'}.get(q.get('sort'),'接口排序')
|
||||
table(stage_name+'重点产品(按'+order+',本次返回前5)',['规格','本期报废(kg)','增量(kg)',rate_name+':比较期→本期'],rows,reference,
|
||||
f'查询共有{q.get("totalRows","未知")}个对象,本节展示所返回排名的前5项。')
|
||||
f'查询共有{q.get("totalRows","未知")}个对象,本节展示所返回排名的前5项。',bound_lead(product_leads[:1]))
|
||||
vcm=False;cross=[]
|
||||
for document in evidence:
|
||||
q=document['result'];reference=document['evidenceRef']
|
||||
@@ -113,11 +123,13 @@ def build_report(evidence):
|
||||
usable.sort(key=lambda row:number(row['currentWeight']),reverse=True)
|
||||
same=scope(q.get('filters'))==binding
|
||||
if same and q.get('dimension')=='defect':
|
||||
rows=[]
|
||||
rows=[];defect_leads=[]
|
||||
for item in usable[:5]:
|
||||
label=str(item.get('field'));rows.append([label,shown(item.get('comparisonWeight')),shown(item.get('currentWeight')),shown(item.get('deltaWeight'),signed=True) if item.get('deltaAvailable') is True else '不可比'])
|
||||
fact(stage+'·'+label,f'{stage}{label}:{shown(item.get("comparisonWeight"))}→{shown(item.get("currentWeight"))} kg,增量{shown(item.get("deltaWeight"),signed=True) if item.get("deltaAvailable") is True else "不可比"}。',reference,'defect')
|
||||
table(stage+'来源具体缺陷(按本期重量,前5)',['源字段',a+'(kg)',b+'(kg)','增量(kg)'],rows,reference)
|
||||
entry=fact(stage+'·'+label,f'{stage}{label}:{shown(item.get("comparisonWeight"))}→{shown(item.get("currentWeight"))} kg,增量{shown(item.get("deltaWeight"),signed=True) if item.get("deltaAvailable") is True else "不可比"}。',reference,'defect')
|
||||
if item.get('deltaAvailable') is True and number(item.get('deltaWeight')) is not None:defect_leads.append((abs(number(item['deltaWeight'])),entry))
|
||||
lead=bound_lead([max(defect_leads,key=lambda item:item[0])[1]]) if defect_leads else ''
|
||||
table(stage+'来源具体缺陷(按本期重量,前5)',['源字段',a+'(kg)',b+'(kg)','增量(kg)'],rows,reference,lead=lead)
|
||||
elif usable:
|
||||
details=scope(q.get('filters'));label_prefix='·'.join(str(v) for k,v in details.items() if k in ('group','product'))
|
||||
for item in usable[:2]:
|
||||
|
||||
+15
-10
@@ -1,15 +1,19 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { sanitizeAnalysisDisplayText } from './analysisDisplayText';
|
||||
|
||||
function inlineMarkdown(value: string, keyPrefix = 'inline'): ReactNode[] {
|
||||
function inlineMarkdown(value: string, keyPrefix = 'inline', evidenceLabels?: Record<string, string>, evidencePrefix = ''): ReactNode[] {
|
||||
const references = (part: string, key: string): ReactNode => !evidenceLabels ? part : part.split(/(\[?Q[A-F0-9]{8}\]?)/g).map((token, index) => {
|
||||
const ref = token.replace(/^\[|\]$/g, '');
|
||||
return evidenceLabels[ref] ? <a className="analysis-evidence-ref" key={`${key}-${index}`} href={`#${evidencePrefix}${ref}`} title={ref}>{evidenceLabels[ref]}</a> : token;
|
||||
});
|
||||
return value.split(/(\*\*.+?\*\*|`[^`]+`)/g).map((part, index) => {
|
||||
if (part.startsWith('**') && part.endsWith('**') && part.length >= 4) {
|
||||
return <strong key={`${keyPrefix}-${index}`}>{part.slice(2, -2)}</strong>;
|
||||
return <strong key={`${keyPrefix}-${index}`}>{references(part.slice(2, -2), `${keyPrefix}-${index}`)}</strong>;
|
||||
}
|
||||
if (part.startsWith('`') && part.endsWith('`') && part.length >= 2) {
|
||||
return <code key={`${keyPrefix}-${index}`}>{part.slice(1, -1)}</code>;
|
||||
}
|
||||
return part;
|
||||
return references(part, `${keyPrefix}-${index}`);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -33,7 +37,8 @@ function isBlockStart(lines: string[], index: number): boolean {
|
||||
}
|
||||
|
||||
/** Renders the small Markdown subset used by analysis answers with React text nodes only. */
|
||||
export function AiMarkdown({ content, className }: { content: string; className?: string }) {
|
||||
export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix }: { content: string; className?: string; evidenceLabels?: Record<string, string>; evidencePrefix?: string }) {
|
||||
const inline = (value: string, key: string) => inlineMarkdown(value, key, evidenceLabels, evidencePrefix);
|
||||
const lines = sanitizeAnalysisDisplayText(content).replaceAll('\r\n', '\n').replaceAll('\r', '\n').split('\n');
|
||||
const blocks: ReactNode[] = [];
|
||||
let index = 0;
|
||||
@@ -56,7 +61,7 @@ export function AiMarkdown({ content, className }: { content: string; className?
|
||||
if (heading) {
|
||||
const level = heading[1].length;
|
||||
const key = `heading-${blocks.length}`;
|
||||
const children = inlineMarkdown(heading[2], key);
|
||||
const children = inline(heading[2], key);
|
||||
if (level === 1) blocks.push(<h1 key={key}>{children}</h1>);
|
||||
else if (level === 2) blocks.push(<h2 key={key}>{children}</h2>);
|
||||
else if (level === 3) blocks.push(<h3 key={key}>{children}</h3>);
|
||||
@@ -73,8 +78,8 @@ export function AiMarkdown({ content, className }: { content: string; className?
|
||||
const body: string[][] = [];
|
||||
while (index < lines.length && lines[index].trim() && lines[index].includes('|')) body.push(tableCells(lines[index++]));
|
||||
blocks.push(<div className="ai-markdown-table-wrap" key={`table-${blocks.length}`}><table>
|
||||
<thead><tr><th className="ai-markdown-index">序号</th>{headers.map((cell, cellIndex) => <th key={cellIndex}>{inlineMarkdown(cell, `th-${cellIndex}`)}</th>)}</tr></thead>
|
||||
<tbody>{body.map((row, rowIndex) => <tr key={rowIndex}><td className="ai-markdown-index">{rowIndex + 1}</td>{headers.map((_, cellIndex) => <td key={cellIndex}>{inlineMarkdown(row[cellIndex] || '', `td-${rowIndex}-${cellIndex}`)}</td>)}</tr>)}</tbody>
|
||||
<thead><tr><th className="ai-markdown-index">序号</th>{headers.map((cell, cellIndex) => <th key={cellIndex}>{inline(cell, `th-${cellIndex}`)}</th>)}</tr></thead>
|
||||
<tbody>{body.map((row, rowIndex) => <tr key={rowIndex}><td className="ai-markdown-index">{rowIndex + 1}</td>{headers.map((_, cellIndex) => <td key={cellIndex}>{inline(row[cellIndex] || '', `td-${rowIndex}-${cellIndex}`)}</td>)}</tr>)}</tbody>
|
||||
</table></div>);
|
||||
continue;
|
||||
}
|
||||
@@ -91,8 +96,8 @@ export function AiMarkdown({ content, className }: { content: string; className?
|
||||
index += 1;
|
||||
}
|
||||
blocks.push(ordered
|
||||
? <ol key={`list-${blocks.length}`} start={firstNumber}>{list.map((item, itemIndex) => <li key={itemIndex}>{inlineMarkdown(item, `ol-${blocks.length}-${itemIndex}`)}</li>)}</ol>
|
||||
: <ul key={`list-${blocks.length}`}>{list.map((item, itemIndex) => <li key={itemIndex}>{inlineMarkdown(item, `ul-${blocks.length}-${itemIndex}`)}</li>)}</ul>);
|
||||
? <ol key={`list-${blocks.length}`} start={firstNumber}>{list.map((item, itemIndex) => <li key={itemIndex}>{inline(item, `ol-${blocks.length}-${itemIndex}`)}</li>)}</ol>
|
||||
: <ul key={`list-${blocks.length}`}>{list.map((item, itemIndex) => <li key={itemIndex}>{inline(item, `ul-${blocks.length}-${itemIndex}`)}</li>)}</ul>);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -101,7 +106,7 @@ export function AiMarkdown({ content, className }: { content: string; className?
|
||||
if (!paragraph.length) { index += 1; continue; }
|
||||
blocks.push(<p key={`paragraph-${blocks.length}`}>{paragraph.flatMap((part, partIndex) => [
|
||||
...(partIndex ? [<br key={`break-${partIndex}`} />] : []),
|
||||
...inlineMarkdown(part, `paragraph-${blocks.length}-${partIndex}`),
|
||||
...inline(part, `paragraph-${blocks.length}-${partIndex}`),
|
||||
])}</p>);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
type Row = Record<string, unknown>;
|
||||
const record = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||
const rows = (value: unknown): Row[] => Array.isArray(value) ? value.map(record) : [];
|
||||
const text = (value: unknown) => value === null || value === undefined || value === '' ? '—' : String(value);
|
||||
const rate = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? `${(value * 100).toFixed(2)}%` : '—';
|
||||
const number = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString('zh-CN', { maximumFractionDigits: 2 }) : '—';
|
||||
const period = (value: unknown) => { const c = record(value); return c.year ? `${c.year}年${c.month ? `${c.month}月` : c.quarter ? `第${c.quarter}季度` : ''}` : ''; };
|
||||
const stageName = (value: unknown) => value === 'black' ? '黑片' : value === 'bright' ? '亮片' : '';
|
||||
const metricName = (value: unknown) => ({ BLACK_RATE: '黑片合格率', BRIGHT_RATE: '亮片合格率', COMPOSITE_RATE: '综合合格率', COMPOSITE_RATE_WITHOUT_HEADQUARTERS_SCRAP: '综合合格率(不含本部报废)', BRIGHT_RATE_WITHOUT_HEADQUARTERS_SCRAP: '亮片合格率(不含本部报废)' }[String(value)] || '合格率');
|
||||
|
||||
export function AnalysisLegacyResults({ turn }: { turn: Row }) {
|
||||
const result = Object.keys(record(turn.result)).length ? record(turn.result) : turn;
|
||||
const results = rows(result.results || turn.results);
|
||||
const comparisons = results.filter(item => item.current && item.comparison && item.delta);
|
||||
const snapshots = results.filter(item => item.summary && item.context);
|
||||
const main = comparisons.length ? record(comparisons[0].current) : snapshots[0] || {};
|
||||
const summary = record(main.summary);
|
||||
const black = record(summary.black); const bright = record(summary.bright);
|
||||
const coverage = record(summary.coverage);
|
||||
const selectedMetric = String(comparisons[0]?.metric || record(record(result.task || turn.task).conditions).metricCode || 'COMPOSITE_RATE');
|
||||
const adjusted = selectedMetric.includes('WITHOUT_HEADQUARTERS_SCRAP');
|
||||
if (!results.length) return null;
|
||||
return <section className="q-report-legacy-results"><h2>保存的统计数据</h2>
|
||||
{Object.keys(summary).length > 0 && <div className="q-kpis">
|
||||
<div className="q-kpi"><span>{adjusted ? '综合合格率(不含本部报废)' : '综合合格率'}</span><strong>{coverage.blackRows === 0 && coverage.brightRows === 0 ? '—' : rate(adjusted ? summary.compositeRateWithoutHeadquartersScrap : summary.compositeRate)}</strong></div>
|
||||
<div className="q-kpi"><span>黑片合格率</span><strong>{coverage.blackRows === 0 ? '—' : rate(black.rate)}</strong></div>
|
||||
<div className="q-kpi"><span>{adjusted ? '亮片合格率(不含本部报废)' : '亮片合格率'}</span><strong>{coverage.brightRows === 0 ? '—' : rate(adjusted ? bright.rateWithoutHeadquartersScrap : bright.rate)}</strong></div>
|
||||
</div>}
|
||||
{comparisons.map((item, index) => {
|
||||
const current = record(item.current), comparison = record(item.comparison), delta = record(item.delta), comparable = record(item.comparability);
|
||||
const value = (side: Row) => { const s = record(side.summary); switch (item.metric) { case 'BLACK_RATE': return rate(record(s.black).rate); case 'BRIGHT_RATE': return rate(record(s.bright).rate); case 'BRIGHT_RATE_WITHOUT_HEADQUARTERS_SCRAP': return rate(record(s.bright).rateWithoutHeadquartersScrap); case 'COMPOSITE_RATE_WITHOUT_HEADQUARTERS_SCRAP': return rate(s.compositeRateWithoutHeadquartersScrap); default: return rate(s.compositeRate); } };
|
||||
return <section key={`compare-${index}`}><h2>{metricName(item.metric)} · 期间比较</h2><table><thead><tr><th>序号</th><th>期间</th><th>正式结果</th></tr></thead><tbody><tr><td>1</td><td>{period(current.context)}</td><td>{value(current)}</td></tr><tr><td>2</td><td>{period(comparison.context)}</td><td>{value(comparison)}</td></tr><tr><td>3</td><td>变化(百分点)</td><td>{number(delta.percentagePoints)}</td></tr></tbody></table>{comparable.comparable === false && <p className="q-note">{text(comparable.reason || (Array.isArray(comparable.reasons) ? comparable.reasons.join(';') : '所选期间不可比,不给出变化结论。'))}</p>}</section>;
|
||||
})}
|
||||
{results.filter(item => Array.isArray(item.groups)).map((item, index) => {
|
||||
const available = item.available === true;
|
||||
const ranked = [...rows(item.groups)].filter(row => typeof row[available ? 'impactPP' : 'scrapDelta'] === 'number').sort((a, b) => available ? Number(a.impactPP) - Number(b.impactPP) : Number(b.scrapDelta) - Number(a.scrapDelta)).slice(0, 10);
|
||||
if (!ranked.length) return null;
|
||||
return <section key={`impact-${index}`}><h2>{stageName(item.stage)} · 优先核查对象</h2><table><thead><tr><th>序号</th><th>产品 / 规格</th><th>当前合格率</th><th>比较期合格率</th><th>{available ? '影响(百分点)' : '报废增量(kg)'}</th></tr></thead><tbody>{ranked.map((row, i) => <tr key={i}><td>{i + 1}</td><td>{text(row.label || row.key)}</td><td>{rate(row.currentRate)}</td><td>{rate(row.comparisonRate)}</td><td>{number(available ? row.impactPP : row.scrapDelta)}</td></tr>)}</tbody></table>{!available && <p className="q-note">按报废增量列出前10项。分组无法完整回加,仅作核查线索,不能当作整体下降贡献。</p>}</section>;
|
||||
})}
|
||||
{results.filter(item => item.kind === 'analysis_statistics').map((item, index) => <section key={`trend-${index}`}><h2>{stageName(item.stage)} · 历史趋势</h2><table><thead><tr><th>序号</th><th>期间</th><th>阶段合格率</th></tr></thead><tbody>{rows(item.trendChange).map((row, i) => <tr key={i}><td>{i + 1}</td><td>{text(row.label || row.period)}</td><td>{rate(row.stageRate)}</td></tr>)}</tbody></table></section>)}
|
||||
{results.filter(item => Array.isArray(item.rows) && item.dimension && item.stage).map((item, index) => <section key={`top-${index}`}><h2>{stageName(item.stage)} · TOP核查对象</h2><table><thead><tr><th>序号</th><th>对象</th><th>报废重量(kg)</th><th>占比</th></tr></thead><tbody>{rows(item.rows).slice(0, 10).map((row, i) => <tr key={i}><td>{i + 1}</td><td>{text(row.label || row.key)}</td><td>{number(row.weight)}</td><td>{rate(row.share)}</td></tr>)}</tbody></table></section>)}
|
||||
</section>;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useMemo } from 'react';
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
import { AnalysisVisuals } from './AnalysisVisuals';
|
||||
import { buildAnalysisNarrative, useCompactRateComparison, type NarrativeSection } from './analysisReportModel';
|
||||
import { visualPeriodSummary, visualScopeSummary, type AnalysisVisual } from './analysisVisualsModel';
|
||||
import './analysis-narrative.css';
|
||||
|
||||
function metricName(visual: AnalysisVisual): string {
|
||||
return ({ composite_rate: '综合合格率', black_rate: '黑片合格率', bright_rate: '亮片合格率' } as Record<string, string>)[visual.metric] || visual.series[0].label;
|
||||
}
|
||||
|
||||
export function RateComparisonReadout({ visual }: { visual: AnalysisVisual }) {
|
||||
const [before, after] = visual.series[0].values as [number, number];
|
||||
const delta = (after - before) * 100;
|
||||
const changed = Math.abs(delta) >= 0.005;
|
||||
const { stage: _stage, ...businessScope } = visual.scope;
|
||||
const scopeLabel = visualScopeSummary(businessScope);
|
||||
return <div className="analysis-rate-readout" aria-label={`${metricName(visual)}两期比较`}>
|
||||
<div className="analysis-rate-name">{metricName(visual)}</div>
|
||||
{scopeLabel && <div className="analysis-rate-scope">{scopeLabel}</div>}
|
||||
<div className="analysis-rate-values">
|
||||
<div className="analysis-rate-previous"><small>{visualPeriodSummary({ ...visual, period: visual.comparisonPeriod!, comparisonPeriod: undefined })}</small><span>{(before * 100).toFixed(2)}<em>%</em></span></div>
|
||||
<span className="analysis-rate-arrow" aria-hidden="true">→</span>
|
||||
<div className="analysis-rate-current"><small>{visualPeriodSummary({ ...visual, comparisonPeriod: undefined })}</small><strong>{(after * 100).toFixed(2)}<em>%</em></strong></div>
|
||||
<div className={`analysis-rate-change ${changed ? delta < 0 ? 'is-worse' : 'is-better' : ''}`}><strong>{changed ? `${delta > 0 ? '+' : ''}${delta.toFixed(2)}` : '0.00'}</strong><span>个百分点 · {changed ? delta < 0 ? '下降' : '上升' : '持平'}</span></div>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
|
||||
export function NarrativeEvidence({ model, prefix }: { model: ReturnType<typeof buildAnalysisNarrative>; prefix: string }) {
|
||||
if (!model.evidence.length) return null;
|
||||
return <footer className="analysis-narrative-evidence"><h3>数据依据</h3><ol>{model.evidence.map(item => <li id={`${prefix}${item.ref}`} key={item.ref}><strong>{item.label}</strong><span>{item.context}</span><code>{item.ref}</code></li>)}</ol></footer>;
|
||||
}
|
||||
|
||||
/** 聊天、HTML 和图片报告共用同一套章节与图表关联。 */
|
||||
export function AnalysisNarrative({ answer, visuals, visualState, question, turnId, beforeExport }: {
|
||||
answer: string; visuals: unknown; visualState?: unknown; question?: string; turnId?: string; beforeExport?: () => Promise<void>;
|
||||
}) {
|
||||
const model = useMemo(() => buildAnalysisNarrative(answer, visuals, question), [answer, visuals, question]);
|
||||
const prefix = `chat-${String(turnId || 'answer').replace(/[^a-zA-Z0-9_-]/g, '')}-`;
|
||||
const renderText = (content: string) => <AiMarkdown className="ai-answer" content={content} evidenceLabels={model.evidenceLabels} evidencePrefix={prefix} />;
|
||||
const compact = (visual: AnalysisVisual) => useCompactRateComparison(visual, question);
|
||||
const comparisons = model.sections.flatMap(section => section.visuals).filter(compact);
|
||||
const renderSection = (section: NarrativeSection) => {
|
||||
const figures = section.visuals.filter(visual => !compact(visual));
|
||||
const hasFigures = figures.some(visual => visual.chartable);
|
||||
const sectionComparisons = section.visuals.filter(compact);
|
||||
return <section key={section.id} className={`analysis-narrative-section is-${section.kind}`} data-section-kind={section.kind}>
|
||||
{section.title && <h3 className="analysis-narrative-title">{section.title}</h3>}
|
||||
{section.narrative && renderText(section.narrative)}
|
||||
{!!sectionComparisons.length && <div className="analysis-rate-grid">{sectionComparisons.map(visual => <RateComparisonReadout key={visual.id} visual={visual} />)}</div>}
|
||||
{!!figures.length && <AnalysisVisuals visuals={figures} visualState="ready" beforeExport={beforeExport} embedded />}
|
||||
{!!section.tables.length && (hasFigures || sectionComparisons.length > 0
|
||||
? <details className="analysis-narrative-details"><summary>查看本节数据与明细</summary>{section.tables.map((table, index) => <div key={index}>{renderText(table)}</div>)}</details>
|
||||
: section.tables.map((table, index) => <div key={index}>{renderText(table)}</div>))}
|
||||
</section>;
|
||||
};
|
||||
return <div className={`analysis-narrative ${comparisons.length ? 'has-comparisons' : ''}`}>
|
||||
{model.sections.map(renderSection)}
|
||||
{!model.sections.some(section => section.visuals.length) && <AnalysisVisuals visuals={visuals} visualState={visualState} beforeExport={beforeExport} />}
|
||||
<NarrativeEvidence model={model} prefix={prefix} />
|
||||
</div>;
|
||||
}
|
||||
@@ -2,22 +2,22 @@ import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Modal } from 'antd';
|
||||
import { DownloadOutlined } from '@ant-design/icons';
|
||||
import { toPng } from 'html-to-image';
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
import { AnalysisLegacyResults } from './AnalysisLegacyResults';
|
||||
import { AnalysisReportNarrative } from './AnalysisReportNarrative';
|
||||
import { buildAnalysisNarrative } from './analysisReportModel';
|
||||
import { integrateNativeReportNarrative } from './nativeReportNarrative';
|
||||
import narrativeCss from './analysis-narrative.css?inline';
|
||||
import { analysisDisplayTextRemovalRanges, sanitizeAnalysisDisplayText } from './analysisDisplayText';
|
||||
import { ReportVisualSections, reportVisualHtml, useReportVisualImages, type ReportVisualImage } from './AnalysisReportVisuals';
|
||||
import { useReportVisualImages, type ReportVisualImage } from './AnalysisReportVisuals';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
const record = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||
const rows = (value: unknown): Row[] => Array.isArray(value) ? value.map(record) : [];
|
||||
const text = (value: unknown) => value === null || value === undefined || value === '' ? '—' : String(value);
|
||||
const rate = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? `${(value * 100).toFixed(2)}%` : '—';
|
||||
const number = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString('zh-CN', { maximumFractionDigits: 2 }) : '—';
|
||||
const period = (value: unknown) => { const c = record(value); return c.year ? `${c.year}年${c.month ? `${c.month}月` : c.quarter ? `第${c.quarter}季度` : ''}` : ''; };
|
||||
const stageName = (value: unknown) => value === 'black' ? '黑片' : value === 'bright' ? '亮片' : '';
|
||||
const metricName = (value: unknown) => ({ BLACK_RATE: '黑片合格率', BRIGHT_RATE: '亮片合格率', COMPOSITE_RATE: '综合合格率', COMPOSITE_RATE_WITHOUT_HEADQUARTERS_SCRAP: '综合合格率(不含本部报废)', BRIGHT_RATE_WITHOUT_HEADQUARTERS_SCRAP: '亮片合格率(不含本部报废)' }[String(value)] || '合格率');
|
||||
const escape = (value: string) => value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"');
|
||||
|
||||
const reportCss = `
|
||||
${narrativeCss}
|
||||
|
||||
.q-report .ai-markdown-table-wrap{height:auto!important;max-height:none!important;overflow:visible!important;border:0;border-radius:0;background:#fff;margin:10px 0 14px}.q-report .ai-markdown{color:inherit;font:inherit}.q-report .ai-markdown pre{white-space:pre-wrap;overflow-wrap:anywhere}
|
||||
.q-report{--surface:#fff;--blue-soft:#eef1ff;--line:#dfe5ef;--ink:#202b3c;--muted-ink:#738197;box-sizing:border-box;width:900px;padding:52px;background:#fff;color:#202b3c;font:15px/1.85 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;overflow-wrap:anywhere}
|
||||
.q-report *{box-sizing:border-box}.q-report header{padding-bottom:26px;border-bottom:2px solid #355f9b}.q-report .q-eyebrow{font-size:12px;letter-spacing:2px;color:#53739c}.q-report h1{font-size:27px;line-height:1.5;margin:10px 0}.q-report .q-subtitle{font-size:12px;color:#69778b}.q-report h2{font-size:18px;margin:30px 0 12px}.q-report p{margin:10px 0}.q-report .q-prose{white-space:pre-wrap}.q-report .q-kpis{display:flex;gap:12px;margin:22px 0}.q-report .q-kpi{flex:1;padding:17px 18px;background:#f2f6fb;border-radius:6px}.q-report .q-kpi span{display:block;font-size:12px;color:#66778d}.q-report .q-kpi strong{display:block;font-size:27px;font-variant-numeric:tabular-nums;color:#254f87}.q-report table{width:100%;border:1px solid #dfe5ef;border-collapse:collapse;font-size:13px;table-layout:fixed}.q-report th{background:#f2f6fb;color:#53657c;text-align:center;font-weight:650}.q-report th,.q-report td{padding:10px 12px;border:1px solid #dfe5ef;text-align:center;vertical-align:middle}.q-report tbody tr:nth-child(even){background:#f8fafd}.q-report th:first-child,.q-report td:first-child{width:62px;color:#738197;font-variant-numeric:tabular-nums}.q-report .q-note{font-size:12px;color:#69778b}.q-report footer{margin-top:34px;padding-top:16px;border-top:1px solid #dde5ef;font-size:11px;color:#738197}.q-report .q-partial{color:#996b20}@media print{body{margin:0}.q-report{width:100%;padding:20px}tr{break-inside:avoid}}
|
||||
@@ -25,47 +25,38 @@ const reportCss = `
|
||||
|
||||
function ReportDocument({ turn, stamp, visualImages }: { turn: Row; stamp: string; visualImages: ReportVisualImage[] }) {
|
||||
const result = Object.keys(record(turn.result)).length ? record(turn.result) : turn;
|
||||
const results = rows(result.results || turn.results);
|
||||
const comparisons = results.filter(item => item.current && item.comparison && item.delta);
|
||||
const snapshots = results.filter(item => item.summary && item.context);
|
||||
const main = comparisons.length ? record(comparisons[0].current) : snapshots[0] || {};
|
||||
const summary = record(main.summary);
|
||||
const black = record(summary.black); const bright = record(summary.bright);
|
||||
const coverage = record(summary.coverage);
|
||||
const selectedMetric = String(comparisons[0]?.metric || record(record(result.task || turn.task).conditions).metricCode || 'COMPOSITE_RATE');
|
||||
const adjusted = selectedMetric.includes('WITHOUT_HEADQUARTERS_SCRAP');
|
||||
const answer = sanitizeAnalysisDisplayText(text(result.answer || turn.answer));
|
||||
const question = sanitizeAnalysisDisplayText(String(turn.question || '质量分析报告'));
|
||||
const answer = sanitizeAnalysisDisplayText(text(result.reportMarkdown || turn.reportMarkdown || result.answer || turn.answer));
|
||||
const model = buildAnalysisNarrative(answer, result.visuals || turn.visuals, String(turn.question || ''));
|
||||
return <div className="q-report">
|
||||
<style>{reportCss}</style>
|
||||
<header><div className="q-eyebrow">质量数据分析平台 · 分析报告</div><h1>{question.length > 90 ? `${question.slice(0, 90)}…` : question}</h1><div className="q-subtitle">{period(main.context)}{period(main.context) ? ' · ' : ''}{stamp}</div></header>
|
||||
<header><div className="q-eyebrow">质量数据分析平台 · 分析报告</div><h1>{model.title.length > 90 ? `${model.title.slice(0, 90)}…` : model.title}</h1>
|
||||
<div className="q-subtitle">{[model.period, model.scope, stamp].filter(Boolean).join(' · ')}</div>
|
||||
{String(turn.question || '') !== model.title && <p className="q-report-question">{sanitizeAnalysisDisplayText(String(turn.question || ''))}</p>}
|
||||
</header>
|
||||
{String(turn.status || result.status) === 'PARTIAL' && <p className="q-partial">本次分析部分完成,以下保留已获得的结果。</p>}
|
||||
{Object.keys(summary).length > 0 && <div className="q-kpis">
|
||||
<div className="q-kpi"><span>{adjusted ? '综合合格率(不含本部报废)' : '综合合格率'}</span><strong>{coverage.blackRows === 0 && coverage.brightRows === 0 ? '—' : rate(adjusted ? summary.compositeRateWithoutHeadquartersScrap : summary.compositeRate)}</strong></div>
|
||||
<div className="q-kpi"><span>黑片合格率</span><strong>{coverage.blackRows === 0 ? '—' : rate(black.rate)}</strong></div>
|
||||
<div className="q-kpi"><span>{adjusted ? '亮片合格率(不含本部报废)' : '亮片合格率'}</span><strong>{coverage.brightRows === 0 ? '—' : rate(adjusted ? bright.rateWithoutHeadquartersScrap : bright.rate)}</strong></div>
|
||||
</div>}
|
||||
<section><h2>分析结论</h2><AiMarkdown content={answer} /></section>
|
||||
<ReportVisualSections turn={turn} images={visualImages} />
|
||||
{comparisons.map((item, index) => {
|
||||
const current = record(item.current), comparison = record(item.comparison), delta = record(item.delta), comparable = record(item.comparability);
|
||||
const value = (side: Row) => { const s = record(side.summary); switch (item.metric) { case 'BLACK_RATE': return rate(record(s.black).rate); case 'BRIGHT_RATE': return rate(record(s.bright).rate); case 'BRIGHT_RATE_WITHOUT_HEADQUARTERS_SCRAP': return rate(record(s.bright).rateWithoutHeadquartersScrap); case 'COMPOSITE_RATE_WITHOUT_HEADQUARTERS_SCRAP': return rate(s.compositeRateWithoutHeadquartersScrap); default: return rate(s.compositeRate); } };
|
||||
return <section key={`compare-${index}`}><h2>{metricName(item.metric)} · 期间比较</h2><table><thead><tr><th>序号</th><th>期间</th><th>正式结果</th></tr></thead><tbody><tr><td>1</td><td>{period(current.context)}</td><td>{value(current)}</td></tr><tr><td>2</td><td>{period(comparison.context)}</td><td>{value(comparison)}</td></tr><tr><td>3</td><td>变化(百分点)</td><td>{number(delta.percentagePoints)}</td></tr></tbody></table>{comparable.comparable === false && <p className="q-note">{text(comparable.reason || (Array.isArray(comparable.reasons) ? comparable.reasons.join(';') : '所选期间不可比,不给出变化结论。'))}</p>}</section>;
|
||||
})}
|
||||
{results.filter(item => Array.isArray(item.groups)).map((item, index) => {
|
||||
const available = item.available === true;
|
||||
const ranked = [...rows(item.groups)].filter(row => typeof row[available ? 'impactPP' : 'scrapDelta'] === 'number').sort((a, b) => available ? Number(a.impactPP) - Number(b.impactPP) : Number(b.scrapDelta) - Number(a.scrapDelta)).slice(0, 10);
|
||||
if (!ranked.length) return null;
|
||||
return <section key={`impact-${index}`}><h2>{stageName(item.stage)} · 优先核查对象</h2><table><thead><tr><th>序号</th><th>产品 / 规格</th><th>当前合格率</th><th>比较期合格率</th><th>{available ? '影响(百分点)' : '报废增量(kg)'}</th></tr></thead><tbody>{ranked.map((row, i) => <tr key={i}><td>{i + 1}</td><td>{text(row.label || row.key)}</td><td>{rate(row.currentRate)}</td><td>{rate(row.comparisonRate)}</td><td>{number(available ? row.impactPP : row.scrapDelta)}</td></tr>)}</tbody></table>{!available && <p className="q-note">按报废增量列出前10项。分组无法完整回加,仅作核查线索,不能当作整体下降贡献。</p>}</section>;
|
||||
})}
|
||||
{results.filter(item => item.kind === 'analysis_statistics').map((item, index) => <section key={`trend-${index}`}><h2>{stageName(item.stage)} · 历史趋势</h2><table><thead><tr><th>序号</th><th>期间</th><th>阶段合格率</th></tr></thead><tbody>{rows(item.trendChange).map((row, i) => <tr key={i}><td>{i + 1}</td><td>{text(row.label || row.period)}</td><td>{rate(row.stageRate)}</td></tr>)}</tbody></table></section>)}
|
||||
{results.filter(item => Array.isArray(item.rows) && item.dimension && item.stage).map((item, index) => <section key={`top-${index}`}><h2>{stageName(item.stage)} · TOP核查对象</h2><table><thead><tr><th>序号</th><th>对象</th><th>报废重量(kg)</th><th>占比</th></tr></thead><tbody>{rows(item.rows).slice(0, 10).map((row, i) => <tr key={i}><td>{i + 1}</td><td>{text(row.label || row.key)}</td><td>{number(row.weight)}</td><td>{rate(row.share)}</td></tr>)}</tbody></table></section>)}
|
||||
<footer>数据来源:质量数据分析平台。指标沿用正式计算口径,原因判断的依据与局限见分析结论。</footer>
|
||||
<AnalysisReportNarrative turn={turn} answer={answer} images={visualImages} />
|
||||
<AnalysisLegacyResults turn={turn} />
|
||||
<footer>数据来源:质量数据分析平台。指标沿用正式计算口径;数据明细保留在 HTML 附录,现场原因以实际核查为准。</footer>
|
||||
</div>;
|
||||
}
|
||||
|
||||
function download(href: string, name: string) { const link = document.createElement('a'); link.href = href; link.download = name; link.click(); }
|
||||
|
||||
/** 图片无法展开明细,生成前临时展开全部附录。 */
|
||||
async function captureReportImage(node: HTMLElement, options: NonNullable<Parameters<typeof toPng>[1]> = {}) {
|
||||
const details = [...node.querySelectorAll('details')].map(element => ({ element, open: element.open }));
|
||||
details.forEach(({ element }) => { element.open = true; });
|
||||
try {
|
||||
await node.ownerDocument.fonts?.ready;
|
||||
await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
|
||||
const height = Math.max(node.scrollHeight, node.offsetHeight);
|
||||
if (height > 16000) throw new Error('报告较长,请下载 HTML 查看完整图文与明细。');
|
||||
return await toPng(node, { height, backgroundColor: '#ffffff', ...options });
|
||||
} finally {
|
||||
details.forEach(({ element, open }) => { element.open = open; });
|
||||
}
|
||||
}
|
||||
|
||||
function removeDisplayMetadataFromElement(element: Element): void {
|
||||
const walker = element.ownerDocument.createTreeWalker(element, NodeFilter.SHOW_TEXT);
|
||||
const textNodes: Array<{ node: Text; start: number; end: number }> = [];
|
||||
@@ -220,9 +211,7 @@ export function AnalysisReportExport({ turn }: { turn: Row }) {
|
||||
try {
|
||||
await visualReport.authorize();
|
||||
if (generation !== exportGeneration.current) return;
|
||||
await document.fonts.ready;
|
||||
if (report.scrollHeight > 16000) throw new Error('报告较长,请下载 HTML 查看完整图文。');
|
||||
const png = await toPng(report, { pixelRatio: 2, backgroundColor: '#ffffff', skipFonts: true });
|
||||
const png = await captureReportImage(report, { pixelRatio: 2, skipFonts: true });
|
||||
if (generation !== exportGeneration.current) return;
|
||||
download(png, `${title}.png`);
|
||||
message.success(visualReport.failed ? '报告图片已生成,未能绘制的图表已保留数据表。' : '报告图片已生成');
|
||||
@@ -258,7 +247,7 @@ export function NativeAnalysisReport({ turn, reportMarkdown, reportHtml }: {
|
||||
const safeHtml = useMemo(() => {
|
||||
const html = reportHtml?.trim() ? safeNativeHtml(reportHtml) : '';
|
||||
if (!html) return '';
|
||||
return html.replace(/<\/body>/i, `${reportVisualHtml(turn, visualReport.images)}</body>`);
|
||||
return integrateNativeReportNarrative(html, turn, visualReport.images);
|
||||
}, [reportHtml, turn, visualReport.images]);
|
||||
const title = useMemo(() => {
|
||||
const nativeTitle = safeHtml ? new DOMParser().parseFromString(safeHtml, 'text/html').title : '';
|
||||
@@ -267,13 +256,14 @@ export function NativeAnalysisReport({ turn, reportMarkdown, reportHtml }: {
|
||||
}, [safeHtml, reportMarkdown, turn.question]);
|
||||
|
||||
const saveHtml = async () => {
|
||||
if (!safeHtml) return;
|
||||
const html = safeHtml || `<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><title>${escape(title)}</title><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:"></head><body>${fallbackNode.current?.innerHTML || ''}</body></html>`;
|
||||
if (!safeHtml && !fallbackNode.current) return;
|
||||
const generation = ++exportGeneration.current;
|
||||
setExporting(true);
|
||||
try {
|
||||
await visualReport.authorize();
|
||||
if (generation !== exportGeneration.current) return;
|
||||
const url = URL.createObjectURL(new Blob([safeHtml], { type: 'text/html;charset=utf-8' }));
|
||||
const url = URL.createObjectURL(new Blob([html], { type: 'text/html;charset=utf-8' }));
|
||||
download(url, `${title}.html`);
|
||||
setTimeout(() => URL.revokeObjectURL(url), 10000);
|
||||
message.success(visualReport.failed ? 'HTML 已生成,未能绘制的图表已保留数据表。' : 'HTML 报告已生成');
|
||||
@@ -302,18 +292,11 @@ export function NativeAnalysisReport({ turn, reportMarkdown, reportHtml }: {
|
||||
if (safeHtml) {
|
||||
const doc = iframe.current?.contentDocument;
|
||||
if (!doc?.body) throw new Error('原生报告尚未载入');
|
||||
await doc.fonts?.ready;
|
||||
await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
|
||||
const height = Math.max(frameContentHeight(doc), frameHeight);
|
||||
if (height > 16000) throw new Error('报告较长,请下载 HTML 查看完整图文。');
|
||||
png = await toPng(doc.body, { width: 900, height, pixelRatio: 1, backgroundColor: '#ffffff', fontEmbedCSS: frameFontCss(doc) });
|
||||
png = await captureReportImage(doc.body, { width: 900, pixelRatio: 1, fontEmbedCSS: frameFontCss(doc) });
|
||||
} else {
|
||||
const report = fallbackNode.current;
|
||||
if (!report) throw new Error('Markdown 报告尚未载入');
|
||||
await document.fonts.ready;
|
||||
const height = Math.max(report.scrollHeight, report.offsetHeight);
|
||||
if (height > 16000) throw new Error('报告较长,请下载 HTML 查看完整图文。');
|
||||
png = await toPng(report, { width: 900, height, pixelRatio: 1, backgroundColor: '#ffffff', skipFonts: true });
|
||||
png = await captureReportImage(report, { width: 900, pixelRatio: 1, skipFonts: true });
|
||||
}
|
||||
if (generation !== exportGeneration.current) return;
|
||||
download(png, `${title}.png`);
|
||||
@@ -328,7 +311,7 @@ export function NativeAnalysisReport({ turn, reportMarkdown, reportHtml }: {
|
||||
return <>
|
||||
<Button type="text" size="small" icon={<DownloadOutlined />} onClick={() => setOpen(true)}>查看报告</Button>
|
||||
<Modal title="分析报告" open={open} onCancel={() => setOpen(false)} width={980} footer={<>
|
||||
<Button disabled={exporting || !safeHtml || visualReport.loading || !visualReport.authorized} onClick={() => void saveHtml()}>下载 HTML</Button>
|
||||
<Button disabled={exporting || visualReport.loading || !visualReport.authorized} onClick={() => void saveHtml()}>下载 HTML</Button>
|
||||
<Button type="primary" loading={exporting} disabled={visualReport.loading || !visualReport.authorized || Boolean(safeHtml) && !frameReady} onClick={() => void saveImage()}>下载图片</Button>
|
||||
</>}>
|
||||
{visualReport.loading && <p role="status">{visualReport.progress || '正在准备报告图表…'}</p>}
|
||||
@@ -337,7 +320,7 @@ export function NativeAnalysisReport({ turn, reportMarkdown, reportHtml }: {
|
||||
{visualReport.authorized && <div className="analysis-report-preview">
|
||||
{safeHtml
|
||||
? <iframe ref={iframe} className="native-analysis-report-frame" title="原生分析报告预览" sandbox="allow-same-origin" srcDoc={safeHtml} width={900} height={frameHeight} onLoad={handleFrameLoad} />
|
||||
: <article className="native-analysis-report" ref={fallbackNode}><AiMarkdown content={reportMarkdown} /><ReportVisualSections turn={turn} images={visualReport.images} /></article>}
|
||||
: <article ref={fallbackNode}><ReportDocument turn={{ ...turn, reportMarkdown }} stamp="" visualImages={visualReport.images} /></article>}
|
||||
</div>}
|
||||
</Modal>
|
||||
</>;
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useMemo } from 'react';
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
import type { AnalysisVisual } from './analysisVisualsModel';
|
||||
import { RateComparisonReadout, NarrativeEvidence } from './AnalysisNarrative';
|
||||
import { buildAnalysisNarrative, useCompactRateComparison } from './analysisReportModel';
|
||||
import { ReportVisualDataTable, ReportVisualFigure, type ReportVisualImage, reportVisuals } from './AnalysisReportVisuals';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
|
||||
export function AnalysisReportNarrative({ turn, answer, images }: { turn: Row; answer: string; images: ReportVisualImage[] }) {
|
||||
const visuals = reportVisuals(turn);
|
||||
const model = useMemo(() => buildAnalysisNarrative(answer, visuals, String(turn.question || '')), [answer, JSON.stringify(visuals), turn.question]);
|
||||
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 compact = (visual: AnalysisVisual) => useCompactRateComparison(visual, String(turn.question || ''));
|
||||
const appendix = model.sections.filter(section => section.visuals.length || section.tables.length);
|
||||
return <div className="analysis-narrative report-narrative">
|
||||
{model.sections.length > 4 && <nav className="q-report-contents" aria-label="报告目录">{model.sections.filter(section => section.title).map(section => <a key={section.id} href={`#${prefix}${section.id}`}>{section.title}</a>)}</nav>}
|
||||
{model.sections.map(section => <section key={section.id} id={`${prefix}${section.id}`} className={`analysis-narrative-section is-${section.kind}`} data-section-kind={section.kind}>
|
||||
{section.title && <h2 className="analysis-narrative-title">{section.title}</h2>}
|
||||
{section.narrative && text(section.narrative)}
|
||||
{!!section.visuals.filter(compact).length && <div className="analysis-rate-grid">{section.visuals.filter(compact).map(visual => <RateComparisonReadout key={visual.id} visual={visual} />)}</div>}
|
||||
{section.visuals.filter(visual => !compact(visual)).map(visual => <ReportVisualFigure key={visual.id} visual={visual} image={images.find(image => image.id === visual.id)} evidenceLabels={model.evidenceLabels} evidencePrefix={prefix} />)}
|
||||
{!section.visuals.length && section.tables.map((table, index) => <div key={index}>{text(table)}</div>)}
|
||||
{!!section.visuals.length && section.tables.length > 0 && <p className="q-note q-report-detail-link"><a href={`#${prefix}appendix`}>完整数据见附录</a></p>}
|
||||
</section>)}
|
||||
{!!appendix.length && <details className="q-report-appendix" id={`${prefix}appendix`}><summary>数据明细与图表依据</summary>{appendix.map(section => <div key={section.id}>
|
||||
<h3>{section.title || '分析数据'}</h3>
|
||||
{section.tables.map((table, index) => <div key={index}>{text(table)}</div>)}
|
||||
{section.visuals.map(visual => <div key={visual.id} className="q-report-appendix-visual"><h4>{visual.title}</h4><ReportVisualDataTable visual={visual} /></div>)}
|
||||
</div>)}</details>}
|
||||
<NarrativeEvidence model={model} prefix={prefix} />
|
||||
</div>;
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { parseAnalysisVisuals, renderVisualPng, visualPeriodSummary, visualScopeSummary, visualCategoryLabel } from './analysisVisualsModel';
|
||||
import { analysisSnapshotResult, authorizeAnalysisSnapshot, reportSnapshotIdentity } from './analysisSnapshot';
|
||||
import { analysisVisualCumulativeShares, analysisVisualShares, analysisVisualTypeLabel } from './analysisVisualPresentation';
|
||||
import type { AnalysisVisual } from './analysisVisualsModel';
|
||||
import { useCompactRateComparison } from './analysisReportModel';
|
||||
import { analysisVisualCumulativeShares, analysisVisualShares } from './analysisVisualPresentation';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
export type ReportVisualImage = { id: string; png?: string; failed?: boolean };
|
||||
@@ -40,10 +42,11 @@ export function useReportVisualImages(turn: Row, open: boolean) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
for (const [index, visual] of visuals.entries()) {
|
||||
const plotted = visuals.filter(visual => !useCompactRateComparison(visual, String(turn.question || '')));
|
||||
for (const [index, visual] of plotted.entries()) {
|
||||
if (controller.signal.aborted) return;
|
||||
setProgress(`正在准备图表 ${index + 1}/${visuals.length}`);
|
||||
try { next.push({ id: visual.id, png: await renderVisualPng(visual, controller.signal) }); }
|
||||
setProgress(`正在准备图表 ${index + 1}/${plotted.length}`);
|
||||
try { next.push({ id: visual.id, png: await renderVisualPng(visual, controller.signal, 'report') }); }
|
||||
catch { if (controller.signal.aborted) return; next.push({ id: visual.id, failed: true }); }
|
||||
}
|
||||
if (!controller.signal.aborted) setImages(next);
|
||||
@@ -75,26 +78,27 @@ function shown(value: number | null, unit: string): string {
|
||||
return `${(unit === 'ratio' ? value * 100 : value).toLocaleString('zh-CN', { maximumFractionDigits: 2 })}${unit === 'ratio' ? '%' : unit === 'pp' ? ' pp' : unit === 'kg' ? ' kg' : ''}`;
|
||||
}
|
||||
|
||||
export function ReportVisualDataTable({ visual }: { visual: AnalysisVisual }) {
|
||||
const shares = analysisVisualShares(visual), cumulativeShares = analysisVisualCumulativeShares(visual);
|
||||
return <table><thead><tr><th>序号</th><th>对象 / 期间</th>{visual.series.map(series => <th key={series.key}>{series.label}</th>)}{shares && <th>占已列类别合计</th>}{cumulativeShares && <th>累计占已列类别合计</th>}</tr></thead>
|
||||
<tbody>{visual.categories.map((category, index) => <tr key={category.key}><td>{index + 1}</td><td>{visualCategoryLabel(visual, index)}</td>{visual.series.map(series => <td key={series.key}>{shown(series.values[index] ?? null, visual.unit)}</td>)}{shares && <td>{(shares[index] * 100).toFixed(2)}%</td>}{cumulativeShares && <td>{(cumulativeShares[index] * 100).toFixed(2)}%</td>}</tr>)}</tbody></table>;
|
||||
}
|
||||
|
||||
export function ReportVisualFigure({ visual, image, evidenceLabels = {}, evidencePrefix = '' }: { visual: AnalysisVisual; image?: ReportVisualImage; evidenceLabels?: Record<string, string>; evidencePrefix?: string }) {
|
||||
|
||||
return <figure className="q-report-visual">
|
||||
<div className="q-report-visual-heading"><strong>{visual.title}</strong><span>{visual.unit === 'pp' ? '百分点' : visual.unit === 'ratio' ? '%' : visual.unit}</span></div>
|
||||
{image?.png && <img src={image.png} alt={visual.title} />}
|
||||
{(!image?.png || image.failed || !visual.chartable) && <><p className="q-partial">此图以同一份结果的数据表显示。</p><ReportVisualDataTable visual={visual} /></>}
|
||||
<figcaption>{visualPeriodSummary(visual)}{visualScopeSummary(visual.scope) ? ` · ${visualScopeSummary(visual.scope)}` : ''}{visual.coverage.truncated ? ` · 展示 ${visual.coverage.returnedRows} / ${visual.coverage.totalRows} 项` : ''}
|
||||
{visual.note && <span> · {visual.note}</span>}
|
||||
{visual.evidenceRefs.map(ref => <a className="analysis-evidence-ref" key={ref} href={`#${evidencePrefix}${ref}`} title={ref}>{evidenceLabels[ref] || ref}</a>)}
|
||||
</figcaption>
|
||||
</figure>;
|
||||
}
|
||||
|
||||
export function ReportVisualSections({ turn, images }: { turn: Row; images: ReportVisualImage[] }) {
|
||||
const visuals = reportVisuals(turn);
|
||||
return <>{visuals.map(visual => {
|
||||
const image = images.find(item => item.id === visual.id);
|
||||
const shares = analysisVisualShares(visual);
|
||||
const cumulativeShares = analysisVisualCumulativeShares(visual);
|
||||
return <section key={visual.id} className="q-report-visual">
|
||||
<h2>{visual.title}</h2>
|
||||
<p className="q-note">{analysisVisualTypeLabel(visual.type)}</p>
|
||||
<p className="q-note">{visual.subtitle}</p>
|
||||
<p className="q-note">期间:{visualPeriodSummary(visual)}{visualScopeSummary(visual.scope) ? ` · 范围:${visualScopeSummary(visual.scope)}` : ''}</p>
|
||||
{image?.png && <img src={image.png} alt={visual.title} style={{ width: '100%', height: 'auto', display: 'block' }} />}
|
||||
{image?.failed && <p className="q-partial">此图未能生成,以下保留同一份结果的数据表。</p>}
|
||||
<table><thead><tr><th>序号</th><th>对象 / 期间</th>{visual.series.map(series => <th key={series.key}>{series.label}</th>)}{shares && <th>占已列类别合计</th>}{cumulativeShares && <th>累计占已列类别合计</th>}</tr></thead>
|
||||
<tbody>{visual.categories.map((category, index) => <tr key={category.key}><td>{index + 1}</td><td>{visualCategoryLabel(visual, index)}</td>{visual.series.map(series => <td key={series.key}>{shown(series.values[index] ?? null, visual.unit)}</td>)}{shares && <td>{(shares[index] * 100).toFixed(2)}%</td>}{cumulativeShares && <td>{(cumulativeShares[index] * 100).toFixed(2)}%</td>}</tr>)}</tbody>
|
||||
</table>
|
||||
{visual.note && <p className="q-note">{visual.note}</p>}
|
||||
<p className="q-note">数据依据:{visual.evidenceRefs.join('、')}</p>
|
||||
</section>;
|
||||
})}</>;
|
||||
return <>{reportVisuals(turn).map(visual => <ReportVisualFigure key={visual.id} visual={visual} image={images.find(image => image.id === visual.id)} />)}</>;
|
||||
}
|
||||
|
||||
const escapeHtml = (value: string) => value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''');
|
||||
@@ -109,6 +113,14 @@ export function reportVisualHtml(turn: Row, images: ReportVisualImage[]): string
|
||||
const rows = visual.categories.map((_category, index) => `<tr><td>${index + 1}</td><td>${escapeHtml(visualCategoryLabel(visual, index))}</td>${visual.series.map(series => `<td>${escapeHtml(shown(series.values[index] ?? null, visual.unit))}</td>`).join('')}${shares ? `<td>${(shares[index] * 100).toFixed(2)}%</td>` : ''}${cumulativeShares ? `<td>${(cumulativeShares[index] * 100).toFixed(2)}%</td>` : ''}</tr>`).join('');
|
||||
const png = image?.png && /^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(image.png) ? image.png : '';
|
||||
const context = `期间:${visualPeriodSummary(visual)}${visualScopeSummary(visual.scope) ? ` · 范围:${visualScopeSummary(visual.scope)}` : ''}`;
|
||||
return `<section class="platform-report-visual" style="break-inside:avoid;padding:20px 0;color:#202b3c;background:white"><h2>${escapeHtml(visual.title)}</h2><p>${escapeHtml(visual.subtitle || '')}</p><p>${escapeHtml(context)}</p>${png ? `<img alt="${escapeHtml(visual.title)}" src="${png}" style="display:block;width:100%;height:auto">` : image?.failed ? '<p>此图未能生成,以下保留同一份结果的数据表。</p>' : ''}<table style="width:100%;border-collapse:collapse" border="1"><thead><tr><th>序号</th><th>对象 / 期间</th>${headers}</tr></thead><tbody>${rows}</tbody></table><p>${escapeHtml(visual.note || '')}</p><p>数据依据:${escapeHtml(visual.evidenceRefs.join('、'))}</p></section>`;
|
||||
const table = `<table style="width:100%;border-collapse:collapse;font-size:13px" border="1"><thead><tr><th>序号</th><th>对象 / 期间</th>${headers}</tr></thead><tbody>${rows}</tbody></table>`;
|
||||
let picture = png ? `<img alt="${escapeHtml(visual.title)}" src="${png}" style="display:block;width:100%;height:auto">` : '';
|
||||
if (useCompactRateComparison(visual, String(turn.question || ''))) {
|
||||
const [before, after] = visual.series[0].values as [number, number];
|
||||
const delta = (after - before) * 100;
|
||||
picture = `<div style="padding:16px 20px;background:#f4f7fb;display:flex;align-items:center;gap:20px;flex-wrap:wrap"><span style="font-size:22px;color:#65748b">${(before * 100).toFixed(2)}%</span><span>→</span><strong style="font-size:30px">${(after * 100).toFixed(2)}%</strong><span style="font-size:16px">${delta > 0 ? '+' : ''}${delta.toFixed(2)} 个百分点</span></div>`;
|
||||
}
|
||||
const detail = picture ? `<details style="margin:10px 0;font-size:12px"><summary style="cursor:pointer">查看本图数据</summary>${table}</details>` : `<p>此图以数据表显示。</p>${table}`;
|
||||
return `<section class="platform-report-visual" style="break-inside:avoid;padding:14px 0;color:#202b3c;background:white"><h3 style="margin:6px 0 10px;font-size:16px">${escapeHtml(visual.title)}</h3>${picture}<p style="font-size:12px;color:#65748b">${escapeHtml(context)}${visual.note ? ` · ${escapeHtml(visual.note)}` : ''}</p>${detail}<p style="font-size:11px;color:#65748b">数据依据:${escapeHtml(visual.evidenceRefs.join('、'))}</p></section>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ export interface AnalysisVisualsProps {
|
||||
visuals: unknown;
|
||||
visualState?: unknown;
|
||||
beforeExport?: () => Promise<void>;
|
||||
embedded?: boolean;
|
||||
}
|
||||
|
||||
interface VisualTableRow {
|
||||
@@ -313,7 +314,7 @@ function AnalysisVisualCard({ visual, beforeExport }: { visual: AnalysisVisual;
|
||||
}
|
||||
|
||||
/** A bad or old visual payload is confined to this module; it never interrupts the answer text. */
|
||||
export function AnalysisVisuals({ visuals, visualState, beforeExport }: AnalysisVisualsProps) {
|
||||
export function AnalysisVisuals({ visuals, visualState, beforeExport, embedded = false }: AnalysisVisualsProps) {
|
||||
const parsed = useMemo(() => parseAnalysisVisuals(visuals), [visuals]);
|
||||
if (!parsed.visuals.length) {
|
||||
const state = visualStateName(visualState);
|
||||
@@ -321,8 +322,8 @@ export function AnalysisVisuals({ visuals, visualState, beforeExport }: Analysis
|
||||
if (state === 'failed' || state === 'unavailable') return <div className="analysis-visual-state" role="status">图表暂不可用,已保留分析结果。</div>;
|
||||
return null;
|
||||
}
|
||||
return <section className="analysis-visuals" aria-label="分析图表">
|
||||
{parsed.visuals.slice(0, 3).map(visual => <AnalysisVisualCard key={visual.id} visual={visual} beforeExport={beforeExport} />)}
|
||||
return <section className={`analysis-visuals${embedded ? ' is-embedded' : ''}`} aria-label="分析图表">
|
||||
{parsed.visuals.map(visual => <AnalysisVisualCard key={visual.id} visual={visual} beforeExport={beforeExport} />)}
|
||||
</section>;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AnalysisNarrative } from './AnalysisNarrative';
|
||||
import { usePageCache } from './pageCache';
|
||||
import { FilterFieldSettings } from './FilterFieldSettings';
|
||||
import { isInternalDataField, publicJson } from './publicDataDisplay';
|
||||
@@ -33,7 +34,6 @@ import './management-alignment.css';
|
||||
import { TargetVersionAdmin } from './AnalyticsCompletion';
|
||||
import { AnalysisReportExport, NativeAnalysisReport } from './AnalysisReportExport';
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
import { AnalysisVisuals } from './AnalysisVisuals';
|
||||
import { authorizeAnalysisSnapshot } from './analysisSnapshot';
|
||||
import { AnalysisApiSettings } from './AnalysisApiSettings';
|
||||
import { acceptAnalysisEvent, analysisScrollFollows, partialAnalysisNotice, partialAnswerIsOnlyProgress } from './analysisConversationState';
|
||||
@@ -1525,13 +1525,13 @@ function AnalysisTurn({ turn, onResume, onRetry, retryDisabled = false }: { turn
|
||||
<AnalysisProcess turn={turn} />
|
||||
{(!resumable || !Array.isArray(turn.timeline || (isObjectRecord(turn.plan) ? turn.plan.timeline : undefined))) && (answer || !resumable || !retryDisabled) && <div className="analysis-answer">
|
||||
{answer ? <>
|
||||
<AiMarkdown content={answer} className="ai-answer" />
|
||||
{!resumable && <AnalysisVisuals visuals={visuals} visualState={result.visualState} beforeExport={() => authorizeAnalysisSnapshot(turn)} />}
|
||||
{resumable ? <AiMarkdown content={answer} className="ai-answer" />
|
||||
: <AnalysisNarrative answer={answer} visuals={visuals} visualState={result.visualState} question={question} turnId={String(turn.id || '')} beforeExport={() => authorizeAnalysisSnapshot(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 : ''))}</p>}
|
||||
<div className="analysis-message-actions">
|
||||
{reportMarkdown.trim() && <NativeAnalysisReport turn={turn} reportMarkdown={reportMarkdown} reportHtml={reportHtml} />}
|
||||
{!reportMarkdown.trim() && answer && ['COMPLETED', 'PARTIAL'].includes(status) && <AnalysisReportExport turn={turn} />}
|
||||
{(reportMarkdown.trim() || reportHtml?.trim()) && <NativeAnalysisReport turn={turn} reportMarkdown={reportMarkdown} reportHtml={reportHtml} />}
|
||||
{!reportMarkdown.trim() && !reportHtml?.trim() && answer && ['COMPLETED', 'PARTIAL'].includes(status) && <AnalysisReportExport turn={turn} />}
|
||||
{['FAILED', 'CANCELLED', 'PARTIAL'].includes(status) && typeof turn.id === 'string' && onRetry && <Button size="small" type="text" disabled={retryDisabled} 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>
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
.analysis-narrative{min-width:0;color:var(--ink,#263c5a)}
|
||||
.analysis-narrative-section{min-width:0;padding:22px 0;border-bottom:1px solid var(--line,#dfe5ef)}
|
||||
.analysis-narrative-section:first-child{padding-top:2px}
|
||||
.analysis-narrative-section:last-of-type{border-bottom:0}
|
||||
.analysis-narrative-title{margin:0 0 12px;font-size:18px;line-height:1.55;color:var(--ink,#263c5a);font-weight:650}
|
||||
.analysis-narrative-section>.ai-answer{font-size:14px;line-height:1.85}
|
||||
.analysis-narrative-section.is-overview>.ai-answer>p:first-child{font-size:16px;line-height:1.85}
|
||||
.analysis-narrative-details{margin:12px 0 0;padding-top:8px;color:var(--muted-ink,#65748b);font-size:12px}
|
||||
.analysis-narrative-details>summary{cursor:pointer;min-height:28px;line-height:28px;font-weight:550}
|
||||
.analysis-narrative-details[open]>summary{margin-bottom:8px}
|
||||
.analysis-narrative .analysis-visuals.is-embedded{margin:12px 0 4px;gap:16px}
|
||||
.analysis-visuals.is-embedded>.analysis-visual-card{padding:8px 0;border:0;box-shadow:none;background:transparent}
|
||||
.analysis-visuals.is-embedded .analysis-visual-heading h3{font-size:14px;font-weight:550}
|
||||
.analysis-visuals.is-embedded .analysis-visual-heading-copy>p{display:none}
|
||||
.analysis-visuals.is-embedded .analysis-visual-context{margin-top:3px}
|
||||
.analysis-visuals.is-embedded .analysis-visual-type-label{display:none}
|
||||
.analysis-visuals.is-embedded .analysis-visual-note{border:0;background:transparent;padding:2px 0;font-size:11px}
|
||||
.analysis-rate-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,280px),1fr));gap:14px;margin:16px 0 10px}
|
||||
.analysis-rate-readout{padding:16px 18px;background:var(--surface-subtle,#f4f7fb);border-radius:6px;min-width:0;font-variant-numeric:tabular-nums}
|
||||
.analysis-rate-name{font-size:13px;font-weight:600;margin-bottom:12px;color:var(--muted-ink,#65748b)}
|
||||
.analysis-rate-scope{font-size:11px;line-height:1.6;margin:-5px 0 10px;color:var(--muted-ink,#65748b);overflow-wrap:anywhere}
|
||||
.analysis-rate-values{display:flex;align-items:center;gap:14px;flex-wrap:wrap}
|
||||
.analysis-rate-values small{display:block;font-size:11px;color:var(--muted-ink,#65748b);margin-bottom:4px}
|
||||
.analysis-rate-values span,.analysis-rate-values strong{font-variant-numeric:tabular-nums}
|
||||
.analysis-rate-values em{font-style:normal;font-size:.58em;margin-left:2px}
|
||||
.analysis-rate-previous>span{font-size:23px;font-weight:500;color:var(--muted-ink,#65748b)}
|
||||
.analysis-rate-current>strong{font-size:30px;font-weight:700;letter-spacing:-.6px;color:var(--ink,#263c5a)}
|
||||
.analysis-rate-arrow{color:var(--muted-ink,#65748b);font-size:18px}
|
||||
.analysis-rate-change{margin-left:auto;display:flex;flex-direction:column;gap:3px;text-align:right}
|
||||
.analysis-rate-change>strong{font-size:19px}
|
||||
.analysis-rate-change>span{font-size:10px;color:var(--muted-ink,#65748b)}
|
||||
.analysis-rate-change.is-worse>strong{color:var(--danger,#c64446)}
|
||||
.analysis-rate-change.is-better>strong{color:var(--success,#008f7d)}
|
||||
.analysis-evidence-ref{font-size:.78em;font-weight:500;white-space:nowrap;text-decoration:none;color:var(--muted-ink,#65748b);margin-left:4px}
|
||||
.analysis-evidence-ref:hover{text-decoration:underline;color:var(--blue,#607ae1)}
|
||||
.analysis-narrative-evidence{margin-top:20px;padding-top:14px;border-top:1px solid var(--line,#dfe5ef);font-size:11px;color:var(--muted-ink,#65748b)}
|
||||
.analysis-narrative-evidence h3{font-size:12px;margin:0 0 8px;font-weight:600}
|
||||
.analysis-narrative-evidence ol{list-style:none;padding:0;margin:0;display:grid;gap:7px}
|
||||
.analysis-narrative-evidence li{display:flex;gap:8px;flex-wrap:wrap;scroll-margin-top:22px;line-height:1.7}
|
||||
.analysis-narrative-evidence li>strong{font-weight:550;min-width:40px}
|
||||
.analysis-narrative-evidence li>span{flex:1;min-width:130px}
|
||||
.analysis-narrative-evidence code{background:transparent;font:inherit;opacity:.85}
|
||||
.q-report .analysis-narrative-section{padding:24px 0}
|
||||
.q-report .analysis-narrative-title{font-size:20px!important;margin:0 0 12px!important}
|
||||
.q-report .q-report-question{font-size:12px;color:#65748b;margin:10px 0 0}
|
||||
.q-report .q-report-contents{display:flex;flex-wrap:wrap;gap:8px 18px;padding:16px 0 8px;font-size:11px;line-height:1.8}
|
||||
.q-report .q-report-contents a,.q-report-detail-link a{color:#65748b;text-decoration:none}
|
||||
.q-report .q-report-contents a:hover,.q-report-detail-link a:hover{text-decoration:underline}
|
||||
.q-report .q-report-detail-link{font-size:11px}
|
||||
.q-report .analysis-narrative-evidence{padding-top:14px!important;margin-top:22px!important}
|
||||
.q-report .analysis-narrative-evidence h3{font-size:13px!important;margin:0 0 8px!important}
|
||||
.q-report .analysis-rate-grid{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
.q-report .analysis-rate-grid:has(>.analysis-rate-readout:only-child){grid-template-columns:1fr}
|
||||
.q-report .analysis-rate-readout{--surface-subtle:#f4f7fb}
|
||||
.q-report .analysis-narrative-details>summary{font-size:12px;color:#65748b}
|
||||
.q-report-visual{margin:14px 0}
|
||||
.q-report-visual figcaption{font-size:12px;line-height:1.8;color:#65748b;margin:8px 0 12px}
|
||||
.q-report-visual>img{display:block;width:100%;height:auto}
|
||||
.q-report-visual-heading{display:flex;justify-content:space-between;gap:16px;align-items:baseline;margin:10px 0 4px}
|
||||
.q-report-visual-heading strong{font-size:14px;font-weight:600}
|
||||
.q-report-visual-heading span{font-size:11px;color:#65748b}
|
||||
.q-report-appendix{margin-top:30px;padding-top:14px;border-top:1px solid #dfe5ef}
|
||||
.q-report-appendix>summary{font-size:15px;font-weight:600;cursor:pointer;line-height:2}
|
||||
.q-report-appendix h3{font-size:14px;margin:20px 0 9px}
|
||||
@media(max-width:640px){.analysis-narrative-section{padding:18px 0}.analysis-narrative-title{font-size:17px}.analysis-rate-readout{padding:13px}.analysis-rate-values{gap:10px}.analysis-rate-change>span{font-size:11px}.analysis-narrative-evidence li{display:block}.analysis-narrative-evidence li>*{margin-right:6px}}
|
||||
@media print{.q-report details:not([open])>*:not(summary){display:block}.q-report details>summary{list-style:none}.q-report .analysis-narrative-section{break-before:auto}.q-report figure,.q-report .analysis-rate-readout{break-inside:avoid}.q-report .analysis-evidence-ref{color:#65748b}}
|
||||
@@ -0,0 +1,173 @@
|
||||
import { sanitizeAnalysisDisplayText } from './analysisDisplayText.ts';
|
||||
import { parseAnalysisVisuals, visualPeriodSummary, visualScopeSummary, type AnalysisVisual } from './analysisVisualsModel.ts';
|
||||
|
||||
export type NarrativeKind = 'overview' | 'stage' | 'department' | 'group' | 'product' | 'category' | 'defect' | 'trend' | 'composition' | 'crosscheck' | 'action' | 'other';
|
||||
export interface NarrativeSection {
|
||||
id: string;
|
||||
title: string;
|
||||
kind: NarrativeKind;
|
||||
markdown: string;
|
||||
narrative: string;
|
||||
tables: string[];
|
||||
visuals: AnalysisVisual[];
|
||||
evidenceRefs: string[];
|
||||
}
|
||||
export interface AnalysisNarrativeModel {
|
||||
sections: NarrativeSection[];
|
||||
evidence: Array<{ ref: string; label: string; context: string }>;
|
||||
evidenceLabels: Record<string, string>;
|
||||
period: string;
|
||||
scope: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
const REF = /\bQ[A-F0-9]{8}\b/g;
|
||||
const refs = (text: string) => [...new Set(text.match(REF) || [])];
|
||||
const TITLES: Partial<Record<NarrativeKind, string>> = { overview: '核心结论', stage: '阶段变化', department: '产业部变化', group: '业务分组变化', product: '重点规格', category: '正式报废类别变化', defect: '具体缺陷变化', trend: '期间趋势', composition: '报废构成', crosscheck: '交叉核查线索', action: '优先核查方向' };
|
||||
|
||||
export function classifyAnalysisSection(title: string): NarrativeKind {
|
||||
if (/已核对|交叉|联系|关联/.test(title)) return 'crosscheck';
|
||||
if (/行动|建议|下一步|重点关注|优先核查|后续核查/.test(title)) return 'action';
|
||||
if (/具体缺陷|源字段|来源.*缺陷|缺角|磕边|隐裂/.test(title)) return 'defect';
|
||||
if (/正式报废|报废大类|报废类别|类别增减/.test(title)) return 'category';
|
||||
if (/产业部|部门/.test(title)) return 'department';
|
||||
if (/业务分组|分组|区域/.test(title)) return 'group';
|
||||
if (/产品|规格/.test(title)) return 'product';
|
||||
if (/趋势|历史|逐月|月度走势/.test(title)) return 'trend';
|
||||
if (/构成|占比|柏拉|帕累托/.test(title)) return 'composition';
|
||||
if (/阶段|黑片|亮片/.test(title)) return 'stage';
|
||||
if (/总体|综合|总览|结论|摘要|概览/.test(title)) return 'overview';
|
||||
return 'other';
|
||||
}
|
||||
|
||||
/** 保留代码块和完整原表,仅拆分展示位置。 */
|
||||
export function narrativeParts(markdown: string): { narrative: string; tables: string[] } {
|
||||
const lines = markdown.split('\n');
|
||||
const prose: string[] = [], tables: string[] = [];
|
||||
let fenced = false;
|
||||
for (let i = 0; i < lines.length; i += 1) {
|
||||
if (/^\s*```/.test(lines[i])) fenced = !fenced;
|
||||
const cells = (lines[i + 1] || '').trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map(cell => cell.trim());
|
||||
if (!fenced && lines[i].includes('|') && cells.length > 0 && cells.every(cell => /^:?-{3,}:?$/.test(cell))) {
|
||||
const table = [lines[i], lines[++i]];
|
||||
while (i + 1 < lines.length && lines[i + 1].trim() && lines[i + 1].includes('|')) table.push(lines[++i]);
|
||||
let note = i + 1;
|
||||
while (note < lines.length && !lines[note].trim()) note += 1;
|
||||
// 表格的引用和覆盖说明随明细保留,避免在结论和图之间重复出现。
|
||||
if (/^\s*\[Q[A-F0-9]{8}\]/.test(lines[note] || '')) { table.push('', lines[note]); i = note; }
|
||||
tables.push(table.join('\n')); prose.push('');
|
||||
} else prose.push(lines[i]);
|
||||
}
|
||||
return { narrative: prose.join('\n').trim(), tables };
|
||||
}
|
||||
|
||||
function visualKind(visual: AnalysisVisual): NarrativeKind {
|
||||
const key = (visual as AnalysisVisual & { sectionKey?: string }).sectionKey;
|
||||
if (key?.startsWith('category_')) return 'category';
|
||||
if (key?.startsWith('defect_')) return 'defect';
|
||||
if (key && key in TITLES) return key as NarrativeKind;
|
||||
if (visual.type === 'waterfall' || visual.metric === 'composite_impact_pp') return 'stage';
|
||||
if (visual.type === 'donut' || visual.type === 'pareto') return 'composition';
|
||||
if (['line', 'area', 'heatmap'].includes(visual.type)) return 'trend';
|
||||
if (visual.metric.startsWith('source_defect')) return /具体缺陷|来源/.test(visual.title) ? 'defect' : 'category';
|
||||
if (visual.comparisonPeriod && visual.unit === 'ratio' && visual.categories.length === 2) return visual.metric === 'composite_rate' ? 'overview' : 'stage';
|
||||
const dimension = (visual as AnalysisVisual & { dimension?: string }).dimension;
|
||||
if (dimension === 'department' || dimension === 'group' || dimension === 'product') return dimension;
|
||||
return classifyAnalysisSection(visual.title);
|
||||
}
|
||||
|
||||
export function isRateComparison(visual: AnalysisVisual): boolean {
|
||||
return visual.chartable && visual.unit === 'ratio' && !!visual.comparisonPeriod && visual.categories.length === 2
|
||||
&& visual.series.length === 1 && ['composite_rate', 'black_rate', 'bright_rate'].includes(visual.metric)
|
||||
&& visual.series[0].values.every(value => value !== null);
|
||||
}
|
||||
|
||||
export function useCompactRateComparison(visual: AnalysisVisual, question = ''): boolean {
|
||||
return isRateComparison(visual) && !/柱状图|柱形图|条形图|横条图/.test(question);
|
||||
}
|
||||
|
||||
function additionalScopeNames(visual: AnalysisVisual, primaryScope: Record<string, unknown>): string[] {
|
||||
return ['department','group','product','category','defect'].filter(key => visual.scope[key] && visual.scope[key] !== primaryScope[key])
|
||||
.map(key => String(visual.scope[key]));
|
||||
}
|
||||
|
||||
function sectionScore(section: NarrativeSection, visual: AnalysisVisual, primaryScope: Record<string, unknown>): number {
|
||||
const extraNames = additionalScopeNames(visual, primaryScope);
|
||||
const scopedComparison = extraNames.length > 0 && (isRateComparison(visual) || visual.metric === 'composite_impact_pp');
|
||||
const kind = scopedComparison ? (visual.scope.product ? 'product' : visual.scope.group ? 'group' : visual.scope.department ? 'department' : visualKind(visual)) : visualKind(visual);
|
||||
if (scopedComparison && !extraNames.every(name => section.markdown.includes(name) || section.title.includes(name))) return Number.NEGATIVE_INFINITY;
|
||||
const matchingRef = visual.evidenceRefs.some(ref => section.evidenceRefs.includes(ref));
|
||||
let score = section.kind === kind ? 30 : 0;
|
||||
if (kind === 'composition' && section.kind === 'category') score = 25;
|
||||
if (matchingRef) score += 18;
|
||||
if (kind === 'other' && matchingRef && visual.categories.length > 1
|
||||
&& visual.categories.filter(category => section.markdown.includes(category.label)).length >= Math.min(2, visual.categories.length)) score += 35;
|
||||
if (/黑片/.test(section.title) && visual.stage === 'black') score += 8;
|
||||
if (/亮片/.test(section.title) && visual.stage === 'bright') score += 8;
|
||||
const blackOnly = /黑片/.test(section.title) && !/亮片/.test(section.title);
|
||||
const brightOnly = /亮片/.test(section.title) && !/黑片/.test(section.title);
|
||||
if ((blackOnly && visual.stage === 'bright') || (brightOnly && visual.stage === 'black')) return Number.NEGATIVE_INFINITY;
|
||||
// 局部交叉核查必须跟随自身依据,不放入全局缺陷章节。
|
||||
const localNames = ['department', 'group', 'product'].map(key => visual.scope[key]).filter((value): value is string => typeof value === 'string' && !!value);
|
||||
const namesMentioned = localNames.some(name => section.markdown.includes(name) || section.title.includes(name));
|
||||
if (kind === 'defect' && localNames.length && matchingRef && section.kind === 'crosscheck') score += 35;
|
||||
if (kind === 'defect' && section.kind === 'defect' && localNames.length && !matchingRef && !namesMentioned) return Number.NEGATIVE_INFINITY;
|
||||
// 多表共用引用时,仍不能把类别图放入总体章节。
|
||||
if (matchingRef && section.kind !== kind && section.kind !== 'other' && section.kind !== 'crosscheck' && !(kind === 'composition' && section.kind === 'category')) score -= 25;
|
||||
return score;
|
||||
}
|
||||
|
||||
export function buildAnalysisNarrative(answer: string, rawVisuals: unknown, question = ''): AnalysisNarrativeModel {
|
||||
const safe = sanitizeAnalysisDisplayText(answer).replaceAll('\r\n', '\n').replaceAll('\r', '\n');
|
||||
const visuals = parseAnalysisVisuals(rawVisuals).visuals;
|
||||
const scopeDepth = (visual: AnalysisVisual) => ['department','group','product','category','defect'].filter(key => visual.scope[key]).length;
|
||||
const main = [...visuals].filter(visual => visual.metric === 'composite_rate').sort((a,b) => scopeDepth(a)-scopeDepth(b))[0] || visuals[0];
|
||||
const primaryScope = main?.scope || {};
|
||||
const chunks: Array<{ title: string; lines: string[] }> = [{ title: '', lines: [] }];
|
||||
let fenced = false;
|
||||
for (const line of safe.split('\n')) {
|
||||
if (/^\s*```/.test(line)) fenced = !fenced;
|
||||
const heading = !fenced ? line.match(/^\s*#{1,4}\s+(.+?)\s*#*\s*$/) : null;
|
||||
if (heading) chunks.push({ title: heading[1], lines: [] });
|
||||
else chunks[chunks.length - 1].lines.push(line);
|
||||
}
|
||||
const sections: NarrativeSection[] = chunks.filter(chunk => chunk.title || chunk.lines.join('').trim()).map((chunk, index) => {
|
||||
const markdown = chunk.lines.join('\n').trim();
|
||||
const kind = chunk.title ? classifyAnalysisSection(chunk.title) : 'overview';
|
||||
return { id: `section-${index + 1}`, title: chunk.title || (visuals.length ? '核心结论' : ''), kind, markdown, ...narrativeParts(markdown), visuals: [], evidenceRefs: refs(markdown) };
|
||||
});
|
||||
const singleNarrativeSection = sections.length === 1 && ['overview', 'other'].includes(sections[0].kind);
|
||||
for (const visual of visuals) {
|
||||
const scored = sections.map((section, index) => {
|
||||
const score = sectionScore(section, visual, primaryScope);
|
||||
return { index, score: Number.isFinite(score) && singleNarrativeSection && index === 0 && visual.evidenceRefs.some(ref => section.evidenceRefs.includes(ref)) ? Math.max(30, score) : score };
|
||||
}).sort((a, b) => b.score - a.score);
|
||||
if (scored[0]?.score >= 25) sections[scored[0].index].visuals.push(visual);
|
||||
else {
|
||||
const kind = visualKind(visual);
|
||||
const extraNames = additionalScopeNames(visual, primaryScope);
|
||||
const title = `${extraNames.length ? `${extraNames.join(' / ')} · ` : ''}${TITLES[kind] || visual.title}`;
|
||||
const existing = sections.find(section => !section.markdown && section.kind === kind && section.title === title);
|
||||
if (existing) existing.visuals.push(visual);
|
||||
else sections.push({ id: `section-${sections.length + 1}`, title, kind, markdown: '', narrative: '', tables: [], visuals: [visual], evidenceRefs: visual.evidenceRefs });
|
||||
}
|
||||
}
|
||||
const allRefs = [...new Set([...refs(safe), ...visuals.flatMap(visual => visual.evidenceRefs)])];
|
||||
const evidenceLabels = Object.fromEntries(allRefs.map((ref, index) => [ref, `依据 ${index + 1}`]));
|
||||
const evidence = allRefs.map(ref => {
|
||||
const charts = visuals.filter(visual => visual.evidenceRefs.includes(ref));
|
||||
const context = [...new Set(charts.map(visual => `${visual.title} · ${visualPeriodSummary(visual)}${visualScopeSummary(visual.scope) ? ` · ${visualScopeSummary(visual.scope)}` : ''}`))].join(';');
|
||||
return { ref, label: evidenceLabels[ref], context: context || '分析正文引用的数据依据' };
|
||||
});
|
||||
const period = main ? visualPeriodSummary(main) : '';
|
||||
const scope = main ? visualScopeSummary(main.scope) : '';
|
||||
const cleanQuestion = sanitizeAnalysisDisplayText(question).trim();
|
||||
const broad = /分析|原因|整体|总体|情况|变化/.test(cleanQuestion);
|
||||
const topic = main?.type === 'pareto' ? '报废类别柏拉图'
|
||||
: main?.type === 'donut' ? '报废类别构成分析'
|
||||
: main && ['area','line'].includes(main.type) ? '质量趋势分析'
|
||||
: main?.metric === 'composite_rate' ? '质量变化分析' : '质量数据分析';
|
||||
const title = period && (broad || cleanQuestion.length > 40 || /用.*图|展示|查看/.test(cleanQuestion))
|
||||
? `${period} ${topic}` : cleanQuestion || '质量分析报告';
|
||||
return { sections, evidence, evidenceLabels, period, scope, title };
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import type { AnalysisVisual } from './analysisVisualsModel';
|
||||
import { visualDonutShares, visualParetoPoints } from './analysisVisualsModel';
|
||||
|
||||
export function analysisVisualTypeLabel(type: string): string {
|
||||
return ({ bar: '条形图', line: '折线图', column: '柱状图', area: '面积图', heatmap: '热力图', donut: '环状图', pareto: '柏拉图' } as Record<string, string>)[type] || '数据图';
|
||||
return ({ bar: '条形图', line: '折线图', column: '柱状图', area: '面积图', heatmap: '热力图', donut: '环状图', pareto: '柏拉图', waterfall: '阶段影响拆解' } as Record<string, string>)[type] || '数据图';
|
||||
}
|
||||
|
||||
/** Share values use the same validated calculation as the chart renderer. */
|
||||
|
||||
+261
-62
@@ -2,6 +2,8 @@ import type { EChartsCoreOption } from 'echarts/core';
|
||||
|
||||
export type AnalysisVisualUnit = 'ratio' | 'kg' | 'pp' | 'count';
|
||||
export type AnalysisVisualStage = 'black' | 'bright';
|
||||
export type AnalysisVisualSectionKey = 'overview' | 'stage' | 'department' | 'group' | 'product' | 'category_black' | 'category_bright' | 'defect_black' | 'defect_bright' | 'trend' | 'composition';
|
||||
export type AnalysisVisualDimension = 'department' | 'group' | 'product' | 'category' | 'defect';
|
||||
export type AnalysisVisualContextValue = string | number | boolean | Array<string | number | boolean> | Record<string, string[]>;
|
||||
export type AnalysisVisualContext = Record<string, AnalysisVisualContextValue>;
|
||||
|
||||
@@ -37,6 +39,8 @@ export interface AnalysisVisual {
|
||||
invalidValueCells: string[];
|
||||
chartable: boolean;
|
||||
chartIssue?: string;
|
||||
sectionKey?: AnalysisVisualSectionKey;
|
||||
dimension?: AnalysisVisualDimension;
|
||||
}
|
||||
|
||||
export interface ParseVisualsResult {
|
||||
@@ -52,13 +56,20 @@ export interface VisualChartTheme {
|
||||
colors?: string[];
|
||||
}
|
||||
|
||||
export const MAX_ANALYSIS_VISUALS = 3;
|
||||
export const MAX_ANALYSIS_VISUALS = 12;
|
||||
export const MAX_VISUAL_BYTES = 256 * 1024;
|
||||
export const MAX_VISUAL_CATEGORIES = 36;
|
||||
export const MAX_VISUAL_SERIES = 4;
|
||||
|
||||
const UNIT_VALUES = new Set<AnalysisVisualUnit>(['ratio', 'kg', 'pp', 'count']);
|
||||
const CHART_TYPES = new Set(['bar', 'line', 'column', 'area', 'heatmap', 'donut', 'pareto']);
|
||||
const CHART_TYPES = new Set(['bar', 'line', 'column', 'area', 'heatmap', 'donut', 'pareto', 'waterfall']);
|
||||
const SECTION_KEYS = new Set<AnalysisVisualSectionKey>(['overview', 'stage', 'department', 'group', 'product', 'category_black', 'category_bright', 'defect_black', 'defect_bright', 'trend', 'composition']);
|
||||
const DIMENSIONS = new Set<AnalysisVisualDimension>(['department', 'group', 'product', 'category', 'defect']);
|
||||
const VISUAL_KEYS = new Set(['id', 'type', 'title', 'subtitle', 'unit', 'categories', 'series', 'evidenceRefs', 'requiredFields', 'scope', 'period', 'comparisonPeriod', 'stage', 'metric', 'coverage', 'note', 'originTurnId', 'sectionKey', 'dimension']);
|
||||
const CATEGORY_KEYS = new Set(['key', 'label']);
|
||||
const SERIES_KEYS = new Set(['key', 'label', 'values']);
|
||||
const COVERAGE_KEYS = new Set(['totalRows', 'returnedRows', 'truncated', 'shareBasis']);
|
||||
const PARSED_VISUALS = new WeakSet<object>();
|
||||
const DONUT_CATEGORY_KEYS: Record<AnalysisVisualStage, Set<string>> = {
|
||||
black: new Set(['black_responsibility_scrap', 'black_material_scrap', 'black_external_scrap']),
|
||||
bright: new Set(['bright_plating_scrap', 'bright_material_scrap', 'bright_processing_scrap', 'bright_diffusion_scrap']),
|
||||
@@ -69,6 +80,61 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function hasOnlyKeys(value: Record<string, unknown>, allowed: Set<string>): boolean {
|
||||
return Object.keys(value).every(key => allowed.has(key));
|
||||
}
|
||||
|
||||
/** 解析前仅复制普通 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');
|
||||
if (value === null || typeof value === 'string' || typeof value === 'boolean' || typeof value === 'number' || value === undefined) return value;
|
||||
if (typeof value !== 'object' || seen.has(value)) throw new Error('unsafe JSON data');
|
||||
if (PARSED_VISUALS.has(value)) {
|
||||
seen.add(value);
|
||||
try {
|
||||
const descriptors = Object.getOwnPropertyDescriptors(value);
|
||||
const result: Record<string, unknown> = Object.create(null);
|
||||
for (const key of VISUAL_KEYS) {
|
||||
const descriptor = descriptors[key];
|
||||
if (!descriptor) continue;
|
||||
if (!('value' in descriptor)) throw new Error('unsafe JSON data');
|
||||
result[key] = copyJsonData(descriptor.value, seen, budget, depth + 1);
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
seen.delete(value);
|
||||
}
|
||||
}
|
||||
seen.add(value);
|
||||
try {
|
||||
if (Array.isArray(value)) {
|
||||
if (Object.getPrototypeOf(value) !== Array.prototype || Object.getOwnPropertySymbols(value).length) throw new Error('unsafe JSON data');
|
||||
const descriptors = Object.getOwnPropertyDescriptors(value);
|
||||
const result: unknown[] = [];
|
||||
for (let index = 0; index < value.length; index++) {
|
||||
const descriptor = descriptors[String(index)];
|
||||
if (!descriptor || !('value' in descriptor)) throw new Error('unsafe JSON data');
|
||||
result.push(copyJsonData(descriptor.value, seen, budget, depth + 1));
|
||||
}
|
||||
if (Object.keys(descriptors).some(key => key !== 'length' && (!/^\d+$/.test(key) || String(Number(key)) !== key || Number(key) >= value.length))) {
|
||||
throw new Error('unsafe JSON data');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
const prototype = Object.getPrototypeOf(value);
|
||||
if (prototype !== Object.prototype && prototype !== null) throw new Error('unsafe JSON data');
|
||||
if (Object.getOwnPropertySymbols(value).length) throw new Error('unsafe JSON data');
|
||||
const result: Record<string, unknown> = Object.create(null);
|
||||
for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
|
||||
if (!('value' in descriptor)) throw new Error('unsafe JSON data');
|
||||
result[key] = copyJsonData(descriptor.value, seen, budget, depth + 1);
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
seen.delete(value);
|
||||
}
|
||||
}
|
||||
|
||||
function boundedText(value: unknown, maxLength = 200): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const text = value.trim();
|
||||
@@ -98,24 +164,24 @@ function safeContext(value: unknown): AnalysisVisualContext | null {
|
||||
for (const [filterKey, filterValues] of Object.entries(raw)) {
|
||||
if (!/^[\w.-]{1,128}$/.test(filterKey) || !Array.isArray(filterValues) || filterValues.length > 20
|
||||
|| !filterValues.every(item => typeof item === 'string' && item.length <= 160)) return null;
|
||||
filters[filterKey] = [...filterValues];
|
||||
Object.defineProperty(filters, filterKey, { value: [...filterValues], enumerable: true, configurable: true, writable: true });
|
||||
}
|
||||
result[key] = filters;
|
||||
Object.defineProperty(result, key, { value: filters, enumerable: true, configurable: true, writable: true });
|
||||
} else if (typeof raw === 'string') {
|
||||
if (raw.length > 160) return null;
|
||||
result[key] = raw;
|
||||
Object.defineProperty(result, key, { value: raw, enumerable: true, configurable: true, writable: true });
|
||||
} else if (typeof raw === 'boolean' || (typeof raw === 'number' && Number.isFinite(raw))) {
|
||||
result[key] = raw;
|
||||
Object.defineProperty(result, key, { value: raw, enumerable: true, configurable: true, writable: true });
|
||||
} else if (Array.isArray(raw) && raw.length <= 20 && raw.every(item =>
|
||||
typeof item === 'boolean' || (typeof item === 'string' && item.length <= 160) || (typeof item === 'number' && Number.isFinite(item)))) {
|
||||
result[key] = raw as Array<string | number | boolean>;
|
||||
Object.defineProperty(result, key, { value: raw as Array<string | number | boolean>, enumerable: true, configurable: true, writable: true });
|
||||
} else return null;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function parseVisual(value: unknown, index: number, issues: string[]): AnalysisVisual | null {
|
||||
if (!isRecord(value)) {
|
||||
if (!isRecord(value) || !hasOnlyKeys(value, VISUAL_KEYS)) {
|
||||
issues.push(`第 ${index + 1} 张图表结构无效`);
|
||||
return null;
|
||||
}
|
||||
@@ -133,8 +199,10 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
|
||||
const requiredFields = safeTextList(value.requiredFields, 100);
|
||||
const note = 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;
|
||||
|
||||
const coverage = isRecord(value.coverage) ? value.coverage : null;
|
||||
const coverage = isRecord(value.coverage) && hasOnlyKeys(value.coverage, COVERAGE_KEYS) ? value.coverage : null;
|
||||
const validCoverage = coverage && Number.isSafeInteger(coverage.totalRows) && Number(coverage.totalRows) >= 0
|
||||
&& Number.isSafeInteger(coverage.returnedRows) && Number(coverage.returnedRows) >= 0
|
||||
&& Number(coverage.returnedRows) <= Number(coverage.totalRows)
|
||||
@@ -150,7 +218,7 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
|
||||
|
||||
const categories = Array.isArray(value.categories) && value.categories.length > 0 && value.categories.length <= MAX_VISUAL_CATEGORIES
|
||||
? value.categories.map(category => {
|
||||
if (!isRecord(category)) return null;
|
||||
if (!isRecord(category) || !hasOnlyKeys(category, CATEGORY_KEYS)) return null;
|
||||
const key = boundedText(category.key, 128);
|
||||
const label = boundedText(category.label, 240);
|
||||
return key && label ? { key, label } : null;
|
||||
@@ -167,7 +235,7 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
|
||||
const series: AnalysisVisualSeries[] = [];
|
||||
if (rawSeries && validCategories) {
|
||||
for (const [seriesIndex, raw] of rawSeries.entries()) {
|
||||
if (!isRecord(raw)) { series.length = 0; break; }
|
||||
if (!isRecord(raw) || !hasOnlyKeys(raw, SERIES_KEYS)) { series.length = 0; break; }
|
||||
const key = boundedText(raw.key, 128);
|
||||
const label = boundedText(raw.label, 160);
|
||||
if (!key || !label || !Array.isArray(raw.values) || raw.values.length !== validCategories.length) { series.length = 0; break; }
|
||||
@@ -191,6 +259,8 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
|
||||
&& !!metric && !!originTurnId && !!scope && !!period && (value.comparisonPeriod === undefined || !!comparisonPeriod)
|
||||
&& !!evidenceRefs && !!requiredFields && (value.note === undefined || note !== null)
|
||||
&& (stage === undefined || stage === 'black' || stage === 'bright')
|
||||
&& (sectionKey === undefined || SECTION_KEYS.has(sectionKey as AnalysisVisualSectionKey))
|
||||
&& (dimension === undefined || DIMENSIONS.has(dimension as AnalysisVisualDimension))
|
||||
&& !!validCoverage && !!validCategories && validSeries;
|
||||
if (!valid) {
|
||||
issues.push(`第 ${index + 1} 张图表未通过结构校验`);
|
||||
@@ -205,6 +275,8 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
|
||||
scope: scope!, period: period!, ...(comparisonPeriod ? { comparisonPeriod } : {}),
|
||||
...(stage ? { stage } : {}), metric: metric!, coverage: validCoverage!,
|
||||
...(note ? { note } : {}), originTurnId: originTurnId!, invalidValueCells, chartable: false,
|
||||
...(sectionKey ? { sectionKey: sectionKey as AnalysisVisualSectionKey } : {}),
|
||||
...(dimension ? { dimension: dimension as AnalysisVisualDimension } : {}),
|
||||
};
|
||||
const semanticIssue = visualSemanticIssue(candidate);
|
||||
const chartable = CHART_TYPES.has(type!) && hasData && invalidValueCells.length === 0 && !semanticIssue;
|
||||
@@ -217,14 +289,37 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
|
||||
else if (semanticIssue) chartIssue = `${semanticIssue},以下展示原始数据表`;
|
||||
if (!chartable) issues.push(`“${title}”已降级为数据表:${chartIssue}`);
|
||||
|
||||
return {
|
||||
const parsedVisual: AnalysisVisual = {
|
||||
...candidate, chartable, ...(chartIssue ? { chartIssue } : {}),
|
||||
};
|
||||
PARSED_VISUALS.add(parsedVisual);
|
||||
return parsedVisual;
|
||||
}
|
||||
|
||||
function visualSemanticIssue(visual: AnalysisVisual): string | undefined {
|
||||
if (visual.type === 'area' && visual.series.length !== 1) return '面积趋势图仅支持单一序列';
|
||||
if (visual.type === 'area' && visual.series.some(series => series.values.some(value => value !== null && value < 0))) return '面积趋势图不支持负值';
|
||||
if (visual.type === 'waterfall') {
|
||||
const allowedFields = new Set(['black_good_weight', 'black_total_weight', 'bright_good_weight', 'bright_total_weight']);
|
||||
const actualFields = visual.requiredFields;
|
||||
if (visual.metric !== 'composite_impact_pp' || visual.unit !== 'pp') return '瀑布图仅支持综合率阶段数学影响(百分点)';
|
||||
if (visual.categories.length !== 3 || visual.categories.map(item => item.key).join('|') !== 'black|bright|total') return '瀑布图类别必须依次为黑片、亮片和综合变化';
|
||||
if (visual.series.length !== 1 || visual.series[0].key !== 'composite_impact_pp') return '瀑布图仅支持综合阶段影响序列';
|
||||
if (actualFields.length !== allowedFields.size || new Set(actualFields).size !== allowedFields.size || actualFields.some(field => !allowedFields.has(field))) {
|
||||
return '瀑布图必须具备黑片和亮片的合格重量、总重量字段权限';
|
||||
}
|
||||
if (visual.stage !== undefined || visual.scope.stage !== undefined || visual.scope.category !== undefined || visual.scope.defect !== undefined) {
|
||||
return '瀑布图只支持未按阶段、类别或缺陷筛选的综合范围';
|
||||
}
|
||||
if (!visual.comparisonPeriod || Object.keys(visual.period).length === 0 || Object.keys(visual.comparisonPeriod).length === 0
|
||||
|| plainPeriod(visual.period) === '当前期间' || plainPeriod(visual.comparisonPeriod) === '当前期间'
|
||||
|| plainPeriod(visual.period) === plainPeriod(visual.comparisonPeriod)) return '瀑布图必须提供两个不同的有效期间';
|
||||
const values = visual.series[0].values;
|
||||
if (values.length !== 3 || values.some(value => value === null || !Number.isFinite(value))) return '瀑布图的三项影响必须是有限数值';
|
||||
const sum = (values[0] as number) + (values[1] as number);
|
||||
if (!Number.isFinite(sum) || Math.abs(sum - (values[2] as number)) > 1e-8) return '黑片与亮片影响之和必须等于综合率变化';
|
||||
return undefined;
|
||||
}
|
||||
if (visual.type !== 'donut' && visual.type !== 'pareto') return undefined;
|
||||
const chartName = visual.type === 'donut' ? '环形图' : '柏拉图';
|
||||
if (visual.unit !== 'kg' || visual.metric !== 'source_defect_weight') return `${chartName}仅支持来源类别重量`;
|
||||
@@ -255,11 +350,17 @@ function visualSemanticIssue(visual: AnalysisVisual): string | undefined {
|
||||
/** Parse untrusted JSON-shaped chart data. An object wrapper may also include visualSchemaVersion. */
|
||||
export function parseAnalysisVisuals(input: unknown, schemaVersion?: unknown): ParseVisualsResult {
|
||||
const issues: string[] = [];
|
||||
let rawVisuals = input;
|
||||
let safeInput: unknown;
|
||||
try { safeInput = copyJsonData(input); }
|
||||
catch { return { visuals: [], issues: ['图表数据无法安全读取'] }; }
|
||||
let rawVisuals = safeInput;
|
||||
let version = schemaVersion;
|
||||
if (isRecord(input) && 'visuals' in input) {
|
||||
rawVisuals = input.visuals;
|
||||
if (version === undefined) version = input.visualSchemaVersion;
|
||||
if (isRecord(safeInput) && 'visuals' in safeInput) {
|
||||
if (!hasOnlyKeys(safeInput, new Set(['visuals', 'visualSchemaVersion']))) {
|
||||
return { visuals: [], issues: ['图表数据包含未知字段'] };
|
||||
}
|
||||
rawVisuals = safeInput.visuals;
|
||||
if (version === undefined) version = safeInput.visualSchemaVersion;
|
||||
}
|
||||
if (version !== undefined && version !== 1) {
|
||||
return { visuals: [], issues: ['不支持此版本的图表数据'] };
|
||||
@@ -269,7 +370,7 @@ export function parseAnalysisVisuals(input: unknown, schemaVersion?: unknown): P
|
||||
let serialized: string;
|
||||
try { serialized = JSON.stringify(rawVisuals); }
|
||||
catch { return { visuals: [], issues: ['图表数据无法安全读取'] }; }
|
||||
if (new TextEncoder().encode(serialized).byteLength > MAX_VISUAL_BYTES) {
|
||||
if (typeof serialized !== 'string' || new TextEncoder().encode(serialized).byteLength > MAX_VISUAL_BYTES) {
|
||||
return { visuals: [], issues: ['图表数据超过安全大小限制'] };
|
||||
}
|
||||
const result: AnalysisVisual[] = [];
|
||||
@@ -303,6 +404,18 @@ function chartNumber(value: number): number {
|
||||
return Number(value.toPrecision(10));
|
||||
}
|
||||
|
||||
function formatChartValue(value: number | null, unit: AnalysisVisualUnit, showPositiveSign = true): string {
|
||||
if (value === null) return '—';
|
||||
if (!Number.isFinite(value)) return '无效值';
|
||||
const plotted = unit === 'ratio' ? value * 100 : value;
|
||||
const numberText = unit === 'kg' || unit === 'pp' || unit === 'ratio'
|
||||
? new Intl.NumberFormat('zh-CN', { useGrouping: false, maximumFractionDigits: 2 }).format(plotted)
|
||||
: new Intl.NumberFormat('zh-CN', { useGrouping: false, maximumSignificantDigits: 10 }).format(plotted);
|
||||
if (unit === 'ratio') return `${numberText}%`;
|
||||
const signed = unit === 'pp' && showPositiveSign && value > 0 ? `+${numberText}` : numberText;
|
||||
return unit === 'kg' ? `${signed} kg` : unit === 'pp' ? `${signed} pp` : signed;
|
||||
}
|
||||
|
||||
export function visualCategoryLabel(visual: AnalysisVisual, categoryIndex: number): string {
|
||||
const category = visual.categories[categoryIndex];
|
||||
if (!category) return '';
|
||||
@@ -367,11 +480,12 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
const colors = theme.colors?.length ? theme.colors : visual.stage === 'black'
|
||||
? ['#607ae1', '#a8b4c4', '#d58c35', '#8b68c5']
|
||||
: visual.stage === 'bright' ? ['#008f7d', '#a8b4c4', '#d58c35', '#8b68c5'] : DEFAULT_COLORS;
|
||||
// 坐标数据保留原始业务标签;提示框等富文本区域单独转义 ECharts 标记。
|
||||
const categories = visual.categories.map((_item, index) => visualCategoryLabel(visual, index));
|
||||
const categoryAxisLabel = { color: ink, fontSize: 11, hideOverlap: true, overflow: 'truncate' as const, width: 160 };
|
||||
const numberAxisLabel = (value: number) => visual.unit === 'ratio'
|
||||
? `${chartNumber(value)}%`
|
||||
: `${chartNumber(value)}${visual.unit === 'pp' ? ' pp' : visual.unit === 'kg' ? ' kg' : ''}`;
|
||||
: formatChartValue(value, visual.unit, false);
|
||||
const formatter = (raw: unknown): string => {
|
||||
const params = Array.isArray(raw) ? raw : [raw];
|
||||
const first = params[0];
|
||||
@@ -409,6 +523,17 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
`累计占本图已列类别合计:${visualDonutShareText(point.cumulativeShare)}`,
|
||||
].join('\n');
|
||||
}
|
||||
if (visual.type === 'waterfall') {
|
||||
const value = visual.series[0]?.values[dataIndex] ?? null;
|
||||
if (value === null) return '';
|
||||
return [
|
||||
plainRichText(visualCategoryLabel(visual, dataIndex)),
|
||||
plainRichText(`期间:${plainPeriod(visual.comparisonPeriod || {})} → ${plainPeriod(visual.period)}`),
|
||||
`阶段数学影响:${formatVisualValue(value, 'pp')}`,
|
||||
...(dataIndex === 2 ? ['黑片与亮片影响之和构成综合率变化。'] : []),
|
||||
'该拆解不代表生产根因。',
|
||||
].join('\n');
|
||||
}
|
||||
const category = visual.categories[dataIndex];
|
||||
const lines = category ? [plainRichText(visualCategoryLabel(visual, dataIndex))] : [];
|
||||
if (visual.comparisonPeriod) lines.push(plainRichText(`期间:${plainPeriod(visual.comparisonPeriod)} → ${plainPeriod(visual.period)}`));
|
||||
@@ -422,6 +547,42 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
return lines.join('\n');
|
||||
};
|
||||
|
||||
if (visual.type === 'waterfall') {
|
||||
const [black, bright, total] = visual.series[0].values as [number, number, number];
|
||||
const endAfterBlack = black;
|
||||
const endAfterBright = black + bright;
|
||||
const baseline = [Math.min(0, black), Math.min(endAfterBlack, endAfterBright), 0];
|
||||
const deltaValues = [Math.abs(black), Math.abs(bright), 0];
|
||||
const minValue = Math.min(0, black, endAfterBright, total);
|
||||
const maxValue = Math.max(0, black, endAfterBright, total);
|
||||
const padding = Math.max((maxValue - minValue) * 0.18, 0.25);
|
||||
const barData = deltaValues.map((value, index) => ({
|
||||
value,
|
||||
label: { ...(index === 2 ? { show: false } : {}), position: (index === 0 ? black : bright) < 0 ? 'bottom' : 'top' },
|
||||
itemStyle: { color: index === 0 ? (black < 0 ? '#c66565' : '#607ae1') : (bright < 0 ? '#c66565' : '#008f7d') },
|
||||
}));
|
||||
const totalData = [{ value: 0, label: { show: false } }, { value: 0, label: { show: false } }, {
|
||||
value: total,
|
||||
label: { position: total < 0 ? 'bottom' : 'top' },
|
||||
itemStyle: { color: total < 0 ? '#c66565' : '#435d7a' },
|
||||
}];
|
||||
return {
|
||||
animation: false,
|
||||
color: ['#607ae1', '#435d7a'],
|
||||
tooltip: { trigger: 'axis', renderMode: 'richText', backgroundColor: theme.surface || '#ffffff', borderColor: line, textStyle: { color: ink }, axisPointer: { type: 'shadow' }, formatter },
|
||||
legend: { show: true, selectedMode: false, type: 'plain', top: 8, data: ['阶段影响', '综合变化'], textStyle: { color: mutedInk, fontSize: 11 } },
|
||||
grid: { left: 72, right: 34, top: 48, bottom: 64, containLabel: true },
|
||||
xAxis: { type: 'category', data: categories, axisLabel: { color: ink, fontSize: 12, interval: 0, width: 150, overflow: 'break', lineHeight: 16 }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false } },
|
||||
yAxis: { type: 'value', min: minValue - padding, max: maxValue + padding, scale: false, name: '变化(百分点)', nameTextStyle: { color: mutedInk, fontSize: 10 }, axisLabel: { color: mutedInk, formatter: numberAxisLabel }, axisLine: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' } } },
|
||||
series: [
|
||||
{ name: '辅助基线', type: 'bar', stack: 'impact', stackStrategy: 'all', data: baseline, itemStyle: { color: 'transparent' }, emphasis: { disabled: true }, silent: true, tooltip: { show: false }, legendHoverLink: false },
|
||||
{ name: '阶段影响', type: 'bar', stack: 'impact', stackStrategy: 'all', data: barData, barMaxWidth: 56, label: { show: true, position: 'top', color: ink, fontSize: 11, formatter: (params: { dataIndex: number }) => formatChartValue(visual.series[0].values[params.dataIndex] ?? null, 'pp') }, emphasis: { disabled: true } },
|
||||
{ name: '综合变化', type: 'bar', stack: 'impact', stackStrategy: 'all', data: totalData, barMaxWidth: 56, label: { show: true, position: 'top', color: ink, fontSize: 11, formatter: () => formatChartValue(total, 'pp') }, emphasis: { disabled: true } },
|
||||
],
|
||||
aria: { enabled: true, decal: { show: false } },
|
||||
};
|
||||
}
|
||||
|
||||
if (visual.type === 'heatmap') {
|
||||
const finiteValues = visual.series.flatMap(item => item.values.filter((value): value is number => value !== null)
|
||||
.map(value => visual.unit === 'ratio' ? chartNumber(value * 100) : chartNumber(value)));
|
||||
@@ -440,7 +601,7 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
tooltip: { trigger: 'item', renderMode: 'richText', backgroundColor: theme.surface || '#ffffff', borderColor: line, textStyle: { color: ink }, formatter },
|
||||
grid: { left: 18, right: 92, top: 18, bottom: 58, containLabel: true, backgroundColor: '#eef1f5' },
|
||||
xAxis: { type: 'category', data: categories, axisLabel: { ...categoryAxisLabel, interval: 0, rotate: categories.length > 8 ? 25 : 0, width: 150 }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false }, splitArea: { show: false } },
|
||||
yAxis: { type: 'category', data: visual.series.map(item => item.label), axisLabel: { color: ink, fontSize: 11, width: 150, overflow: 'truncate' }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false } },
|
||||
yAxis: { type: 'category', data: visual.series.map(item => plainRichText(item.label)), axisLabel: { color: ink, fontSize: 11, width: 150, overflow: 'truncate' }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false } },
|
||||
visualMap: {
|
||||
type: 'continuous', min: visualMin, max: visualMax, calculable: false, orient: 'vertical', right: 2, top: 'middle', itemHeight: 120,
|
||||
text: [numberAxisLabel(visualMax), numberAxisLabel(visualMin)], textStyle: { color: mutedInk, fontSize: 10 },
|
||||
@@ -448,7 +609,7 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
...(hasNegative ? {} : { outOfRange: { color: '#e8ebef' } }),
|
||||
},
|
||||
series: [{
|
||||
name: visual.series[0]?.label || '数值', type: 'heatmap', data: matrixData,
|
||||
name: plainRichText(visual.series[0]?.label || '数值'), type: 'heatmap', data: matrixData,
|
||||
label: { show: true, color: ink, fontSize: 11, formatter: (params: { data?: unknown }) => {
|
||||
const tuple = Array.isArray(params?.data) ? params.data : [];
|
||||
return typeof tuple[2] === 'number' ? tuple[2].toFixed(2) : '';
|
||||
@@ -463,7 +624,7 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
const shares = visualDonutShares(visual);
|
||||
const total = shares.reduce((sum, item) => sum + item.valueKg, 0);
|
||||
const pieData = shares.map(({ categoryIndex, valueKg, share }) => ({
|
||||
name: visualCategoryLabel(visual, categoryIndex),
|
||||
name: plainRichText(visualCategoryLabel(visual, categoryIndex)),
|
||||
value: valueKg,
|
||||
visualCategoryIndex: categoryIndex,
|
||||
visualShare: share,
|
||||
@@ -476,20 +637,20 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
legend: { show: true, selectedMode: false, type: 'scroll', orient: 'horizontal', bottom: 3, left: 10, right: 10, textStyle: { color: mutedInk, fontSize: 11 } },
|
||||
graphic: [{
|
||||
type: 'text', left: 'center', top: '39%', silent: true,
|
||||
style: { text: `所列类别合计\n${formatVisualValue(total, 'kg')}`, textAlign: 'center', fill: ink, font: '600 15px sans-serif', lineHeight: 24 },
|
||||
style: { text: `所列类别合计\n${formatChartValue(total, 'kg')}`, textAlign: 'center', fill: ink, font: '600 15px sans-serif', lineHeight: 24 },
|
||||
}, {
|
||||
type: 'text', left: 'center', bottom: 30, silent: true,
|
||||
style: { text: '占比以本图列出类别重量合计为分母,不代表正式总报废占比', textAlign: 'center', fill: mutedInk, font: '10px sans-serif', width: 560, overflow: 'break', lineHeight: 15 },
|
||||
}],
|
||||
series: [{
|
||||
name: visual.series[0].label, type: 'pie', radius: ['42%', '66%'], center: ['50%', '44%'], avoidLabelOverlap: true,
|
||||
name: plainRichText(visual.series[0].label), type: 'pie', radius: ['42%', '66%'], center: ['50%', '44%'], avoidLabelOverlap: true,
|
||||
data: pieData,
|
||||
label: { show: true, position: 'outside', alignTo: 'labelLine', edgeDistance: 12, width: 210, overflow: 'break', lineHeight: 16, color: ink, fontSize: 11,
|
||||
formatter: (params: { dataIndex?: number }) => {
|
||||
const index = Number.isInteger(params?.dataIndex) ? params.dataIndex as number : -1;
|
||||
const share = shares[index];
|
||||
if (!share) return '';
|
||||
return `${visualCategoryLabel(visual, index)}\n${formatVisualValue(share.valueKg, 'kg')} · ${visualDonutShareText(share.share)}`;
|
||||
return `${plainRichText(visualCategoryLabel(visual, index))}\n${formatChartValue(share.valueKg, 'kg')} · ${visualDonutShareText(share.share)}`;
|
||||
} },
|
||||
labelLine: { show: true, length: 16, length2: 12, lineStyle: { color: line } },
|
||||
emphasis: { disabled: true },
|
||||
@@ -501,7 +662,7 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
series: [{ radius: ['44%', '72%'], center: ['50%', '45%'], label: { show: false }, labelLine: { show: false } }],
|
||||
graphic: [{
|
||||
type: 'text', left: 'center', top: '39%', silent: true,
|
||||
style: { text: `所列类别合计\n${formatVisualValue(total, 'kg')}`, textAlign: 'center', fill: ink, font: '600 15px sans-serif', lineHeight: 23 },
|
||||
style: { text: `所列类别合计\n${formatChartValue(total, 'kg')}`, textAlign: 'center', fill: ink, font: '600 15px sans-serif', lineHeight: 23 },
|
||||
}, {
|
||||
type: 'text', left: 'center', bottom: 8, silent: true,
|
||||
style: { text: '占比以本图列出类别重量合计为分母,不代表正式总报废占比', textAlign: 'center', fill: mutedInk, font: '9px sans-serif', width: 300, overflow: 'break', lineHeight: 13 },
|
||||
@@ -519,15 +680,15 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
animation: false,
|
||||
color: [colors[0], '#435d7a'],
|
||||
tooltip: { trigger: 'axis', renderMode: 'richText', backgroundColor: theme.surface || '#ffffff', borderColor: line, textStyle: { color: ink }, axisPointer: { type: 'shadow' }, formatter },
|
||||
legend: { show: true, selectedMode: false, type: 'plain', top: 6, left: 12, data: [visual.series[0].label, cumulativeName], textStyle: { color: mutedInk, fontSize: 10 } },
|
||||
legend: { show: true, selectedMode: false, type: 'plain', top: 6, left: 12, data: [plainRichText(visual.series[0].label), cumulativeName], textStyle: { color: mutedInk, fontSize: 10 } },
|
||||
grid: { left: 56, right: 66, top: 36, bottom: 70, containLabel: true },
|
||||
xAxis: { type: 'category', data: categories.map(label => truncateText(label, 16)), axisLabel: { color: ink, fontSize: 10, interval: 0, rotate: categories.length > 3 ? 18 : 0, width: 130 }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false } },
|
||||
xAxis: { type: 'category', data: categories, axisLabel: { color: ink, fontSize: 10, interval: 0, rotate: categories.length > 3 ? 34 : 0, width: 160, overflow: 'break', hideOverlap: false, lineHeight: 13 }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false } },
|
||||
yAxis: [
|
||||
{ type: 'value', min: 0, name: '重量(kg)', nameTextStyle: { color: mutedInk, fontSize: 10 }, axisLabel: { color: mutedInk, formatter: (value: number) => `${chartNumber(value)} kg` }, axisLine: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' } } },
|
||||
{ type: 'value', min: 0, name: '重量(kg)', nameTextStyle: { color: mutedInk, fontSize: 10 }, axisLabel: { color: mutedInk, formatter: (value: number) => formatChartValue(value, 'kg') }, axisLine: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' } } },
|
||||
{ type: 'value', min: 0, max: 100, position: 'right', name: '累计占比', nameTextStyle: { color: mutedInk, fontSize: 10 }, axisLabel: { color: mutedInk, formatter: (value: number) => `${chartNumber(value)}%` }, axisLine: { show: false }, splitLine: { show: false } },
|
||||
],
|
||||
series: [
|
||||
{ name: visual.series[0].label, type: 'bar', yAxisIndex: 0, data: visual.series[0].values, barMaxWidth: 48, itemStyle: { color: colors[0] }, label: { show: true, position: 'top', color: ink, fontSize: 10, formatter: (params: { dataIndex: number }) => formatVisualValue(points[params.dataIndex]?.valueKg ?? null, 'kg') }, emphasis: { disabled: true } },
|
||||
{ name: plainRichText(visual.series[0].label), type: 'bar', yAxisIndex: 0, data: visual.series[0].values, barMaxWidth: 48, itemStyle: { color: colors[0] }, label: { show: true, position: 'top', color: ink, fontSize: 10, formatter: (params: { dataIndex: number }) => formatChartValue(points[params.dataIndex]?.valueKg ?? null, 'kg') }, emphasis: { disabled: true } },
|
||||
{ name: cumulativeName, type: 'line', yAxisIndex: 1, data: points.map(point => chartNumber(point.cumulativeShare * 100)), symbol: 'circle', symbolSize: 7, lineStyle: { width: 2.2, color: ink }, itemStyle: { color: ink }, label: { show: true, position: 'top', color: ink, fontSize: 10, formatter: (params: { data?: number }) => visualDonutShareText((params.data || 0) / 100) }, emphasis: { disabled: true } },
|
||||
],
|
||||
aria: { enabled: true, decal: { show: false } },
|
||||
@@ -535,7 +696,7 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
}
|
||||
|
||||
const series = visual.series.map((item, seriesIndex) => ({
|
||||
name: item.label,
|
||||
name: plainRichText(item.label),
|
||||
type: visual.type === 'area' ? 'line' : visual.type === 'column' ? 'bar' : visual.type,
|
||||
data: item.values.map(value => {
|
||||
if (value === null) return null;
|
||||
@@ -552,8 +713,7 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
color: ink, fontSize: 11,
|
||||
formatter: (raw: { dataIndex: number }) => {
|
||||
const value = item.values[raw.dataIndex];
|
||||
return value === null || value === undefined ? '—'
|
||||
: `${(visual.unit === 'ratio' ? value * 100 : value).toLocaleString('zh-CN', { maximumFractionDigits: 2 })}${visual.unit === 'ratio' ? '%' : visual.unit === 'pp' ? ' pp' : visual.unit === 'kg' ? ' kg' : ''}`;
|
||||
return formatChartValue(value ?? null, visual.unit);
|
||||
} },
|
||||
emphasis: { focus: 'series' },
|
||||
} : {
|
||||
@@ -637,9 +797,12 @@ export interface AnalysisVisualExportOption {
|
||||
}
|
||||
|
||||
/** Add static report context around the complete, unfiltered snapshot for PNG export. */
|
||||
export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width = 1280): AnalysisVisualExportOption {
|
||||
const titleLines = wrapLines(visual.title, 34, 3);
|
||||
const headerParts = [
|
||||
export type AnalysisVisualRenderContext = 'standalone' | 'report';
|
||||
|
||||
export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width = 1280, context: AnalysisVisualRenderContext = 'standalone'): AnalysisVisualExportOption {
|
||||
const reportMode = context === 'report';
|
||||
const titleLines = reportMode ? [] : wrapLines(visual.title, 34, 3);
|
||||
const headerParts = reportMode ? [] : [
|
||||
visual.subtitle,
|
||||
`期间:${visualPeriodSummary(visual)}`,
|
||||
`范围:${visualScopeSummary(visual.scope) || '按本轮查询条件'}`,
|
||||
@@ -654,31 +817,34 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
: visual.coverage.shareBasis ? [`占比口径:${visual.coverage.shareBasis}`] : []),
|
||||
].filter(Boolean);
|
||||
const headerLines = headerParts.flatMap(part => wrapLines(part, 96, 4));
|
||||
const chartTop = 30 + titleLines.length * 28 + headerLines.length * 17 + 20;
|
||||
const chartTop = reportMode ? 18 : 30 + titleLines.length * 28 + headerLines.length * 17 + 20;
|
||||
const footerParts = [
|
||||
...(visual.type === 'donut' ? visualDonutShares(visual).map(({ categoryIndex, valueKg, share }) =>
|
||||
`${visualCategoryLabel(visual, categoryIndex)}:${formatVisualValue(valueKg, 'kg')}(占本图已列类别重量合计 ${visualDonutShareText(share)})`) : []),
|
||||
...(!reportMode && visual.type === 'donut' ? visualDonutShares(visual).map(({ categoryIndex, valueKg, share }) =>
|
||||
`${visualCategoryLabel(visual, categoryIndex)}:${formatChartValue(valueKg, 'kg')}(占本图已列类别重量合计 ${visualDonutShareText(share)})`) : []),
|
||||
...(visual.type === 'pareto' ? ['柏拉图累计占比=累计重量÷本图已列类别重量合计;不代表正式总报废累计占比'] : []),
|
||||
...(visual.note ? [`说明:${visual.note}`] : []),
|
||||
...(visual.evidenceRefs.length ? [`证据引用:${visual.evidenceRefs.join(' · ')}`] : []),
|
||||
...(visual.type === 'waterfall' ? ['阶段影响是对综合合格率变化的数学拆解,不代表生产根因。'] : []),
|
||||
...(!reportMode && visual.note ? [`说明:${visual.note}`] : []),
|
||||
...(!reportMode && visual.evidenceRefs.length ? [`证据引用:${visual.evidenceRefs.join(' · ')}`] : []),
|
||||
];
|
||||
const footerLines = footerParts.flatMap(part => wrapLines(part, 124));
|
||||
const chartBottom = footerLines.length ? footerLines.length * 15 + 28 : 24;
|
||||
const chartBottom = footerLines.length ? footerLines.length * 15 + (reportMode ? 20 : 28) : (reportMode ? 10 : 24);
|
||||
|
||||
const wrappedCategories = visual.categories.map((_category, index) =>
|
||||
wrapLines(visualCategoryLabel(visual, index), 18, 4));
|
||||
const wrappedCategories = visual.categories.map((_category, index) => wrapLines(visualCategoryLabel(visual, index), 14));
|
||||
const categoryLabelHeight = wrappedCategories.reduce((total, lines) => total + Math.max(28, lines.length * 14 + 8), 0);
|
||||
const chartHeight = visual.type === 'donut' ? 600
|
||||
: visual.type === 'heatmap' ? Math.max(240, visual.series.length * 90)
|
||||
: Math.max(480, categoryLabelHeight);
|
||||
const maxCategoryLines = Math.max(1, ...wrappedCategories.map(lines => lines.length));
|
||||
const chartHeight = visual.type === 'donut' ? (reportMode ? Math.max(390, 290 + maxCategoryLines * 20) : Math.max(600, 300 + maxCategoryLines * 20))
|
||||
: visual.type === 'waterfall' ? (reportMode ? 300 : 480)
|
||||
: visual.type === 'heatmap' ? Math.max(reportMode ? 180 : 240, visual.series.length * (reportMode ? 62 : 90))
|
||||
: visual.type === 'pareto' ? (reportMode ? Math.max(300, 170 + maxCategoryLines * 18) : Math.max(480, categoryLabelHeight))
|
||||
: reportMode ? visual.type === 'bar' ? Math.max(230, categoryLabelHeight * 1.3) : Math.max(230, 165 + maxCategoryLines * 20) : Math.max(480, categoryLabelHeight);
|
||||
const height = chartTop + chartHeight + chartBottom;
|
||||
const base = buildAnalysisVisualOption(visual, { ink: '#263c5a', mutedInk: '#65748b', line: '#dfe5ef', surface: '#ffffff' });
|
||||
const categories = wrappedCategories.map(lines => lines.join('\n'));
|
||||
const donutShares = visual.type === 'donut' ? visualDonutShares(visual) : [];
|
||||
const valueAxisLabel = (value: number) => visual.unit === 'ratio'
|
||||
? `${chartNumber(value)}%`
|
||||
: `${chartNumber(value)}${visual.unit === 'pp' ? ' pp' : visual.unit === 'kg' ? ' kg' : ''}`;
|
||||
const allSeriesSelected = Object.fromEntries(visual.series.map(series => [series.label, true]));
|
||||
: formatChartValue(value, visual.unit, false);
|
||||
const allSeriesSelected = Object.fromEntries(visual.series.map(series => [plainRichText(series.label), true]));
|
||||
const legendOption = visual.type === 'donut'
|
||||
? {
|
||||
show: true,
|
||||
@@ -690,24 +856,24 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
bottom: chartBottom + 4,
|
||||
textStyle: { color: '#65748b', fontSize: 11 },
|
||||
formatter: (name: string) => {
|
||||
const index = visual.categories.findIndex((_category, categoryIndex) => visualCategoryLabel(visual, categoryIndex) === name);
|
||||
const index = visual.categories.findIndex((_category, categoryIndex) => plainRichText(visualCategoryLabel(visual, categoryIndex)) === name);
|
||||
const share = donutShares[index];
|
||||
return index < 0 || !share ? plainRichText(name) : plainRichText(`${name} · ${formatVisualValue(share.valueKg, 'kg')} · ${visualDonutShareText(share.share)}`);
|
||||
return index < 0 || !share ? plainRichText(name) : plainRichText(`${name} · ${formatChartValue(share.valueKg, 'kg')} · ${visualDonutShareText(share.share)}`);
|
||||
},
|
||||
}
|
||||
: visual.type === 'pareto'
|
||||
? {
|
||||
show: true,
|
||||
type: 'plain' as const,
|
||||
top: chartTop - 26,
|
||||
top: reportMode ? chartTop + 2 : chartTop - 26,
|
||||
left: 56,
|
||||
data: [visual.series[0].label, '累计占本图已列类别合计'],
|
||||
data: [plainRichText(visual.series[0].label), '累计占本图已列类别合计'],
|
||||
textStyle: { color: '#65748b', fontSize: 11 },
|
||||
}
|
||||
: {
|
||||
show: visual.series.length > 1,
|
||||
type: 'scroll' as const,
|
||||
top: chartTop - 26,
|
||||
top: reportMode ? chartTop + 2 : chartTop - 26,
|
||||
left: 56,
|
||||
selected: allSeriesSelected,
|
||||
textStyle: { color: '#65748b', fontSize: 11 },
|
||||
@@ -717,7 +883,7 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
...base,
|
||||
animation: false,
|
||||
tooltip: { show: false },
|
||||
title: {
|
||||
title: reportMode ? { show: false, text: '', subtext: '' } : {
|
||||
text: plainRichText(titleLines.join('\n')),
|
||||
subtext: plainRichText(headerLines.join('\n')),
|
||||
left: 56,
|
||||
@@ -744,7 +910,7 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
elements: [
|
||||
...(donutShares.length ? [{
|
||||
type: 'text', left: 'center', top: chartTop + chartHeight * 0.39 - 22, silent: true,
|
||||
style: { text: `所列类别合计\n${formatVisualValue(donutShares.reduce((sum, item) => sum + item.valueKg, 0), 'kg')}`, textAlign: 'center', fill: '#263c5a', font: '600 16px sans-serif', lineHeight: 25 },
|
||||
style: { text: `所列类别合计\n${formatChartValue(donutShares.reduce((sum, item) => sum + item.valueKg, 0), 'kg')}`, textAlign: 'center', fill: '#263c5a', font: '600 16px sans-serif', lineHeight: 25 },
|
||||
}] : []),
|
||||
...(footerLines.length ? [{
|
||||
type: 'text', left: 56, top: chartTop + chartHeight + 14, silent: true,
|
||||
@@ -762,7 +928,7 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
formatter: (params: { dataIndex?: number }) => {
|
||||
const index = Number.isInteger(params?.dataIndex) ? params.dataIndex as number : -1;
|
||||
const share = donutShares[index];
|
||||
return share ? plainRichText(`${visualCategoryLabel(visual, index)}\n${formatVisualValue(share.valueKg, 'kg')} · ${visualDonutShareText(share.share)}`) : '';
|
||||
return share ? plainRichText(`${visualCategoryLabel(visual, index)}\n${formatChartValue(share.valueKg, 'kg')} · ${visualDonutShareText(share.share)}`) : '';
|
||||
},
|
||||
},
|
||||
labelLine: { show: true, length: 16, length2: 12, lineStyle: { color: '#dfe5ef' } },
|
||||
@@ -798,14 +964,31 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
axisLine: { lineStyle: { color: '#dfe5ef' } }, axisTick: { show: false },
|
||||
},
|
||||
yAxis: [
|
||||
{ type: 'value', min: 0, name: '重量(kg)', nameTextStyle: { color: '#65748b', fontSize: 10 }, axisLabel: { color: '#65748b', formatter: (value: number) => `${chartNumber(value)} kg` }, axisLine: { show: false }, splitLine: { lineStyle: { color: '#dfe5ef', type: 'dashed' } } },
|
||||
{ type: 'value', min: 0, name: '重量(kg)', nameTextStyle: { color: '#65748b', fontSize: 10 }, axisLabel: { color: '#65748b', formatter: (value: number) => formatChartValue(value, 'kg') }, axisLine: { show: false }, splitLine: { lineStyle: { color: '#dfe5ef', type: 'dashed' } } },
|
||||
{ type: 'value', min: 0, max: 100, position: 'right', name: '累计占比(本图已列类别)', nameTextStyle: { color: '#65748b', fontSize: 10 }, axisLabel: { color: '#65748b', formatter: (value: number) => `${chartNumber(value)}%` }, axisLine: { show: false }, splitLine: { show: false } },
|
||||
],
|
||||
series: [
|
||||
{ name: visual.series[0].label, type: 'bar', yAxisIndex: 0, data: visual.series[0].values, barMaxWidth: 48, itemStyle: { color: '#607ae1' }, label: { show: true, position: 'top', color: '#263c5a', fontSize: 10, formatter: (params: { dataIndex: number }) => formatVisualValue(visualParetoPoints(visual)[params.dataIndex]?.valueKg ?? null, 'kg') } },
|
||||
{ name: plainRichText(visual.series[0].label), type: 'bar', yAxisIndex: 0, data: visual.series[0].values, barMaxWidth: 48, itemStyle: { color: '#607ae1' }, label: { show: true, position: 'top', color: '#263c5a', fontSize: 10, formatter: (params: { dataIndex: number }) => formatChartValue(visualParetoPoints(visual)[params.dataIndex]?.valueKg ?? null, 'kg') } },
|
||||
{ name: '累计占本图已列类别合计', type: 'line', yAxisIndex: 1, data: visualParetoPoints(visual).map(point => chartNumber(point.cumulativeShare * 100)), symbol: 'circle', symbolSize: 7, lineStyle: { width: 2.2, color: '#435d7a' }, itemStyle: { color: '#435d7a' }, label: { show: true, position: 'top', color: '#435d7a', fontSize: 10, formatter: (params: { data?: number }) => visualDonutShareText((params.data || 0) / 100) } },
|
||||
],
|
||||
}
|
||||
: visual.type === 'waterfall'
|
||||
? {
|
||||
legend: { show: false },
|
||||
grid: { left: 76, right: 42, top: chartTop + 8, bottom: chartBottom + 76, containLabel: true },
|
||||
xAxis: {
|
||||
type: 'category', data: categories, boundaryGap: true,
|
||||
axisLabel: { color: '#263c5a', fontSize: 11, lineHeight: 15, width: 180, overflow: 'break', interval: 0, hideOverlap: false },
|
||||
axisLine: { lineStyle: { color: '#dfe5ef' } }, axisTick: { show: false },
|
||||
},
|
||||
yAxis: {
|
||||
type: 'value', min: (base as any).yAxis?.min, max: (base as any).yAxis?.max, scale: false,
|
||||
name: '变化(百分点)', nameTextStyle: { color: '#65748b', fontSize: 10 },
|
||||
axisLabel: { color: '#65748b', formatter: valueAxisLabel }, axisLine: { show: false },
|
||||
splitLine: { lineStyle: { color: '#dfe5ef', type: 'dashed' } },
|
||||
},
|
||||
series: (base as any).series,
|
||||
}
|
||||
: visual.type === 'bar'
|
||||
? {
|
||||
xAxis: {
|
||||
@@ -832,7 +1015,7 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
type: 'category',
|
||||
data: categories,
|
||||
boundaryGap: visual.type === 'column',
|
||||
axisLabel: { color: '#263c5a', fontSize: 10, lineHeight: 12, rotate: categories.length > 10 ? 28 : 0, width: 112, overflow: 'break', hideOverlap: true },
|
||||
axisLabel: { color: '#263c5a', fontSize: 10, lineHeight: 13, rotate: categories.length > 5 ? 42 : 0, width: 160, overflow: 'break', interval: 0, hideOverlap: false },
|
||||
axisLine: { lineStyle: { color: '#dfe5ef' } },
|
||||
axisTick: { show: false },
|
||||
},
|
||||
@@ -845,9 +1028,22 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
axisLine: { show: false },
|
||||
splitLine: { lineStyle: { color: '#dfe5ef', type: 'dashed' } },
|
||||
},
|
||||
grid: { left: 64, right: 42, top: chartTop, bottom: chartBottom + (visual.type === 'column' ? 80 : 68), containLabel: true },
|
||||
grid: { left: 64, right: 42, top: chartTop, bottom: chartBottom + (visual.type === 'column' ? 80 : reportMode ? 110 : 68), containLabel: true },
|
||||
}),
|
||||
};
|
||||
if (reportMode) {
|
||||
// 图片按报告正文列宽显示,确保缩放后的标签仍然可读。
|
||||
const enlargeText = (value: unknown): void => {
|
||||
if (!value || typeof value !== 'object') return;
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (key === 'fontSize' && typeof child === 'number') (value as Record<string, unknown>)[key] = Math.max(14, child);
|
||||
else if (key === 'lineHeight' && typeof child === 'number') (value as Record<string, unknown>)[key] = Math.max(18, child);
|
||||
else enlargeText(child);
|
||||
}
|
||||
};
|
||||
enlargeText(option);
|
||||
(option as Record<string, unknown>).textStyle = { fontSize: 14, fontFamily: '-apple-system,BlinkMacSystemFont,PingFang SC,Microsoft YaHei,sans-serif' };
|
||||
}
|
||||
return { option, width, height };
|
||||
}
|
||||
|
||||
@@ -986,6 +1182,9 @@ function waitForFont(signal?: AbortSignal): Promise<void> {
|
||||
function svgToPng(svg: string, width: number, height: number, signal?: AbortSignal): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
throwIfAborted(signal);
|
||||
const parsedSvg = new DOMParser().parseFromString(svg, 'image/svg+xml');
|
||||
const syntaxError = parsedSvg.querySelector('parsererror');
|
||||
if (syntaxError) { reject(new Error(`图表 SVG 格式错误:${syntaxError.textContent?.slice(0, 240)}`)); return; }
|
||||
const svgUrl = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml;charset=utf-8' }));
|
||||
const image = new Image();
|
||||
const canvas = document.createElement('canvas');
|
||||
@@ -1020,13 +1219,13 @@ function svgToPng(svg: string, width: number, height: number, signal?: AbortSign
|
||||
}
|
||||
|
||||
/** Render a snapshot independently of any visible chart instance or current legend state. */
|
||||
export async function renderVisualPng(visualOrUnknown: AnalysisVisual | unknown, signal?: AbortSignal): Promise<string> {
|
||||
export async function renderVisualPng(visualOrUnknown: AnalysisVisual | unknown, signal?: AbortSignal, context: AnalysisVisualRenderContext = 'standalone'): Promise<string> {
|
||||
const parsed = parseAnalysisVisuals([visualOrUnknown]);
|
||||
const visual = parsed.visuals[0];
|
||||
if (!visual || !visual.chartable) throw new Error(visual?.chartIssue || parsed.issues[0] || '没有可导出的图表数据');
|
||||
if (typeof document === 'undefined') throw new Error('图表图片只能在浏览器中生成');
|
||||
throwIfAborted(signal);
|
||||
const { option, width, height } = buildAnalysisVisualExportOption(visual, 1280);
|
||||
const { option, width, height } = buildAnalysisVisualExportOption(visual, context === 'report' ? 900 : 1280, context);
|
||||
const node = document.createElement('div');
|
||||
Object.assign(node.style, { position: 'fixed', left: '-10000px', top: '0', width: `${width}px`, height: `${height}px`, background: '#ffffff', color: '#263c5a', pointerEvents: 'none' });
|
||||
document.body.appendChild(node);
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { buildAnalysisNarrative, classifyAnalysisSection } from './analysisReportModel';
|
||||
import { reportVisualHtml, type ReportVisualImage } from './AnalysisReportVisuals';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
const normalized = (value: string) => value.replace(/^\s*(?:[一二三四五六七八九十]+[、..]|\d+(?:\.\d+)*[、..)\s]+)\s*/, '').replace(/[\s·//::、,,()().]+/g, '').toLowerCase();
|
||||
function chapterText(heading: Element): string {
|
||||
const content = [heading.textContent || ''];
|
||||
for (let sibling = heading.nextElementSibling; sibling && !/^H[1-4]$/.test(sibling.tagName); sibling = sibling.nextElementSibling) content.push(sibling.textContent || '');
|
||||
return content.join('\n');
|
||||
}
|
||||
|
||||
/** 保留原生 HTML 内容,在对应章节插入图表。 */
|
||||
export function integrateNativeReportNarrative(source: string, turn: Row, images: ReportVisualImage[]): string {
|
||||
const doc = new DOMParser().parseFromString(source, 'text/html');
|
||||
const result = turn.result && typeof turn.result === 'object' ? turn.result as Row : turn;
|
||||
const text = String(result.reportMarkdown || turn.reportMarkdown || result.answer || turn.answer || '');
|
||||
const model = buildAnalysisNarrative(text, result.visuals || turn.visuals, String(turn.question || ''));
|
||||
const headings = [...doc.querySelectorAll('h1,h2,h3,h4')];
|
||||
const assigned = new Set<string>();
|
||||
for (const section of model.sections) {
|
||||
if (!section.title || !section.visuals.length) continue;
|
||||
const exact = headings.find(element => normalized(element.textContent || '') === normalized(section.title));
|
||||
// 原生模板可能使用不同章节名称,仅在语义匹配唯一且阶段一致时回退。
|
||||
const compatible = headings.filter(element => {
|
||||
const title = element.textContent || '';
|
||||
if (classifyAnalysisSection(title) !== section.kind) return false;
|
||||
const stages = new Set(section.visuals.map(visual => visual.stage).filter(Boolean));
|
||||
if (/黑片/.test(title) && !/亮片/.test(title) && stages.has('bright')) return false;
|
||||
if (/亮片/.test(title) && !/黑片/.test(title) && stages.has('black')) return false;
|
||||
const localNames = section.visuals.flatMap(visual => ['department','group','product'].map(key => visual.scope[key])).filter((name): name is string => typeof name === 'string' && !!name);
|
||||
return !localNames.length || localNames.every(name => chapterText(element).includes(name));
|
||||
});
|
||||
const heading = exact || (compatible.length === 1 ? compatible[0] : undefined);
|
||||
if (!heading) continue;
|
||||
const figure = doc.createElement('div');
|
||||
figure.className = 'platform-chapter-figures';
|
||||
figure.innerHTML = reportVisualHtml({ ...turn, result: { ...result, visuals: section.visuals, visualSchemaVersion: 1 } }, images);
|
||||
// 解读保留在图前,原有表格保留在图后。
|
||||
let anchor: Element = heading;
|
||||
let sibling = heading.nextElementSibling;
|
||||
while (sibling && ['P', 'BLOCKQUOTE'].includes(sibling.tagName)) { anchor = sibling; sibling = sibling.nextElementSibling; }
|
||||
anchor.after(figure);
|
||||
section.visuals.forEach(visual => assigned.add(visual.id));
|
||||
}
|
||||
const remaining = model.sections.flatMap(section => section.visuals).filter(visual => !assigned.has(visual.id));
|
||||
if (remaining.length) {
|
||||
const appendix = doc.createElement('section');
|
||||
appendix.className = 'platform-chapter-figures';
|
||||
const heading = doc.createElement('h2'); heading.textContent = '补充分析图表'; appendix.append(heading);
|
||||
const content = doc.createElement('div');
|
||||
content.innerHTML = reportVisualHtml({ ...turn, result: { ...result, visuals: remaining, visualSchemaVersion: 1 } }, images);
|
||||
appendix.append(content); doc.body.append(appendix);
|
||||
}
|
||||
return '<!doctype html>\n' + doc.documentElement.outerHTML;
|
||||
}
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
declare module '*.css?inline' {
|
||||
const content: string;
|
||||
export default content;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { buildAnalysisNarrative, narrativeParts, isRateComparison, useCompactRateComparison } from '../src/analysisReportModel.ts';
|
||||
|
||||
const visual = (overrides = {}) => ({
|
||||
id: 'chart-1', type: 'column', title: '综合合格率期间比较', subtitle: '2026-08 → 2026-09', unit: 'ratio',
|
||||
categories: [{ key: 'comparison', label: '2026-08' }, { key: 'current', label: '2026-09' }],
|
||||
series: [{ key: 'composite_rate', label: '综合合格率', values: [0.9557, 0.9513] }],
|
||||
evidenceRefs: ['Q1234ABCD'], requiredFields: ['black_good_weight','black_total_weight','bright_good_weight','bright_total_weight'],
|
||||
scope: { year: 2026, month: 9, releaseId: 'release-a' }, period: { year: 2026, month: 9 }, comparisonPeriod: { year: 2026, month: 8 },
|
||||
metric: 'composite_rate', coverage: { totalRows: 2, returnedRows: 2, truncated: false }, originTurnId: 'turn-1', ...overrides,
|
||||
});
|
||||
|
||||
test('paragraphs and exact tables are retained with charts next to their semantic chapter', () => {
|
||||
const source = '综合率下降。[Q1234ABCD]\n\n### 产业部变化\n重点组织发生变化。\n\n| 组织 | 变化 |\n| --- | --- |\n| 电机 | -0.24 |\n\n### 优先核查\n核对投入。';
|
||||
const model = buildAnalysisNarrative(source, [visual(), visual({ id: 'department', type: 'bar', unit: 'pp', metric: 'rate_drop_pp', title: '产业部合格率变化', categories: [{key:'motor',label:'电机'},{key:'consumer',label:'消费电子'}], series: [{key:'rate_drop_pp',label:'下降百分点',values:[0.24,-0.34]}], evidenceRefs: ['Q5678ABCD'] })], '分析合格率下降原因');
|
||||
assert.equal(model.sections[0].visuals[0].id, 'chart-1');
|
||||
const department = model.sections.find(section => section.kind === 'department');
|
||||
assert.equal(department.visuals[0].id, 'department');
|
||||
assert.match(department.narrative, /重点组织发生变化/);
|
||||
assert.match(department.tables[0], /电机 \| -0.24/);
|
||||
assert.equal(model.sections.at(-1).kind, 'action');
|
||||
assert.equal(model.sections.flatMap(section => section.visuals).length, 2);
|
||||
assert.equal(model.evidenceLabels.Q1234ABCD, '依据 1');
|
||||
});
|
||||
|
||||
test('scoped defect crosscheck stays with its own evidence instead of the global defect chapter', () => {
|
||||
const v = visual({ id:'scoped',type:'bar',unit:'kg',metric:'source_defect_delta_weight',stage:'black',title:'黑片来源具体缺陷报废增减',scope:{year:2026,month:9,releaseId:'release-a',group:'汽车交通-国内',stage:'black'},evidenceRefs:['Q5678ABCD'],requiredFields:['责废缺角重量'],series:[{key:'source_defect_delta_weight',label:'缺陷增量',values:[200,100]}] });
|
||||
const model = buildAnalysisNarrative('### 黑片来源具体缺陷\n全公司缺角变化。[Q1234ABCD]\n### 已核对的组织与缺陷联系\n汽车交通-国内的缺角增加。[Q5678ABCD]',[v]);
|
||||
assert.equal(model.sections.find(section=>section.kind==='defect').visuals.length,0);
|
||||
assert.equal(model.sections.find(section=>section.kind==='crosscheck').visuals[0].id,'scoped');
|
||||
});
|
||||
|
||||
test('opposite stages are never placed together by a shared evidence reference', () => {
|
||||
const v=visual({id:'bright',type:'bar',unit:'kg',stage:'bright',metric:'source_defect_delta_weight',title:'亮片来源具体缺陷',requiredFields:['加工缺角重量'],series:[{key:'source_defect_delta_weight',label:'重量',values:[2,3]}]});
|
||||
const model=buildAnalysisNarrative('### 黑片来源具体缺陷\n[Q1234ABCD]\n### 亮片来源具体缺陷\n[Q1234ABCD]',[v]);
|
||||
assert.equal(model.sections[0].visuals.length,0);assert.equal(model.sections[1].visuals.length,1);
|
||||
});
|
||||
|
||||
test('headings inside fences and unknown narrative content are preserved',()=>{
|
||||
const source='普通回答。\n\n```text\n### 代码内标题\n| a | b |\n|---|---|\n```\n\n### 特别说明\n内容不得丢失。';
|
||||
const model=buildAnalysisNarrative(source,[]);
|
||||
assert.equal(model.sections.length,2);assert.match(model.sections[0].markdown,/### 代码内标题/);assert.match(model.sections[1].markdown,/内容不得丢失/);
|
||||
assert.equal(narrativeParts(model.sections[0].markdown).tables.length,0);
|
||||
});
|
||||
|
||||
test('single-value answers, text-only and old turns remain complete without invented figures',()=>{
|
||||
const m=buildAnalysisNarrative('9月综合合格率95.13%。',undefined,'9月合格率是多少');
|
||||
assert.equal(m.sections.length,1);assert.equal(m.sections[0].markdown,'9月综合合格率95.13%。');assert.equal(m.sections[0].title,'');assert.equal(m.sections[0].visuals.length,0);
|
||||
});
|
||||
|
||||
test('unmatched chart is retained once under a separately named chapter',()=>{
|
||||
const m=buildAnalysisNarrative('### 下一步\n继续核查。',[visual()]);
|
||||
assert.equal(m.sections.flatMap(s=>s.visuals).length,1);assert.equal(m.sections.find(s=>s.visuals.length).kind,'overview');
|
||||
});
|
||||
|
||||
test('compact comparison is limited to valid two-period stage-rate snapshots',()=>{
|
||||
const m=buildAnalysisNarrative('两期比较',[visual()]);assert.equal(isRateComparison(m.sections.flatMap(s=>s.visuals)[0]),true);
|
||||
const missing=buildAnalysisNarrative('两期比较',[visual({series:[{key:'composite_rate',label:'率',values:[null,0.95]}]})]);assert.equal(isRateComparison(missing.sections.flatMap(s=>s.visuals)[0]),false);
|
||||
});
|
||||
|
||||
test('combined black and bright chapter retains both stage comparisons',()=>{
|
||||
const stages=['black','bright'].map(stage=>visual({id:stage,sectionKey:'stage',stage,metric:`${stage}_rate`,series:[{key:`${stage}_rate`,label:stage,values:[0.97,0.96]}]}));
|
||||
const model=buildAnalysisNarrative('### 黑片与亮片阶段变化\n阶段均有变化。[Q1234ABCD]',stages);
|
||||
assert.equal(model.sections.length,1);
|
||||
assert.deepEqual(model.sections[0].visuals.map(v=>v.id),['black','bright']);
|
||||
});
|
||||
|
||||
test('explicit bar or column requests keep charts while default rate comparisons stay compact',()=>{
|
||||
const v=buildAnalysisNarrative('两期比较',[visual()]).sections.flatMap(s=>s.visuals)[0];
|
||||
assert.equal(useCompactRateComparison(v,'比较合格率'),true);
|
||||
for(const request of ['用柱状图比较','用横条图比较','用条形图比较','用柱形图比较']) assert.equal(useCompactRateComparison(v,request),false);
|
||||
});
|
||||
|
||||
test('a short answer without headings keeps its requested chart next to the cited prose',()=>{
|
||||
const v=visual({id:'trend',type:'area',sectionKey:'trend',title:'产品趋势'});
|
||||
const m=buildAnalysisNarrative('该规格两期正式值如下。[Q1234ABCD]\n\n| 期间 | 值 |\n| --- | --- |\n| 8月 | 95.57% |\n| 9月 | 95.13% |',[v]);
|
||||
assert.equal(m.sections.length,1);assert.equal(m.sections[0].visuals[0].id,'trend');assert.equal(m.sections[0].tables.length,1);
|
||||
});
|
||||
|
||||
test('long plotting instructions become a concise report title with the full question retained by the caller',()=>{
|
||||
const question='请用纵向柱状图展示消费电子业务分组本月与上月的正式综合合格率,只需要两个期间和正式数值,简短回答,不查询其他范围';
|
||||
const model=buildAnalysisNarrative('两期比较。[Q1234ABCD]',[visual()],question);
|
||||
assert.equal(model.title,'2026-08 → 2026-09 质量变化分析');assert.ok(model.title.length<40);
|
||||
});
|
||||
|
||||
test('table-specific citation and coverage remain with the full table details',()=>{
|
||||
const part=narrativeParts('本节结论。[Q1234ABCD]\n\n| 对象 | 重量 |\n| --- | --- |\n| A | 12 |\n\n[Q1234ABCD] 共20项,本节展示1项。\n\n后续说明。');
|
||||
assert.match(part.narrative,/本节结论/);assert.match(part.narrative,/后续说明/);
|
||||
assert.doesNotMatch(part.narrative,/共20项/);assert.match(part.tables[0],/共20项,本节展示1项/);
|
||||
});
|
||||
|
||||
test('scoped comparisons cannot enter a global overview or stage chapter',()=>{
|
||||
const product='16.33X15.5X3.75+T';
|
||||
const local=visual({id:'product-rate',scope:{year:2026,month:9,releaseId:'release-a',product},evidenceRefs:['Q9999ABCD']});
|
||||
const stage=visual({...local,id:'product-black',sectionKey:'stage',stage:'black',metric:'black_rate',series:[{key:'black_rate',label:'黑片',values:[0.98,0.97]}]});
|
||||
const m=buildAnalysisNarrative('总体变化。[Q1234ABCD]\n\n### 总体与阶段\n全局阶段。',[local,visual(),stage]);
|
||||
assert.equal(m.sections[0].visuals.length,1);assert.equal(m.sections[0].visuals[0].id,'chart-1');
|
||||
assert.equal(m.sections[1].visuals.length,0);
|
||||
assert.ok(m.sections.filter(s=>s.visuals.some(v=>v.id.startsWith('product-'))).every(s=>s.title.includes(product)));
|
||||
const matched=buildAnalysisNarrative(`总体变化。[Q1234ABCD]\n\n### 重点产品\n${product} 的变化。`,[visual(),local,stage]);
|
||||
assert.equal(matched.sections.find(s=>s.kind==='product').visuals.length,2);
|
||||
});
|
||||
@@ -61,6 +61,28 @@ function pareto(overrides = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
function waterfall(overrides = {}) {
|
||||
return visual({
|
||||
type: 'waterfall',
|
||||
title: '综合率变化的阶段数学影响',
|
||||
subtitle: '对比两个期间的正式综合率变化',
|
||||
unit: 'pp',
|
||||
categories: [
|
||||
{ key: 'black', label: '黑片贡献' },
|
||||
{ key: 'bright', label: '亮片贡献' },
|
||||
{ key: 'total', label: '综合变化' },
|
||||
],
|
||||
series: [{ key: 'composite_impact_pp', label: '综合率阶段影响', values: [1.25, -0.25, 1] }],
|
||||
requiredFields: ['black_good_weight', 'black_total_weight', 'bright_good_weight', 'bright_total_weight'],
|
||||
scope: { department: '工业电机' },
|
||||
period: { label: '2026-09' },
|
||||
comparisonPeriod: { label: '2026-08' },
|
||||
metric: 'composite_impact_pp',
|
||||
note: '数学拆解,不代表生产根因。',
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
test('parser preserves zero and null as different values', () => {
|
||||
const parsed = parseAnalysisVisuals([visual({ series: [{ key: 'a', label: 'A', values: [null, 0] }] })]);
|
||||
assert.equal(parsed.visuals.length, 1);
|
||||
@@ -124,6 +146,7 @@ test('business labels remain plain text in tooltip output and data options', ()
|
||||
assert.equal(option.tooltip.renderMode, 'richText');
|
||||
const tooltip = option.tooltip.formatter([{ dataIndex: 0, seriesIndex: 0 }]);
|
||||
assert.equal(tooltip.includes('<script>alert(1)</script>'), true);
|
||||
assert.equal(tooltip.includes('{style|name}'), true);
|
||||
assert.equal(tooltip.includes('<br'), false);
|
||||
assert.equal(tooltip.includes('<strong>'), false);
|
||||
});
|
||||
@@ -226,10 +249,10 @@ test('duplicate ids, malformed values, and over-size payloads do not break neigh
|
||||
assert.match(oversized.issues[0], /大小限制/);
|
||||
});
|
||||
|
||||
test('only three visuals are admitted to a chat render', () => {
|
||||
const result = parseAnalysisVisuals([visual(), visual({ id: 'visual-2' }), visual({ id: 'visual-3' }), visual({ id: 'visual-4' })]);
|
||||
assert.equal(result.visuals.length, 3);
|
||||
assert.ok(result.issues.some(issue => issue.includes('前 3 张')));
|
||||
test('up to twelve visuals are admitted while later charts stay outside the render', () => {
|
||||
const result = parseAnalysisVisuals(Array.from({ length: 13 }, (_, index) => visual({ id: `visual-${index + 1}` })));
|
||||
assert.equal(result.visuals.length, 12);
|
||||
assert.ok(result.issues.some(issue => issue.includes('前 12 张')));
|
||||
});
|
||||
|
||||
test('column is vertical, preserves zero and places negative values below their endpoints', () => {
|
||||
@@ -511,3 +534,160 @@ test('negative area data is shown as a table rather than filled as a valid trend
|
||||
assert.equal(model.chartable, false);
|
||||
assert.match(model.chartIssue, /负值/);
|
||||
});
|
||||
|
||||
test('report export removes duplicated context but standalone export keeps full context', () => {
|
||||
const model = parseAnalysisVisuals([visual({ note: '需在原始表格保持精确值。' })]).visuals[0];
|
||||
const standalone = buildAnalysisVisualExportOption(model);
|
||||
const report = buildAnalysisVisualExportOption(model, 1280, 'report');
|
||||
assert.match(standalone.option.title.text, /月度合格率/);
|
||||
assert.match(standalone.option.title.subtext, /期间:2026-08 → 2026-08 至 2026-09/);
|
||||
assert.match(standalone.option.title.subtext, /范围:产业部:工业电机/);
|
||||
assert.equal(report.width, 1280);
|
||||
assert.equal(report.option.title.show, false);
|
||||
assert.equal(report.option.title.text, '');
|
||||
assert.equal(report.option.title.subtext, '');
|
||||
assert.ok(report.height < standalone.height);
|
||||
assert.equal(report.option.tooltip.show, false);
|
||||
});
|
||||
|
||||
test('section and dimension metadata use fixed enums and unknown visual keys are rejected', () => {
|
||||
const valid = parseAnalysisVisuals([visual({ sectionKey: 'department', dimension: 'department' })]);
|
||||
assert.equal(valid.visuals[0].sectionKey, 'department');
|
||||
assert.equal(valid.visuals[0].dimension, 'department');
|
||||
assert.deepEqual(parseAnalysisVisuals([visual({ sectionKey: 'run-code' })]).visuals, []);
|
||||
assert.deepEqual(parseAnalysisVisuals([visual({ dimension: 'anything' })]).visuals, []);
|
||||
assert.deepEqual(parseAnalysisVisuals([visual({ executable: 'alert(1)' })]).visuals, []);
|
||||
assert.deepEqual(parseAnalysisVisuals([visual({ categories: [{ key: 'x', label: 'X', renderer: 'html' }, { key: 'y', label: 'Y' }] })]).visuals, []);
|
||||
});
|
||||
|
||||
test('untrusted getters and function-valued metadata never run in the parser', () => {
|
||||
let getterCalled = false;
|
||||
const hostile = visual();
|
||||
Object.defineProperty(hostile, 'title', { enumerable: true, get() { getterCalled = true; return 'bad'; } });
|
||||
const getterResult = parseAnalysisVisuals([hostile]);
|
||||
assert.equal(getterCalled, false);
|
||||
assert.deepEqual(getterResult.visuals, []);
|
||||
|
||||
const functionValue = visual({ callback: () => { getterCalled = true; } });
|
||||
assert.deepEqual(parseAnalysisVisuals([functionValue]).visuals, []);
|
||||
assert.equal(getterCalled, false);
|
||||
});
|
||||
|
||||
test('waterfall validates authorized inputs and renders signed stages from a zero baseline', () => {
|
||||
const model = parseAnalysisVisuals([waterfall()]).visuals[0];
|
||||
assert.equal(model.chartable, true);
|
||||
const option = buildAnalysisVisualOption(model);
|
||||
assert.equal(option.legend.selectedMode, false);
|
||||
assert.deepEqual(option.legend.data, ['阶段影响', '综合变化']);
|
||||
assert.equal(option.series[0].name, '辅助基线');
|
||||
assert.equal(option.series[0].stackStrategy, 'all');
|
||||
assert.deepEqual(option.series[0].data, [0, 1, 0]);
|
||||
assert.deepEqual(option.series[1].data.map(item => item.value), [1.25, 0.25, 0]);
|
||||
assert.deepEqual(option.series[2].data.map(item => item.value), [0, 0, 1]);
|
||||
assert.equal(option.series[1].data[1].itemStyle.color, '#c66565');
|
||||
assert.equal(option.series[1].label.formatter({ dataIndex: 0 }), '+1.25 pp');
|
||||
assert.equal(option.series[1].label.formatter({ dataIndex: 1 }), '-0.25 pp');
|
||||
const tooltip = option.tooltip.formatter([{ dataIndex: 1, seriesIndex: 1 }]);
|
||||
assert.match(tooltip, /亮片贡献/);
|
||||
assert.match(tooltip, /-0.25 pp/);
|
||||
assert.match(tooltip, /不代表生产根因/);
|
||||
|
||||
const exported = buildAnalysisVisualExportOption(model, 1280, 'report');
|
||||
assert.equal(exported.option.title.show, false);
|
||||
assert.equal(exported.option.legend.show, false);
|
||||
assert.match(exported.option.graphic.elements[0].style.text, /数学拆解/);
|
||||
assert.match(exported.option.graphic.elements[0].style.text, /不代表生产根因/);
|
||||
assert.equal(exported.option.yAxis.name, '变化(百分点)');
|
||||
assert.ok(exported.height < 440);
|
||||
});
|
||||
|
||||
test('waterfall requires the exact four-field permission, two periods, an overall scope, and a matching sum', () => {
|
||||
const validTolerance = parseAnalysisVisuals([waterfall({ series: [{ key: 'composite_impact_pp', label: '影响', values: [1.25, -0.25, 1.000000009] }] })]).visuals[0];
|
||||
assert.equal(validTolerance.chartable, true);
|
||||
const badCases = [
|
||||
waterfall({ requiredFields: ['black_good_weight', 'black_total_weight', 'bright_good_weight'] }),
|
||||
waterfall({ requiredFields: ['black_good_weight', 'black_total_weight', 'bright_good_weight', 'bright_total_weight', 'bright_scrap_weight'] }),
|
||||
waterfall({ scope: { stage: 'black' } }),
|
||||
waterfall({ scope: { category: '责废' } }),
|
||||
waterfall({ scope: { defect: '裂纹' } }),
|
||||
waterfall({ stage: 'black' }),
|
||||
waterfall({ comparisonPeriod: undefined }),
|
||||
waterfall({ period: { label: '2026-08' }, comparisonPeriod: { label: '2026-08' } }),
|
||||
waterfall({ metric: 'combined_rate' }),
|
||||
waterfall({ unit: 'ratio' }),
|
||||
waterfall({ categories: [{ key: 'black', label: '黑片' }, { key: 'total', label: '总计' }, { key: 'bright', label: '亮片' }] }),
|
||||
waterfall({ series: [{ key: 'other', label: '影响', values: [1.25, -0.25, 1] }] }),
|
||||
waterfall({ series: [{ key: 'composite_impact_pp', label: '影响', values: [1.25, -0.25, 1.00000002] }] }),
|
||||
waterfall({ series: [{ key: 'composite_impact_pp', label: '影响', values: [1.25, null, 1] }] }),
|
||||
];
|
||||
for (const item of badCases) {
|
||||
const parsed = parseAnalysisVisuals([item]);
|
||||
assert.equal(parsed.visuals.length, 1, JSON.stringify(item));
|
||||
assert.equal(parsed.visuals[0].chartable, false, JSON.stringify(item));
|
||||
assert.match(parsed.visuals[0].chartIssue, /表/);
|
||||
}
|
||||
});
|
||||
|
||||
test('declining waterfall total remains negative and hides unused total labels', () => {
|
||||
const model = parseAnalysisVisuals([waterfall({series:[{key:'composite_impact_pp',label:'影响',values:[-0.30,-0.15,-0.45]}]})]).visuals[0];
|
||||
for(const option of [buildAnalysisVisualOption(model),buildAnalysisVisualExportOption(model,900,'report').option]) {
|
||||
assert.equal(option.series[2].data[2].value,-0.45);
|
||||
assert.equal(option.series[2].data[0].label.show,false);
|
||||
assert.equal(option.series[2].data[1].label.show,false);
|
||||
assert.equal(option.series[1].data[2].label.show,false);
|
||||
assert.deepEqual(option.series[0].data,[ -0.3,-0.44999999999999996,0 ]);
|
||||
}
|
||||
});
|
||||
|
||||
test('kg and pp chart labels round to two decimals while tooltips and tables keep source precision', () => {
|
||||
const model = parseAnalysisVisuals([visual({ type: 'column', unit: 'pp',
|
||||
categories: [{ key: 'up', label: '改善' }, { key: 'down', label: '下降' }],
|
||||
series: [{ key: 'change', label: '变化', values: [2.34567, -1.23456] }],
|
||||
})]).visuals[0];
|
||||
const option = buildAnalysisVisualOption(model);
|
||||
assert.equal(option.series[0].data[0].value, 2.34567);
|
||||
assert.equal(option.series[0].label.formatter({ dataIndex: 0 }), '+2.35 pp');
|
||||
assert.equal(option.series[0].label.formatter({ dataIndex: 1 }), '-1.23 pp');
|
||||
assert.match(option.tooltip.formatter([{ dataIndex: 0, seriesIndex: 0 }]), /2.34567 pp/);
|
||||
assert.match(renderVisualTableHtml(model), /2\.34567 pp/);
|
||||
|
||||
const ring = parseAnalysisVisuals([donut({ series: [{ key: 'source_defect_weight', label: '类别重量', values: [2.34567, 3, 4] }] })]).visuals[0];
|
||||
const ringOption = buildAnalysisVisualOption(ring);
|
||||
assert.match(ringOption.series[0].label.formatter({ dataIndex: 0 }), /2\.35 kg/);
|
||||
assert.match(ringOption.tooltip.formatter([{ dataIndex: 0, seriesIndex: 0 }]), /2.34567 kg/);
|
||||
assert.match(renderVisualTableHtml(ring), /2\.34567 kg/);
|
||||
});
|
||||
|
||||
test('report export fully wraps long donut, Pareto, and trend category names', () => {
|
||||
const longName = '很长的业务规格名称'.repeat(16);
|
||||
const ring = parseAnalysisVisuals([donut({
|
||||
categories: [
|
||||
{ key: 'black_responsibility_scrap', label: longName },
|
||||
{ key: 'black_material_scrap', label: '料废' },
|
||||
],
|
||||
series: [{ key: 'source_defect_weight', label: '类别重量', values: [8, 2] }],
|
||||
coverage: { totalRows: 2, returnedRows: 2, truncated: false, shareBasis: 'displayed_categories' },
|
||||
})]).visuals[0];
|
||||
const ringExport = buildAnalysisVisualExportOption(ring, 1280, 'report');
|
||||
assert.ok(ringExport.option.series[0].label.formatter({ dataIndex: 0 }).replaceAll('\n', '').includes(longName));
|
||||
assert.ok(ringExport.height > 390);
|
||||
|
||||
const ranked = parseAnalysisVisuals([pareto({
|
||||
categories: [
|
||||
{ key: 'black_responsibility_scrap', label: longName },
|
||||
{ key: 'black_material_scrap', label: '料废' },
|
||||
],
|
||||
series: [{ key: 'source_defect_weight', label: '类别重量', values: [8, 2] }],
|
||||
coverage: { totalRows: 2, returnedRows: 2, truncated: false, shareBasis: 'displayed_categories' },
|
||||
})]).visuals[0];
|
||||
const rankedExport = buildAnalysisVisualExportOption(ranked, 1280, 'report');
|
||||
assert.ok(rankedExport.option.xAxis.data[0].replaceAll('\n', '').includes(longName));
|
||||
|
||||
const trend = parseAnalysisVisuals([visual({ type: 'line',
|
||||
categories: [{ key: 'a', label: longName }, { key: 'b', label: '短名称' }],
|
||||
series: [{ key: 'overall', label: '综合', values: [0.82, 0.84] }],
|
||||
})]).visuals[0];
|
||||
const trendExport = buildAnalysisVisualExportOption(trend, 1280, 'report');
|
||||
assert.ok(trendExport.option.xAxis.data[0].replaceAll('\n', '').includes(longName));
|
||||
assert.equal(trendExport.option.xAxis.axisLabel.hideOverlap, false);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user