Combine black and bright defect charts in analysis reports
This commit is contained in:
@@ -16,7 +16,7 @@ releaseId、发布版本号、候选发布状态、Story ID/slug/version 仅作
|
|||||||
- 整体比较已返回两个阶段各报废大类的defects重量时,直接复用比较期与本期的数据分析大类增减,不重复为每个类别查询。具体缺陷用 defects 按黑片、亮片分别带 comparisonPeriod 查询;既关注报废增量,也结合当前重量识别主要存量问题,不把大类当小类。某阶段不适用或没有细分数据时如实说明,继续其余维度;原始细分为零不自动当作系统故障,也不因此中断分析。
|
- 整体比较已返回两个阶段各报废大类的defects重量时,直接复用比较期与本期的数据分析大类增减,不重复为每个类别查询。具体缺陷用 defects 按黑片、亮片分别带 comparisonPeriod 查询;既关注报废增量,也结合当前重量识别主要存量问题,不把大类当小类。某阶段不适用或没有细分数据时如实说明,继续其余维度;原始细分为零不自动当作系统故障,也不因此中断分析。
|
||||||
- 产品从报废增量、率变化、当前报废规模等角度找重点,核对阶段投入以区分放量、缩量与质量恶化;新增/退出规格单独解释。组织、产品和缺陷之间应有至少1至2条实际交叉查询支持的主要线索(如重点业务分组内TOP规格、重点规格的具体缺陷、某缺陷涉及的TOP规格),具体路线由前面结果决定。不要只并列几张互不关联的排名表,不要求逐个组织、产品全部下钻。
|
- 产品从报废增量、率变化、当前报废规模等角度找重点,核对阶段投入以区分放量、缩量与质量恶化;新增/退出规格单独解释。组织、产品和缺陷之间应有至少1至2条实际交叉查询支持的主要线索(如重点业务分组内TOP规格、重点规格的具体缺陷、某缺陷涉及的TOP规格),具体路线由前面结果决定。不要只并列几张互不关联的排名表,不要求逐个组织、产品全部下钻。
|
||||||
- 用户要深入分析时,最终通常需要具体的TOP规格和TOP报废分类,并对至少一个主要线索进一步核对。写清楚排名按报废重量、增量还是率降幅;看投入规模和缺失覆盖,避免把小批量最低率排成主要问题。没有适用数据时说明具体缺口。
|
- 用户要深入分析时,最终通常需要具体的TOP规格和TOP报废分类,并对至少一个主要线索进一步核对。写清楚排名按报废重量、增量还是率降幅;看投入规模和缺失覆盖,避免把小批量最低率排成主要问题。没有适用数据时说明具体缺口。
|
||||||
- 用户说TOP缺陷类型时,不要停留在责废/料废等大类:使用 quality_data 的 defects 模式查询主要阶段的实际具体缺陷TOP,必要时带 comparisonPeriod 看增量,再用 filters.product 或 dimension=product+defect 核对主要规格与具体缺陷的关系。缺陷源字段名、覆盖与对账结果均要尊重工具返回。
|
- 用户说TOP缺陷类型时,不要停留在责废/料废等大类:使用 quality_data 的 defects 模式查询主要阶段的实际具体缺陷TOP。每次 defects 调用都必须显式传 dimension;查某规格的具体缺陷时传 dimension=defect、stage=black 或 bright,必要时带 comparisonPeriod 看增量;按某个缺陷找产品时才传 dimension=product 和 defect 原字段名。缺陷源字段名、覆盖与对账结果均要尊重工具返回。
|
||||||
- 正式指标引用API;接口返回的阶段数学拆解可用于解释率变化。产品报废增量和报废份额用于确定核查优先级,不擅自变成总体百分点贡献。当前报废大类不是裂纹、崩边等具体现象;设备、班次、工艺等原因要留作待验证假设。
|
- 正式指标引用API;接口返回的阶段数学拆解可用于解释率变化。产品报废增量和报废份额用于确定核查优先级,不擅自变成总体百分点贡献。当前报废大类不是裂纹、崩边等具体现象;设备、班次、工艺等原因要留作待验证假设。
|
||||||
- TOP的占比分母严格沿用shareBasis,不把“所列报废构成合计”改称正式全部报废。未指定stage时的黑亮片重量相加只是跨阶段描述,不能当作独立投入或单一阶段分母;需要判断放量时查对应阶段的投入。具体缺陷源字段聚合与正式大类未对账时要说明差异。
|
- TOP的占比分母严格沿用shareBasis,不把“所列报废构成合计”改称正式全部报废。未指定stage时的黑亮片重量相加只是跨阶段描述,不能当作独立投入或单一阶段分母;需要判断放量时查对应阶段的投入。具体缺陷源字段聚合与正式大类未对账时要说明差异。
|
||||||
- 未对账的来源缺陷即使增量很大,也只能说“来源细分增量集中于该缺陷”,不得说占正式报废增量主体、解释了正式下降或给出正式贡献占比。整体缺陷改善与某个规格恶化可以同时发生,所有“上升/未降/恶化”等句子必须写明阶段、期间及整体或具体规格范围。
|
- 未对账的来源缺陷即使增量很大,也只能说“来源细分增量集中于该缺陷”,不得说占正式报废增量主体、解释了正式下降或给出正式贡献占比。整体缺陷改善与某个规格恶化可以同时发生,所有“上升/未降/恶化”等句子必须写明阶段、期间及整体或具体规格范围。
|
||||||
@@ -32,6 +32,7 @@ releaseId、发布版本号、候选发布状态、Story ID/slug/version 仅作
|
|||||||
整体变化先用简短摘要说清变化方向、主要阶段和优先核查线索,再展开各节。每节先写一到三句解释已确认的现象及实际含义,必要时附一张紧凑数据表,不只连续抄表、不在“重点关注”重复全部数字。阶段数学影响沿用 stageDecomposition 的服务端结果,不能把阶段自身率变化当作对综合率贡献,也不把数学拆解称现场生产根因。亮片报废下降而投入下降更多时,要明确解释合格率仍可能下降。
|
整体变化先用简短摘要说清变化方向、主要阶段和优先核查线索,再展开各节。每节先写一到三句解释已确认的现象及实际含义,必要时附一张紧凑数据表,不只连续抄表、不在“重点关注”重复全部数字。阶段数学影响沿用 stageDecomposition 的服务端结果,不能把阶段自身率变化当作对综合率贡献,也不把数学拆解称现场生产根因。亮片报废下降而投入下降更多时,要明确解释合格率仍可能下降。
|
||||||
|
|
||||||
常规整体分析的重点规格优先结合报废增量、当前规模、率变化和分阶段有效投入确定核查优先级。单按合格率降幅返回的小批量、0率或阶段缺失规格,另列“极端率变化线索”,不能只因降幅大就称整体主要原因;两期分母未查清时不推断停产、退出或全批报废。用户明确只看降幅排名时保留真实排名与批量背景。不得自设未授权的最低批量阈值或忽略小批量的安全/质量异常。
|
常规整体分析的重点规格优先结合报废增量、当前规模、率变化和分阶段有效投入确定核查优先级。单按合格率降幅返回的小批量、0率或阶段缺失规格,另列“极端率变化线索”,不能只因降幅大就称整体主要原因;两期分母未查清时不推断停产、退出或全批报废。用户明确只看降幅排名时保留真实排名与批量背景。不得自设未授权的最低批量阈值或忽略小批量的安全/质量异常。
|
||||||
|
即使这些规格报废绝对重量较小,也不能据此断言其对总体综合率的影响“可忽略”或计算贡献;只能说明报废重量及投入规模,并把总体影响留待正式可加总口径核验。0率原因未核实前,不用“更可能是全批报废/覆盖问题”等概率判断,只写待核对的分母、批次和数据覆盖。没有已确认的批量阈值时,不给规格贴“批量有效/无代表性”的确定性标签,可具体写两期投入重量及其变化。合格率变化一律明确比较期→本期,并写“下降/上升X.XX个百分点”,避免只写带符号的pp。
|
||||||
|
|
||||||
组织、规格和具体缺陷之间的关系只写实际交叉查询已经核对的联系;没有交叉证据时保持各自范围,不把两个独立排名拼成因果链。最后只列能执行的优先核查问题,分清已确认现象与待验证原因,不编造责任人、完成期限或闭环结果。所有图文继续复用同一轮证据;不要为了报告样式重复查询、重新计算核心指标或自动生成故事。
|
组织、规格和具体缺陷之间的关系只写实际交叉查询已经核对的联系;没有交叉证据时保持各自范围,不把两个独立排名拼成因果链。最后只列能执行的优先核查问题,分清已确认现象与待验证原因,不编造责任人、完成期限或闭环结果。所有图文继续复用同一轮证据;不要为了报告样式重复查询、重新计算核心指标或自动生成故事。
|
||||||
|
|
||||||
|
|||||||
@@ -521,6 +521,10 @@ def tool_operation_key(tool: str, raw_input: Any, *, complete_defects: bool = Fa
|
|||||||
value = {"file_path": value["path"]}
|
value = {"file_path": value["path"]}
|
||||||
if tool == "mcp_call" and value.get("tool") == "quality_data":
|
if tool == "mcp_call" and value.get("tool") == "quality_data":
|
||||||
args = value.get("arguments")
|
args = value.get("arguments")
|
||||||
|
if isinstance(args,dict) and args.get("mode") == "defects" and "dimension" not in args and "defect" not in args:
|
||||||
|
# A failed stage defect query missing the required dimension is
|
||||||
|
# recovered only by the otherwise identical dimension=defect retry.
|
||||||
|
args["dimension"] = "defect"
|
||||||
if isinstance(args,dict) and args.get("scope")=="overall" and isinstance(args.get("filters"),dict) and args["filters"].get("group"):
|
if isinstance(args,dict) and args.get("scope")=="overall" and isinstance(args.get("filters"),dict) and args["filters"].get("group"):
|
||||||
# Rejected conflicting scope is recovered only by the successful
|
# Rejected conflicting scope is recovered only by the successful
|
||||||
# same group query after the redundant overall scope is removed.
|
# same group query after the redundant overall scope is removed.
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
"""Regress the real recovered-compare failure without calling a model or changing old records."""
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||||
|
import nao_quality_runtime as runtime
|
||||||
|
|
||||||
|
class ProgressRecoveryTest(unittest.TestCase):
|
||||||
|
def test_known_query_error_reason_is_visible_without_private_headers(self):
|
||||||
|
output={'isError':True,'structuredContent':{'error':{'code':'invalid_or_unavailable','message':'显式 scope 与 filters.group 不能同时指定'}}}
|
||||||
|
self.assertIn('不能同时指定',runtime.public_tool_failure(output))
|
||||||
|
self.assertNotIn('private-secret',runtime.public_tool_failure({'error':{'code':'provider_failure','message':'private-secret'}}))
|
||||||
|
def test_invalid_read_parameter_recovers_only_after_the_same_static_file_succeeds(self):
|
||||||
|
stream=runtime.ConversationAccumulator()
|
||||||
|
stream.feed({'type':'tool-input-error','toolName':'read','toolCallId':'bad-read',
|
||||||
|
'input':{'path':'/agent/mcps/quality/quality_data.json'},'errorText':'An error occurred.'})
|
||||||
|
stream.feed({'type':'tool-output-error','toolCallId':'bad-read','errorText':'An error occurred.'})
|
||||||
|
stream.feed({'type':'tool-input-available','toolName':'read','toolCallId':'rules','input':{'file_path':'/RULES.md'}})
|
||||||
|
stream.feed({'type':'tool-output-available','toolCallId':'rules','output':{'content':'rules'}})
|
||||||
|
self.assertEqual(self.finished(stream),('PARTIAL','mcp_error'))
|
||||||
|
stream.feed({'type':'tool-input-available','toolName':'read','toolCallId':'fixed','input':{'file_path':'/agent/mcps/quality/quality_data.json'}})
|
||||||
|
stream.feed({'type':'tool-output-available','toolCallId':'fixed','output':{'content':'schema'}})
|
||||||
|
self.assertEqual(self.finished(stream),('COMPLETED','stop'))
|
||||||
|
self.assertTrue(stream.tool_calls[0]['recovered'])
|
||||||
|
self.assertEqual(len(stream.tool_calls),3)
|
||||||
|
|
||||||
|
def call(self, stream, call_id, args, failed=False):
|
||||||
|
stream.feed({'type': 'tool-input-available', 'toolName': 'mcp_call', 'toolCallId': call_id,
|
||||||
|
'input': {'server': 'quality', 'tool': 'quality_data', 'arguments': args}})
|
||||||
|
stream.feed({'type': 'tool-output-available', 'toolCallId': call_id,
|
||||||
|
'output': {'isError': failed, 'content': [{'type': 'text', 'text': 'result'}]}})
|
||||||
|
|
||||||
|
def finished(self, stream):
|
||||||
|
stream.feed({'type': 'text-delta', 'id': 'a', 'delta': '结果及数据局限。'})
|
||||||
|
stream.feed({'type': 'finish', 'finishReason': 'stop'})
|
||||||
|
return stream.status()
|
||||||
|
|
||||||
|
def test_corrected_compare_does_not_poison_completed_turn(self):
|
||||||
|
stream = runtime.ConversationAccumulator()
|
||||||
|
args = {'mode': 'compare', 'period': {'year': 2026, 'month': 9}, 'comparisonPeriod': {'year': 2026, 'month': 8}, 'filters': {'group': '工业电机-VCM'}}
|
||||||
|
self.call(stream, 'bad', {**args, 'view': 'overall'}, failed=True)
|
||||||
|
self.call(stream, 'fixed', args)
|
||||||
|
self.assertEqual(self.finished(stream), ('COMPLETED', 'stop'))
|
||||||
|
self.assertEqual(stream.tool_calls[0]['status'], 'failed')
|
||||||
|
self.assertTrue(stream.tool_calls[0]['recovered'])
|
||||||
|
|
||||||
|
def test_missing_defect_dimension_recovers_only_for_same_stage_and_scope(self):
|
||||||
|
base = {'mode':'defects','stage':'black','limit':20,'period':{'year':2026,'month':9},
|
||||||
|
'comparisonPeriod':{'year':2026,'month':8},'filters':{'product':'16.33X15.5X3.75+T'}}
|
||||||
|
stream = runtime.ConversationAccumulator()
|
||||||
|
self.call(stream, 'bad', base, failed=True)
|
||||||
|
self.call(stream, 'unrelated', {**base,'dimension':'defect','stage':'bright'})
|
||||||
|
self.assertEqual(self.finished(stream), ('PARTIAL','mcp_error'))
|
||||||
|
self.call(stream, 'fixed', {**base,'dimension':'defect'})
|
||||||
|
self.assertEqual(self.finished(stream), ('COMPLETED','stop'))
|
||||||
|
self.assertTrue(stream.tool_calls[0]['recovered'])
|
||||||
|
|
||||||
|
def test_corrected_conflicting_overall_scope_requires_same_group_success(self):
|
||||||
|
args={'mode':'changes','dimension':'product','limit':5,'filters':{'group':'汽车交通-国内'},
|
||||||
|
'period':{'year':2026,'month':9},'comparisonPeriod':{'year':2026,'month':8}}
|
||||||
|
stream=runtime.ConversationAccumulator();self.call(stream,'bad',{**args,'scope':'overall'},failed=True)
|
||||||
|
self.call(stream,'other',{**args,'filters':{'group':'汽车交通-海外'}})
|
||||||
|
self.assertEqual(self.finished(stream),('PARTIAL','mcp_error'))
|
||||||
|
self.call(stream,'fixed',args)
|
||||||
|
self.assertEqual(self.finished(stream),('COMPLETED','stop'))
|
||||||
|
|
||||||
|
def test_unrelated_success_does_not_hide_an_unresolved_failure(self):
|
||||||
|
stream = runtime.ConversationAccumulator()
|
||||||
|
self.call(stream, 'bad', {'mode': 'compare', 'period': {'year': 2026, 'month': 9}}, failed=True)
|
||||||
|
self.call(stream, 'different', {'mode': 'query', 'period': {'year': 2026, 'month': 9}})
|
||||||
|
self.assertEqual(self.finished(stream), ('PARTIAL', 'mcp_error'))
|
||||||
|
|
||||||
|
def test_corrected_all_defects_recovers_changed_limit_only_when_all_results_returned(self):
|
||||||
|
args={'mode':'defects','dimension':'defect','stage':'black','limit':100,
|
||||||
|
'period':{'year':2026,'month':9},'filters':{'department':'工业电机产业部'}}
|
||||||
|
for complete in (False,True):
|
||||||
|
stream=runtime.ConversationAccumulator()
|
||||||
|
self.call(stream,'bad',{**args,'defect':'all'},failed=True)
|
||||||
|
stream.feed({'type':'tool-input-available','toolName':'mcp_call','toolCallId':'fixed',
|
||||||
|
'input':{'server':'quality','tool':'quality_data','arguments':{**args,'limit':50}}})
|
||||||
|
stream.feed({'type':'tool-output-available','toolCallId':'fixed','output':{'content':[{'type':'text','text':json.dumps({
|
||||||
|
'kind':'quality_fine_defects','rankingComplete':complete,'truncated':not complete,'pairedTruncated':not complete})}]}})
|
||||||
|
self.assertEqual(self.finished(stream),('COMPLETED','stop') if complete else ('PARTIAL','mcp_error'))
|
||||||
|
|
||||||
|
def test_operation_trace_preserves_query_not_secrets_or_file_contents(self):
|
||||||
|
stream = runtime.ConversationAccumulator()
|
||||||
|
self.call(stream, 'q', {'mode': 'query', 'releaseId': 'internal-release', 'apiKey': 'private-secret',
|
||||||
|
'period': {'year': 2026, 'month': 9}, 'filters': {'product': 'N52', 'token': 'private-secret'}})
|
||||||
|
encoded = json.dumps(stream.tool_calls)
|
||||||
|
self.assertNotIn('private-secret', encoded)
|
||||||
|
self.assertNotIn('internal-release', encoded)
|
||||||
|
self.assertIn('N52', encoded)
|
||||||
|
self.assertIn('startedAt', encoded)
|
||||||
|
self.assertIn('finishedAt', encoded)
|
||||||
|
self.assertNotIn('private prompt', json.dumps(runtime.public_tool_call('read', {'file': 'private prompt'})))
|
||||||
|
|
||||||
|
if __name__ == '__main__': unittest.main()
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useMemo } from 'react';
|
import { useEffect, useMemo, useRef } from 'react';
|
||||||
import { AiMarkdown } from './AiMarkdown';
|
import { AiMarkdown } from './AiMarkdown';
|
||||||
import { AnalysisVisuals } from './AnalysisVisuals';
|
import { AnalysisVisuals } from './AnalysisVisuals';
|
||||||
import { buildAnalysisNarrative, useCompactRateComparison, type NarrativeSection } from './analysisReportModel';
|
import { buildAnalysisNarrative, useCompactRateComparison, type NarrativeSection } from './analysisReportModel';
|
||||||
@@ -28,8 +28,20 @@ export function RateComparisonReadout({ visual }: { visual: AnalysisVisual }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function NarrativeEvidence({ model, prefix }: { model: ReturnType<typeof buildAnalysisNarrative>; prefix: string }) {
|
export function NarrativeEvidence({ model, prefix }: { model: ReturnType<typeof buildAnalysisNarrative>; prefix: string }) {
|
||||||
|
const details = useRef<HTMLDetailsElement>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
const revealLinkedEvidence = () => {
|
||||||
|
const target = window.location.hash.slice(1);
|
||||||
|
if (target.startsWith(prefix) && model.evidence.some(item => `${prefix}${item.ref}` === target) && details.current) {
|
||||||
|
details.current.open = true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
revealLinkedEvidence();
|
||||||
|
window.addEventListener('hashchange', revealLinkedEvidence);
|
||||||
|
return () => window.removeEventListener('hashchange', revealLinkedEvidence);
|
||||||
|
}, [model.evidence, prefix]);
|
||||||
if (!model.evidence.length) return null;
|
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>;
|
return <footer className="analysis-narrative-evidence"><details ref={details}><summary>数据依据</summary><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></details></footer>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 聊天、HTML 和图片报告共用同一套章节与图表关联。 */
|
/** 聊天、HTML 和图片报告共用同一套章节与图表关联。 */
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { parseAnalysisVisuals, renderVisualPng, visualPeriodSummary, visualScopeSummary, visualCategoryLabel } from './analysisVisualsModel';
|
import { parseAnalysisVisuals, combineStageDefectVisuals, renderVisualPng, visualPeriodSummary, visualScopeSummary, visualCategoryLabel } from './analysisVisualsModel';
|
||||||
import { analysisSnapshotResult, authorizeAnalysisSnapshot, reportSnapshotIdentity } from './analysisSnapshot';
|
import { analysisSnapshotResult, authorizeAnalysisSnapshot, reportSnapshotIdentity } from './analysisSnapshot';
|
||||||
import type { AnalysisVisual } from './analysisVisualsModel';
|
import type { AnalysisVisual } from './analysisVisualsModel';
|
||||||
import { useCompactRateComparison } from './analysisReportModel';
|
import { useCompactRateComparison } from './analysisReportModel';
|
||||||
@@ -10,7 +10,7 @@ export type ReportVisualImage = { id: string; png?: string; failed?: boolean };
|
|||||||
|
|
||||||
export function reportVisuals(turn: Row) {
|
export function reportVisuals(turn: Row) {
|
||||||
const result = analysisSnapshotResult(turn);
|
const result = analysisSnapshotResult(turn);
|
||||||
return result.visualSchemaVersion === 1 ? parseAnalysisVisuals(result.visuals, 1).visuals : [];
|
return result.visualSchemaVersion === 1 ? combineStageDefectVisuals(parseAnalysisVisuals(result.visuals, 1).visuals) : [];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useReportVisualImages(turn: Row, open: boolean) {
|
export function useReportVisualImages(turn: Row, open: boolean) {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
isVisualCellInvalid,
|
isVisualCellInvalid,
|
||||||
loadAnalysisVisualECharts,
|
loadAnalysisVisualECharts,
|
||||||
parseAnalysisVisuals,
|
parseAnalysisVisuals,
|
||||||
|
combineStageDefectVisuals,
|
||||||
renderVisualPng,
|
renderVisualPng,
|
||||||
visualCategoryLabel,
|
visualCategoryLabel,
|
||||||
visualPeriodSummary,
|
visualPeriodSummary,
|
||||||
@@ -315,7 +316,10 @@ function AnalysisVisualCard({ visual, beforeExport }: { visual: AnalysisVisual;
|
|||||||
|
|
||||||
/** A bad or old visual payload is confined to this module; it never interrupts the answer text. */
|
/** A bad or old visual payload is confined to this module; it never interrupts the answer text. */
|
||||||
export function AnalysisVisuals({ visuals, visualState, beforeExport, embedded = false }: AnalysisVisualsProps) {
|
export function AnalysisVisuals({ visuals, visualState, beforeExport, embedded = false }: AnalysisVisualsProps) {
|
||||||
const parsed = useMemo(() => parseAnalysisVisuals(visuals), [visuals]);
|
const parsed = useMemo(() => {
|
||||||
|
const result = parseAnalysisVisuals(visuals);
|
||||||
|
return { ...result, visuals: combineStageDefectVisuals(result.visuals) };
|
||||||
|
}, [visuals]);
|
||||||
if (!parsed.visuals.length) {
|
if (!parsed.visuals.length) {
|
||||||
const state = visualStateName(visualState);
|
const state = visualStateName(visualState);
|
||||||
if (state === 'building') return <div className="analysis-visual-state" role="status">图表整理中</div>;
|
if (state === 'building') return <div className="analysis-visual-state" role="status">图表整理中</div>;
|
||||||
|
|||||||
@@ -48,7 +48,8 @@
|
|||||||
.q-report .q-report-contents a:hover,.q-report-detail-link a:hover{text-decoration:underline}
|
.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 .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{padding-top:14px!important;margin-top:22px!important}
|
||||||
.q-report .analysis-narrative-evidence h3{font-size:13px!important;margin:0 0 8px!important}
|
.analysis-narrative-evidence summary{cursor:pointer;font-weight:600;color:var(--muted-ink,#65748b);padding:6px 0}
|
||||||
|
.q-report .analysis-narrative-evidence summary{font-size:13px!important}
|
||||||
.q-report .analysis-rate-grid{grid-template-columns:repeat(2,minmax(0,1fr))}
|
.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-grid:has(>.analysis-rate-readout:only-child){grid-template-columns:1fr}
|
||||||
.q-report .analysis-rate-readout{--surface-subtle:#f4f7fb}
|
.q-report .analysis-rate-readout{--surface-subtle:#f4f7fb}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { sanitizeAnalysisDisplayText } from './analysisDisplayText.ts';
|
import { sanitizeAnalysisDisplayText } from './analysisDisplayText.ts';
|
||||||
import { parseAnalysisVisuals, visualPeriodSummary, visualScopeSummary, type AnalysisVisual } from './analysisVisualsModel.ts';
|
import { parseAnalysisVisuals, combineStageDefectVisuals, visualPeriodSummary, visualScopeSummary, type AnalysisVisual } from './analysisVisualsModel.ts';
|
||||||
|
|
||||||
export type NarrativeKind = 'overview' | 'stage' | 'department' | 'group' | 'product' | 'category' | 'defect' | 'trend' | 'composition' | 'crosscheck' | 'action' | 'other';
|
export type NarrativeKind = 'overview' | 'stage' | 'department' | 'group' | 'product' | 'category' | 'defect' | 'trend' | 'composition' | 'crosscheck' | 'action' | 'other';
|
||||||
export interface NarrativeSection {
|
export interface NarrativeSection {
|
||||||
@@ -119,7 +119,7 @@ function sectionScore(section: NarrativeSection, visual: AnalysisVisual, primary
|
|||||||
|
|
||||||
export function buildAnalysisNarrative(answer: string, rawVisuals: unknown, question = ''): AnalysisNarrativeModel {
|
export function buildAnalysisNarrative(answer: string, rawVisuals: unknown, question = ''): AnalysisNarrativeModel {
|
||||||
const safe = sanitizeAnalysisDisplayText(answer).replaceAll('\r\n', '\n').replaceAll('\r', '\n');
|
const safe = sanitizeAnalysisDisplayText(answer).replaceAll('\r\n', '\n').replaceAll('\r', '\n');
|
||||||
const visuals = parseAnalysisVisuals(rawVisuals).visuals;
|
const visuals = combineStageDefectVisuals(parseAnalysisVisuals(rawVisuals).visuals);
|
||||||
const scopeDepth = (visual: AnalysisVisual) => ['department','group','product','category','defect'].filter(key => visual.scope[key]).length;
|
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 main = [...visuals].filter(visual => visual.metric === 'composite_rate').sort((a,b) => scopeDepth(a)-scopeDepth(b))[0] || visuals[0];
|
||||||
const primaryScope = main?.scope || {};
|
const primaryScope = main?.scope || {};
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import type { EChartsCoreOption } from 'echarts/core';
|
|||||||
|
|
||||||
export type AnalysisVisualUnit = 'ratio' | 'kg' | 'pp' | 'count';
|
export type AnalysisVisualUnit = 'ratio' | 'kg' | 'pp' | 'count';
|
||||||
export type AnalysisVisualStage = 'black' | 'bright';
|
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 AnalysisVisualSectionKey = 'overview' | 'stage' | 'department' | 'group' | 'product' | 'category_black' | 'category_bright' | 'defect_black' | 'defect_bright' | 'defect_combined' | 'trend' | 'composition';
|
||||||
export type AnalysisVisualDimension = 'department' | 'group' | 'product' | 'category' | 'defect';
|
export type AnalysisVisualDimension = 'department' | 'group' | 'product' | 'category' | 'defect';
|
||||||
export type AnalysisVisualContextValue = string | number | boolean | Array<string | number | boolean> | Record<string, string[]>;
|
export type AnalysisVisualContextValue = string | number | boolean | Array<string | number | boolean> | Record<string, string[]>;
|
||||||
export type AnalysisVisualContext = Record<string, AnalysisVisualContextValue>;
|
export type AnalysisVisualContext = Record<string, AnalysisVisualContextValue>;
|
||||||
@@ -63,7 +63,7 @@ export const MAX_VISUAL_SERIES = 4;
|
|||||||
|
|
||||||
const UNIT_VALUES = new Set<AnalysisVisualUnit>(['ratio', 'kg', 'pp', 'count']);
|
const UNIT_VALUES = new Set<AnalysisVisualUnit>(['ratio', 'kg', 'pp', 'count']);
|
||||||
const CHART_TYPES = new Set(['bar', 'line', 'column', 'area', 'heatmap', 'donut', 'pareto', 'waterfall']);
|
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 SECTION_KEYS = new Set<AnalysisVisualSectionKey>(['overview', 'stage', 'department', 'group', 'product', 'category_black', 'category_bright', 'defect_black', 'defect_bright', 'defect_combined', 'trend', 'composition']);
|
||||||
const DIMENSIONS = new Set<AnalysisVisualDimension>(['department', 'group', 'product', 'category', 'defect']);
|
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 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 CATEGORY_KEYS = new Set(['key', 'label']);
|
||||||
@@ -389,6 +389,69 @@ export function parseAnalysisVisuals(input: unknown, schemaVersion?: unknown): P
|
|||||||
return { visuals: result, issues };
|
return { visuals: result, issues };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Combine only comparable, already-validated stage defect views. Saved reports remain unchanged. */
|
||||||
|
export function combineStageDefectVisuals(visuals: AnalysisVisual[]): AnalysisVisual[] {
|
||||||
|
const used = new Set<string>();
|
||||||
|
const comparableScope = (visual: AnalysisVisual) => {
|
||||||
|
const { stage: _stage, ...scope } = visual.scope;
|
||||||
|
return JSON.stringify(Object.entries(scope).sort(([a], [b]) => a.localeCompare(b)));
|
||||||
|
};
|
||||||
|
const canPair = (a: AnalysisVisual, b: AnalysisVisual) =>
|
||||||
|
a.type === 'bar' && b.type === 'bar' && a.unit === 'kg' && b.unit === 'kg'
|
||||||
|
&& a.metric === b.metric && ['source_defect_delta_weight', 'source_defect_weight'].includes(a.metric)
|
||||||
|
&& a.sectionKey === `defect_${a.stage}` && b.sectionKey === `defect_${b.stage}`
|
||||||
|
&& a.stage === 'black' && b.stage === 'bright' && a.chartable && b.chartable
|
||||||
|
&& a.originTurnId === b.originTurnId && comparableScope(a) === comparableScope(b)
|
||||||
|
&& JSON.stringify(a.period) === JSON.stringify(b.period)
|
||||||
|
&& JSON.stringify(a.comparisonPeriod) === JSON.stringify(b.comparisonPeriod);
|
||||||
|
const selectedRows = (visual: AnalysisVisual) => visual.categories
|
||||||
|
.map((category, index) => ({ category, value: visual.series[0]?.values[index] ?? null, index }))
|
||||||
|
.filter(row => row.value !== null && Number.isFinite(row.value) && row.value !== 0)
|
||||||
|
.sort((a, b) => Math.abs(b.value!) - Math.abs(a.value!) || a.index - b.index)
|
||||||
|
.slice(0, 5);
|
||||||
|
const result: AnalysisVisual[] = [];
|
||||||
|
for (const visual of visuals) {
|
||||||
|
if (used.has(visual.id)) continue;
|
||||||
|
const black = visual.stage === 'black' ? visual : visuals.find(candidate => canPair(candidate, visual));
|
||||||
|
const bright = visual.stage === 'bright' ? visual : visuals.find(candidate => black !== undefined && canPair(black, candidate));
|
||||||
|
if (!black || !bright || !canPair(black, bright) || used.has(black.id) || used.has(bright.id)) {
|
||||||
|
result.push(visual);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const rows = [
|
||||||
|
...selectedRows(black).map(row => ({ ...row, stage: 'black' as const })),
|
||||||
|
...selectedRows(bright).map(row => ({ ...row, stage: 'bright' as const })),
|
||||||
|
].sort((a, b) => Math.abs(b.value!) - Math.abs(a.value!) || (a.stage === 'black' ? -1 : 1));
|
||||||
|
if (!rows.some(row => row.stage === 'black') || !rows.some(row => row.stage === 'bright')) {
|
||||||
|
result.push(visual);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const { stage: _stage, ...scope } = black.scope;
|
||||||
|
const delta = black.metric === 'source_defect_delta_weight';
|
||||||
|
const combined = parseAnalysisVisuals([{
|
||||||
|
id: `combined-${black.id}-${bright.id}`, type: 'bar', title: `黑片与亮片来源具体缺陷${delta ? '报废增减' : '报废重量'}`,
|
||||||
|
subtitle: `按缺陷${delta ? '报废重量增减' : '报废重量'}比较,颜色区分阶段;各阶段最多展示${delta ? '变化较大' : '重量较高'}的 5 项。`,
|
||||||
|
unit: 'kg',
|
||||||
|
categories: rows.map(row => ({ key: `${row.stage}:${row.category.key}`, label: `${row.stage === 'black' ? '黑片' : '亮片'} · ${row.category.label}` })),
|
||||||
|
series: [
|
||||||
|
{ key: 'black', label: '黑片', values: rows.map(row => row.stage === 'black' ? row.value : null) },
|
||||||
|
{ key: 'bright', label: '亮片', values: rows.map(row => row.stage === 'bright' ? row.value : null) },
|
||||||
|
],
|
||||||
|
evidenceRefs: [...new Set([...black.evidenceRefs, ...bright.evidenceRefs])],
|
||||||
|
requiredFields: [...new Set([...black.requiredFields, ...bright.requiredFields])],
|
||||||
|
scope, period: black.period, ...(black.comparisonPeriod ? { comparisonPeriod: black.comparisonPeriod } : {}),
|
||||||
|
metric: black.metric, originTurnId: black.originTurnId, sectionKey: 'defect_combined', dimension: 'defect',
|
||||||
|
coverage: { totalRows: black.coverage.totalRows + bright.coverage.totalRows, returnedRows: rows.length,
|
||||||
|
truncated: black.coverage.truncated || bright.coverage.truncated || rows.length < black.coverage.totalRows + bright.coverage.totalRows },
|
||||||
|
note: `具体缺陷按来源字段统计,仅作核查线索;${delta ? '零变化' : '零重量'}项不占图表空间,完整数据保留在原始依据中。`,
|
||||||
|
}], 1).visuals[0];
|
||||||
|
if (!combined) { result.push(visual); continue; }
|
||||||
|
used.add(black.id); used.add(bright.id);
|
||||||
|
result.push(combined);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
export function formatVisualValue(value: number | null, unit: AnalysisVisualUnit): string {
|
export function formatVisualValue(value: number | null, unit: AnalysisVisualUnit): string {
|
||||||
if (value === null) return '—';
|
if (value === null) return '—';
|
||||||
if (!Number.isFinite(value)) return '无效值';
|
if (!Number.isFinite(value)) return '无效值';
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
|
|||||||
import {
|
import {
|
||||||
buildAnalysisVisualOption,
|
buildAnalysisVisualOption,
|
||||||
buildAnalysisVisualExportOption,
|
buildAnalysisVisualExportOption,
|
||||||
|
combineStageDefectVisuals,
|
||||||
formatVisualValue,
|
formatVisualValue,
|
||||||
parseAnalysisVisuals,
|
parseAnalysisVisuals,
|
||||||
renderVisualTableHtml,
|
renderVisualTableHtml,
|
||||||
@@ -93,6 +94,31 @@ test('parser preserves zero and null as different values', () => {
|
|||||||
assert.equal(option.animation, false);
|
assert.equal(option.animation, false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('same-scope black and bright defect changes become one stage-colored chart', () => {
|
||||||
|
const defect = (stage, values, product = '规格 A') => visual({
|
||||||
|
id: `defect-${stage}-${product}`, type: 'bar', title: `${stage}具体缺陷`, subtitle: '来源字段',
|
||||||
|
unit: 'kg', metric: 'source_defect_delta_weight', sectionKey: `defect_${stage}`, dimension: 'defect', stage,
|
||||||
|
scope: { product, stage }, period: { year: 2026, month: 9 }, comparisonPeriod: { year: 2026, month: 8 },
|
||||||
|
categories: values.map((_, index) => ({ key: `field-${index}`, label: `缺陷 ${index}` })),
|
||||||
|
series: [{ key: 'delta', label: '增减', values }], evidenceRefs: [`ref-${stage}`],
|
||||||
|
requiredFields: values.map((_, index) => `field-${index}`),
|
||||||
|
coverage: { totalRows: values.length, returnedRows: values.length, truncated: false },
|
||||||
|
});
|
||||||
|
const [black, bright, other] = parseAnalysisVisuals([
|
||||||
|
defect('black', [265.85, 0, -12]), defect('bright', [123.42, 0, 39.25]), defect('bright', [9], '规格 B'),
|
||||||
|
]).visuals;
|
||||||
|
const combined = combineStageDefectVisuals([black, bright, other]);
|
||||||
|
assert.equal(combined.length, 2);
|
||||||
|
assert.equal(combined[0].sectionKey, 'defect_combined');
|
||||||
|
assert.deepEqual(combined[0].evidenceRefs, ['ref-black', 'ref-bright']);
|
||||||
|
assert.deepEqual(combined[0].categories.map(item => item.label), ['黑片 · 缺陷 0', '亮片 · 缺陷 0', '亮片 · 缺陷 2', '黑片 · 缺陷 2']);
|
||||||
|
assert.deepEqual(combined[0].series[0].values, [265.85, null, null, -12]);
|
||||||
|
assert.deepEqual(combined[0].series[1].values, [null, 123.42, 39.25, null]);
|
||||||
|
assert.equal(combined[0].chartable, true);
|
||||||
|
assert.equal(combined[1].scope.product, '规格 B');
|
||||||
|
assert.equal(combineStageDefectVisuals(combined).length, 2);
|
||||||
|
});
|
||||||
|
|
||||||
test('ratio charts use 0 to 100 percent and convert raw ratios only for plotting', () => {
|
test('ratio charts use 0 to 100 percent and convert raw ratios only for plotting', () => {
|
||||||
const parsed = parseAnalysisVisuals([visual()]);
|
const parsed = parseAnalysisVisuals([visual()]);
|
||||||
const option = buildAnalysisVisualOption(parsed.visuals[0]);
|
const option = buildAnalysisVisualOption(parsed.visuals[0]);
|
||||||
|
|||||||
Reference in New Issue
Block a user