修复:DSH 自主查询、图片直显与报告稳定性
允许 Agent 在循环中查目录、修正查询和提问,保留实时权限检查及模型原始回答。 统一相同查询证据与图表资源;排名补齐阶段指标,修正 OR 重量筛选,并限制模型明细输入。 增加运行恢复、图表自适应坐标轴与两位小数,修复报告主图选择、重复图及边缘标签。 验证:独立副本通过 162 项 Python、73 项前端及 21 项后端测试,前端构建通过。 线上已用原 8 题复测,并追加两轮双期对比;TOP100 与组合筛选分别核对 100 行和 20 行。
This commit is contained in:
+27
-4
@@ -3,11 +3,27 @@ import { tableTextAlignment } from './tableTextAlignment';
|
||||
import { sanitizeAnalysisDisplayText } from './analysisDisplayText';
|
||||
import { analysisEvidenceParts } from './analysisEvidenceRefs';
|
||||
|
||||
function inlineMarkdown(value: string, keyPrefix = 'inline', evidenceLabels?: Record<string, string>, evidencePrefix = ''): ReactNode[] {
|
||||
function inlineMarkdown(value: string, keyPrefix = 'inline', evidenceLabels?: Record<string, string>, evidencePrefix = '', imageTargets?: Record<string, string>, renderImage?: (alt: string, source: string, key: string) => ReactNode): ReactNode[] {
|
||||
const references = (part: string, key: string): ReactNode => !evidenceLabels ? part : analysisEvidenceParts(part).map(({ text, ref }, index) => {
|
||||
return ref && Object.hasOwn(evidenceLabels, ref) ? <a className="analysis-evidence-ref" key={`${key}-${index}`} href={`#${evidencePrefix}${ref}`} title={ref}>{evidenceLabels[ref]}</a> : text;
|
||||
});
|
||||
return value.split(/(\*\*.+?\*\*|`[^`]+`)/g).map((part, index) => {
|
||||
return value.split(/(`[^`]+`|!\[[^\]\n]*\]\([^\n]*?\)|\*\*.+?\*\*)/g).map((part, index) => {
|
||||
const image = part.match(/^!\[([^\]\n]*)\]\(([^\n]*)\)$/);
|
||||
if (image) {
|
||||
const rendered = renderImage?.(image[1], image[2].trim(), `${keyPrefix}-${index}`);
|
||||
if (rendered != null) return rendered;
|
||||
const target = imageTargets?.[image[2].trim()];
|
||||
if (target) return <a key={`${keyPrefix}-${index}`} href={`#${encodeURIComponent(target)}`} onClick={event => {
|
||||
event.preventDefault();
|
||||
const article = event.currentTarget.closest('.agent-turn');
|
||||
const chart = Array.from(article?.querySelectorAll<HTMLElement>('[data-analysis-visual-id]') || []).find(node => node.dataset.analysisVisualId === target);
|
||||
const transcript = article?.closest('.agent-transcript');
|
||||
if (chart && transcript) transcript.scrollTop += chart.getBoundingClientRect().top - transcript.getBoundingClientRect().top - 12;
|
||||
}}>{image[1] || '图表'}</a>;
|
||||
// 图片语法是展示指令,不是业务正文。资源由平台图表组件提供,
|
||||
// 未绑定资源只显示原始标题;不加载模型编造的 URL,也不改写原文。
|
||||
return <span className="ai-markdown-image-caption" role="img" aria-label={image[1] || '图表'} key={`${keyPrefix}-${index}`}>{image[1] || '图表'}</span>;
|
||||
}
|
||||
if (part.startsWith('**') && part.endsWith('**') && part.length >= 4) {
|
||||
return <strong key={`${keyPrefix}-${index}`}>{references(part.slice(2, -2), `${keyPrefix}-${index}`)}</strong>;
|
||||
}
|
||||
@@ -37,6 +53,7 @@ function isBlockStart(lines: string[], index: number): boolean {
|
||||
const line = lines[index];
|
||||
return /^\s*#{1,6}\s+/.test(line)
|
||||
|| /^\s*```/.test(line)
|
||||
|| /^\s*!\[[^\]\n]*\]\([^\n]*?\)\s*$/.test(line)
|
||||
|| isRule(line) || /^\s{0,3}>/.test(line)
|
||||
|| /^\s*(?:[-*+]\s+|\d+[.)]\s+)/.test(line)
|
||||
|| isTableStart(lines, index);
|
||||
@@ -62,8 +79,8 @@ function readingSentences(value: string, boundaries = '。!?;'): string[]
|
||||
}
|
||||
|
||||
/** Renders the small Markdown subset used by analysis answers with React text nodes only. */
|
||||
export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix, layout, preserveSource = false }: { content: string; className?: string; evidenceLabels?: Record<string, string>; evidencePrefix?: string; layout?: 'conclusions' | 'sections'; preserveSource?: boolean }) {
|
||||
const inline = (value: string, key: string) => inlineMarkdown(value, key, evidenceLabels, evidencePrefix);
|
||||
export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix, imageTargets, renderImage, layout, preserveSource = false }: { content: string; className?: string; evidenceLabels?: Record<string, string>; evidencePrefix?: string; imageTargets?: Record<string, string>; renderImage?: (alt: string, source: string, key: string) => ReactNode; layout?: 'conclusions' | 'sections'; preserveSource?: boolean }) {
|
||||
const inline = (value: string, key: string) => inlineMarkdown(value, key, evidenceLabels, evidencePrefix, imageTargets, renderImage);
|
||||
const lines = (preserveSource ? content : sanitizeAnalysisDisplayText(content)).replaceAll('\r\n', '\n').replaceAll('\r', '\n').split('\n');
|
||||
const blocks: ReactNode[] = [];
|
||||
let index = 0;
|
||||
@@ -132,6 +149,12 @@ export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix,
|
||||
continue;
|
||||
}
|
||||
|
||||
if (/^\s*!\[[^\]\n]*\]\([^\n]*?\)\s*$/.test(line)) {
|
||||
blocks.push(<div className="ai-markdown-image-block" key={`image-${blocks.length}`}>{inline(line.trim(), `image-${blocks.length}`)}</div>);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const heading = line.match(/^\s*(#{1,6})\s+(.+?)\s*#*\s*$/);
|
||||
if (heading) {
|
||||
const level = heading[1].length;
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
loadAnalysisVisualECharts,
|
||||
parseAnalysisVisuals,
|
||||
combineStageDefectVisuals,
|
||||
distinctAnalysisVisuals,
|
||||
renderVisualPng,
|
||||
visualCategoryLabel,
|
||||
visualPeriodSummary,
|
||||
@@ -28,6 +29,7 @@ export interface AnalysisVisualsProps {
|
||||
hideEvidence?: boolean;
|
||||
combineStages?: boolean;
|
||||
quiet?: boolean;
|
||||
excludeIds?: string[];
|
||||
}
|
||||
|
||||
interface VisualTableRow {
|
||||
@@ -301,7 +303,7 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna
|
||||
<Button size="small" loading={retrying} onClick={() => void retryChart()}>重试图表</Button>
|
||||
</article>;
|
||||
|
||||
return <article className={`analysis-visual-card analysis-visual-type-${visual.type}`} ref={cardRef} aria-label={visual.title}>
|
||||
return <article className={`analysis-visual-card analysis-visual-type-${visual.type}`} data-analysis-visual-id={visual.id} ref={cardRef} aria-label={visual.title}>
|
||||
<header className="analysis-visual-heading">
|
||||
<div className="analysis-visual-heading-copy">
|
||||
<h3>{visual.title}</h3>
|
||||
@@ -380,7 +382,7 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna
|
||||
}
|
||||
|
||||
/** 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, hideEvidence = false, combineStages = true, quiet = false }: AnalysisVisualsProps) {
|
||||
export function AnalysisVisuals({ visuals, visualState, beforeExport, embedded = false, hideEvidence = false, combineStages = true, quiet = false, excludeIds = [] }: AnalysisVisualsProps) {
|
||||
const parsed = useMemo(() => {
|
||||
const result = parseAnalysisVisuals(visuals);
|
||||
return { ...result, visuals: combineStages ? combineStageDefectVisuals(result.visuals) : result.visuals };
|
||||
@@ -393,7 +395,7 @@ export function AnalysisVisuals({ visuals, visualState, beforeExport, embedded =
|
||||
return null;
|
||||
}
|
||||
return <section className={`analysis-visuals${embedded ? ' is-embedded' : ''}`} aria-label="分析图表">
|
||||
{parsed.visuals.map(visual => <AnalysisVisualCard key={visual.id} visual={visual} beforeExport={beforeExport} hideEvidence={hideEvidence} quiet={quiet} />)}
|
||||
{distinctAnalysisVisuals(parsed.visuals).filter(visual => !excludeIds.includes(visual.id)).map(visual => <AnalysisVisualCard key={visual.id} visual={visual} beforeExport={beforeExport} hideEvidence={hideEvidence} quiet={quiet} />)}
|
||||
</section>;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { memo, useEffect, useMemo, useState } from 'react';
|
||||
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Button } from 'antd';
|
||||
import { ApartmentOutlined, CheckOutlined, ClockCircleOutlined, CloseOutlined, FileTextOutlined, LoadingOutlined, RightOutlined } from '@ant-design/icons';
|
||||
import { AnalysisClarification } from '../AnalysisClarification';
|
||||
@@ -6,6 +6,9 @@ import { AnalysisMemberListPanel } from '../AnalysisMemberList';
|
||||
import { AnalysisVisuals } from '../AnalysisVisuals';
|
||||
import { AnalysisRecordListPanel } from '../AnalysisRecordList';
|
||||
import { AiMarkdown } from '../AiMarkdown';
|
||||
import { analysisChartReferences } from '../analysisChartReferences';
|
||||
import { parseAnalysisVisuals } from '../analysisVisualsModel';
|
||||
import { AgentInlineImage } from './AgentInlineImage';
|
||||
import { AnalysisThinkingBlock } from '../ModelThinkingPanel';
|
||||
import { analysisIsRunning, compactAnalysisTimeline } from '../analysisConversationState';
|
||||
import { orderedAnalysisProcess, type ModelThinking } from '../analysisModelThinking';
|
||||
@@ -130,6 +133,16 @@ export const AgentConversationTurn = memo(function AgentConversationTurn({ turn:
|
||||
const draft = running ? string(turn.dshDraft) : '';
|
||||
const events = useMemo(() => executionEvents(turn), [turn]);
|
||||
const artifact = !running ? authoredReport(turn) : null;
|
||||
const imageTargets = useMemo(() => analysisChartReferences(result.visuals, id), [result.visuals, id]);
|
||||
const inlineVisuals = useMemo(() => parseAnalysisVisuals(result.visuals).visuals, [result.visuals]);
|
||||
const [inlineReady, setInlineReady] = useState<string[]>([]);
|
||||
const onInlineReady = useCallback((visualId: string, ready: boolean) => setInlineReady(previous => ready
|
||||
? previous.includes(visualId) ? previous : [...previous, visualId]
|
||||
: previous.includes(visualId) ? previous.filter(value => value !== visualId) : previous), []);
|
||||
const renderImage = (alt: string, source: string, key: string) => {
|
||||
const visual = inlineVisuals.find(value => value.id === imageTargets[source]);
|
||||
return visual ? <AgentInlineImage key={key} turn={turn} visual={visual} alt={alt} onReady={onInlineReady} /> : undefined;
|
||||
};
|
||||
const [open, setOpen] = useState(running);
|
||||
useEffect(() => { setOpen(running); }, [running, id]);
|
||||
const notice = !answer && !running ? sanitizeAnalysisDisplayText(string(result.message ?? turn.message)
|
||||
@@ -149,10 +162,10 @@ export const AgentConversationTurn = memo(function AgentConversationTurn({ turn:
|
||||
{running && draft && <div className="agent-draft" aria-label="生成中的草稿"><small>草稿 · 正在生成</small><AiMarkdown content={draft} preserveSource /></div>}
|
||||
{!running && status === 'NEEDS_CLARIFICATION' && latest && <AnalysisClarification turn={turn} disabled={!canAct} onContinue={onPrompt} />}
|
||||
{!running && status !== 'NEEDS_CLARIFICATION' && (artifact
|
||||
? <AiMarkdown content={answer} className="agent-model-answer" preserveSource />
|
||||
: answer ? <><AiMarkdown content={answer} className="agent-model-answer" preserveSource />
|
||||
? <AiMarkdown content={answer} className="agent-model-answer" renderImage={renderImage} preserveSource />
|
||||
: answer ? <><AiMarkdown content={answer} className="agent-model-answer" renderImage={renderImage} preserveSource />
|
||||
{result.visualSchemaVersion === 1 && <AnalysisVisuals visuals={result.visuals} visualState={result.visualState}
|
||||
beforeExport={() => authorizeAnalysisSnapshot(turn)} embedded quiet />}</>
|
||||
beforeExport={() => authorizeAnalysisSnapshot(turn)} excludeIds={inlineReady} embedded quiet />}</>
|
||||
: notice ? <p className="agent-turn-notice" role="status">{notice}</p> : null)}
|
||||
{artifact && <button type="button" className="agent-report-open" onClick={() => onReport(id)}><FileTextOutlined />{artifact.title}.html<RightOutlined /></button>}
|
||||
{canRetry && <div className="agent-turn-actions">
|
||||
|
||||
@@ -12,7 +12,7 @@ import { analysisSnapshotResult, reportSnapshotIdentity } from '../analysisSnaps
|
||||
import { analysisScopeText } from '../analysisScope';
|
||||
import documentCss from './agent-document.css?inline';
|
||||
import './agent-document.css';
|
||||
import { buildAgentReportLayout, agentReportPrimary, agentReportSupplementary } from './agentReportLayout';
|
||||
import { buildAgentReportLayout, partitionAgentReportVisuals } from './agentReportLayout';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
|
||||
@@ -59,12 +59,9 @@ export function AgentDeliverable({ turn, onClose }: { turn: Row; onClose: () =>
|
||||
const chartSections = layout.sections.map(section => ({ ...section,
|
||||
figures: section.charts.figures.filter(visual => reportVisualImageSource(imageFor(visual.id))),
|
||||
})).filter(section => section.figures.length);
|
||||
const primary = agentReportPrimary(chartSections.flatMap(section => section.figures), String(turn.question || ''));
|
||||
const { primary, secondary, supplemental } = partitionAgentReportVisuals(chartSections.flatMap(section => section.figures), String(turn.question || ''));
|
||||
const primarySection = chartSections.find(section => section.figures.some(visual => visual.id === primary?.id));
|
||||
const wide = (visual: typeof visuals[number]) => ['bar', 'heatmap', 'pareto'].includes(visual.type);
|
||||
const available = chartSections.flatMap(section => section.figures);
|
||||
const secondary = available.filter(visual => visual.id !== primary?.id && !agentReportSupplementary(visual, available, String(turn.question || '')));
|
||||
const supplemental = available.filter(visual => agentReportSupplementary(visual, available, String(turn.question || '')));
|
||||
const chart = (visual: typeof visuals[number]) => <div key={visual.id} className={wide(visual) ? 'is-wide' : undefined}><ReportVisualFigure visual={visual} image={imageFor(visual.id)} hideEvidence quiet /></div>;
|
||||
const scope = analysisScopeText(turn);
|
||||
const focus = /前后(?:月份|月)|相邻(?:月份|月)/.test(String(turn.question || ''))
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { authorizeAnalysisSnapshot, reportSnapshotIdentity } from '../analysisSnapshot';
|
||||
import { renderVisualSvg, type AnalysisVisual } from '../analysisVisualsModel';
|
||||
|
||||
/** 仅用当前授权快照在本机生成 SVG;不请求模型提供的 URL。 */
|
||||
export function AgentInlineImage({ turn, visual, alt, onReady }: {
|
||||
turn: Record<string, unknown>; visual: AnalysisVisual; alt: string;
|
||||
onReady: (id: string, ready: boolean) => void;
|
||||
}) {
|
||||
const signature = `${reportSnapshotIdentity(turn)}:${visual.id}`;
|
||||
const [image, setImage] = useState({ signature: '', source: '' });
|
||||
const [failed, setFailed] = useState('');
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
onReady(visual.id, false);
|
||||
void (async () => {
|
||||
try {
|
||||
await authorizeAnalysisSnapshot(turn);
|
||||
if (controller.signal.aborted) return;
|
||||
const source = await renderVisualSvg(visual, controller.signal, 'report');
|
||||
if (!controller.signal.aborted) setImage({ signature, source });
|
||||
} catch {
|
||||
if (!controller.signal.aborted) setFailed(signature);
|
||||
}
|
||||
})();
|
||||
return () => controller.abort();
|
||||
}, [signature, onReady]);
|
||||
const source = image.signature === signature && failed !== signature ? image.source : '';
|
||||
return <span className="agent-inline-image" data-inline-visual-id={visual.id} style={{ display: 'block', margin: '16px 0' }}>
|
||||
{source ? <img src={source} alt={alt || visual.title} style={{ display: 'block', width: '100%', height: 'auto' }}
|
||||
onLoad={() => onReady(visual.id, true)}
|
||||
onError={() => { setFailed(signature); onReady(visual.id, false); }} />
|
||||
: <span>{alt || visual.title}</span>}
|
||||
</span>;
|
||||
}
|
||||
@@ -185,6 +185,7 @@ export function agentReportChartWidth(visual: AnalysisVisual, visuals: AnalysisV
|
||||
|
||||
/** Complementary rates and volume traces remain available, without crowding the requested story. */
|
||||
export function agentReportSupplementary(visual: AnalysisVisual, visuals: AnalysisVisual[], question: string): boolean {
|
||||
if (visual.id === agentReportPrimary(visuals, question)?.id) return false;
|
||||
if (/具体缺陷|缺陷\s*(?:top|前)/i.test(question) && !/规格|产品/.test(question) && visual.dimension === 'product') return true;
|
||||
if (/(?:产业部|部门).*top/i.test(question) && !/业务分组/.test(question) && visual.dimension === 'group') return true;
|
||||
if (/报废/.test(question) && !/投入|生产|产量/.test(question) && /total_weight/.test(visual.metric)) return true;
|
||||
@@ -249,3 +250,14 @@ export function buildAgentReportLayout(markdown: string, visuals: AnalysisVisual
|
||||
const aggregate = aggregateMetrics(clean);
|
||||
return { lead, sections, metrics: aggregate.length ? aggregate : comparisonMetrics(visuals) };
|
||||
}
|
||||
|
||||
/** A figure belongs to exactly one report position. */
|
||||
export function partitionAgentReportVisuals(visuals: AnalysisVisual[], question = '') {
|
||||
const unique = [...new Map(visuals.map(visual => [visual.id, visual])).values()];
|
||||
const primary = agentReportPrimary(unique, question);
|
||||
const rest = unique.filter(visual => visual.id !== primary?.id);
|
||||
return { primary,
|
||||
secondary: rest.filter(visual => !agentReportSupplementary(visual, unique, question)),
|
||||
supplemental: rest.filter(visual => agentReportSupplementary(visual, unique, question)),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { parseAnalysisVisuals, distinctAnalysisVisuals } from './analysisVisualsModel.ts';
|
||||
|
||||
/** 只绑定本轮已授权快照中的图表;历史别名仅在唯一趋势图时兼容。 */
|
||||
export function analysisChartReferences(value: unknown, turnId: string): Record<string, string> {
|
||||
const visuals = parseAnalysisVisuals(value).visuals.filter(visual => visual.chartable && visual.originTurnId === turnId);
|
||||
const distinct = distinctAnalysisVisuals(visuals);
|
||||
const targets = Object.fromEntries(visuals.map(visual => [`chart:${visual.id}`,
|
||||
distinct.find(candidate => distinctAnalysisVisuals([candidate, visual]).length === 1)!.id]));
|
||||
const trends = distinct.filter(visual => visual.sectionKey === 'trend' && ['line', 'area'].includes(visual.type));
|
||||
if (trends.length === 1) targets[`chart:quality-trend-${turnId}`] = trends[0].id;
|
||||
return targets;
|
||||
}
|
||||
@@ -2,7 +2,8 @@ import * as echarts from 'echarts/core';
|
||||
import { BarChart, LineChart, PieChart, HeatmapChart } from 'echarts/charts';
|
||||
import { GridComponent, LegendComponent, TooltipComponent, AriaComponent, TitleComponent, GraphicComponent, VisualMapComponent } from 'echarts/components';
|
||||
import { SVGRenderer } from 'echarts/renderers';
|
||||
import { LabelLayout } from 'echarts/features';
|
||||
|
||||
// A single lazy module keeps unused chart families out of the analysis download.
|
||||
echarts.use([BarChart, LineChart, PieChart, HeatmapChart, GridComponent, LegendComponent, TooltipComponent, AriaComponent, TitleComponent, GraphicComponent, VisualMapComponent, SVGRenderer]);
|
||||
echarts.use([BarChart, LineChart, PieChart, HeatmapChart, GridComponent, LegendComponent, TooltipComponent, AriaComponent, TitleComponent, GraphicComponent, VisualMapComponent, SVGRenderer, LabelLayout]);
|
||||
export { echarts };
|
||||
|
||||
@@ -113,6 +113,27 @@ function ratioAxisMax(visual: AnalysisVisual): number | undefined {
|
||||
return Math.ceil((highestPercent + Math.max(10, highestPercent * 0.08)) / 10) * 10;
|
||||
}
|
||||
|
||||
/** 趋势图按所有有效序列统一取范围;柱状/占比图继续保留零基线。 */
|
||||
function trendAxisRange(visual: AnalysisVisual) {
|
||||
if (!['line', 'area'].includes(visual.type)) return {};
|
||||
const values = visual.series.flatMap(series => series.values.flatMap(value => value === null || !Number.isFinite(value) ? [] : [visual.unit === 'ratio' ? value * 100 : value]));
|
||||
if (!values.length) return {};
|
||||
const low = Math.min(...values), high = Math.max(...values);
|
||||
const minimumStep = visual.unit === 'count' ? 1 : 0.01;
|
||||
const span = Math.max(high - low, Math.abs(high) * (high === low ? 0.01 : 0), minimumStep * 4);
|
||||
const rawStep = span / 4;
|
||||
const magnitude = 10 ** Math.floor(Math.log10(rawStep));
|
||||
const interval = Math.max(minimumStep, ([1, 2, 5, 10].find(factor => factor * magnitude >= rawStep) || 10) * magnitude);
|
||||
const round = (value: number) => Number(value.toFixed(8));
|
||||
const min = round(Math.floor((low - interval / 3) / interval) * interval);
|
||||
const max = round(Math.ceil((high + interval / 3) / interval) * interval);
|
||||
return {
|
||||
min: visual.unit === 'ratio' && low >= 0 ? Math.max(0, min) : min,
|
||||
max: visual.unit === 'ratio' && high <= 100 ? Math.min(100, max) : max,
|
||||
interval: round(interval), scale: false,
|
||||
};
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -570,7 +591,7 @@ export function combineStageDefectVisuals(visuals: AnalysisVisual[]): AnalysisVi
|
||||
export function formatVisualValue(value: number | null, unit: AnalysisVisualUnit): string {
|
||||
if (value === null) return '—';
|
||||
if (!Number.isFinite(value)) return '无效值';
|
||||
const numberText = new Intl.NumberFormat('en-US', { useGrouping: false, maximumSignificantDigits: 15 }).format(unit === 'ratio' ? value * 100 : value);
|
||||
const numberText = new Intl.NumberFormat('en-US', { useGrouping: false, minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(unit === 'ratio' ? value * 100 : value);
|
||||
if (unit === 'ratio') return `${numberText}%`;
|
||||
const signedNumber = `${value > 0 && unit === 'pp' ? '+' : ''}${numberText}`;
|
||||
if (unit === 'kg') return `${signedNumber} kg`;
|
||||
@@ -578,6 +599,18 @@ export function formatVisualValue(value: number | null, unit: AnalysisVisualUnit
|
||||
return signedNumber;
|
||||
}
|
||||
|
||||
/** 相同查询的不同证据 ID 不应产生重复图形;不合并不同来源轮次或范围。 */
|
||||
export function distinctAnalysisVisuals(visuals: AnalysisVisual[]): AnalysisVisual[] {
|
||||
const seen = new Set<string>();
|
||||
return visuals.filter(visual => {
|
||||
const { id: _id, evidenceRefs: _refs, ...presentation } = visual;
|
||||
const key = JSON.stringify(presentation);
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function chartNumber(value: number): number {
|
||||
return Number(value.toPrecision(10));
|
||||
}
|
||||
@@ -586,9 +619,7 @@ function formatChartValue(value: number | null, unit: AnalysisVisualUnit, showPo
|
||||
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);
|
||||
const numberText = new Intl.NumberFormat('zh-CN', { useGrouping: false, minimumFractionDigits: 2, maximumFractionDigits: 2 }).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;
|
||||
@@ -650,7 +681,7 @@ export function visualParetoPoints(visual: AnalysisVisual): AnalysisVisualPareto
|
||||
}
|
||||
|
||||
export function visualDonutShareText(share: number): string {
|
||||
return `${(share * 100).toLocaleString('zh-CN', { maximumFractionDigits: 2 })}%`;
|
||||
return `${(share * 100).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}%`;
|
||||
}
|
||||
|
||||
function plainRichText(value: string): string {
|
||||
@@ -669,7 +700,7 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
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)}%`
|
||||
? `${value.toFixed(2)}%`
|
||||
: formatChartValue(value, visual.unit, false);
|
||||
const formatter = (raw: unknown): string => {
|
||||
const params = Array.isArray(raw) ? raw : [raw];
|
||||
@@ -871,7 +902,7 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
xAxis: { type: 'category', data: categories, axisLabel: { color: ink, fontSize: 10, interval: 0, rotate: allScopeWeight ? 0 : categories.length > 3 ? 34 : 0, width: allScopeWeight ? 80 : 160, overflow: 'break', hideOverlap: false, lineHeight: 13, ...(allScopeWeight ? { formatter: (name: string) => wrapAxisLabel(name, 80, 10, 5).join('\n') } : {}) }, 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) => formatChartValue(value, 'kg') }, axisLine: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' } } },
|
||||
{ type: 'value', min: 0, max: 100, position: 'right', name: allScopeWeight ? cumulativeName : '累计占比', nameTextStyle: { color: mutedInk, fontSize: 10 }, axisLabel: { color: mutedInk, formatter: (value: number) => `${chartNumber(value)}%` }, axisLine: { show: false }, splitLine: { show: false } },
|
||||
{ type: 'value', min: 0, max: 100, position: 'right', name: allScopeWeight ? cumulativeName : '累计占比', nameTextStyle: { color: mutedInk, fontSize: 10 }, axisLabel: { color: mutedInk, formatter: (value: number) => `${value.toFixed(2)}%` }, axisLine: { show: false }, splitLine: { show: false } },
|
||||
],
|
||||
series: [
|
||||
{ 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 }) => paretoWeightLabel(points[params.dataIndex]?.valueKg ?? null, allScopeWeight) }, ...(allScopeWeight ? { labelLayout: { hideOverlap: true } } : {}), emphasis: { disabled: true } },
|
||||
@@ -946,7 +977,7 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
return {
|
||||
...shared,
|
||||
xAxis: { type: 'category', data: categories, boundaryGap: false, axisLabel: { ...categoryAxisLabel, rotate: categories.length > 10 ? 25 : 0, width: 120 }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false } },
|
||||
yAxis: valueAxis,
|
||||
yAxis: { ...valueAxis, ...trendAxisRange(visual) },
|
||||
series,
|
||||
};
|
||||
}
|
||||
@@ -1022,12 +1053,11 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
const reportMode = context !== 'standalone';
|
||||
const editorial = context === 'agent-document';
|
||||
const rateTrend = editorial && visual.unit === 'ratio' && ['line', 'area'].includes(visual.type);
|
||||
const values = rateTrend ? visual.series.flatMap(series => series.values.flatMap(value => value == null ? [] : [value * 100])) : [];
|
||||
const low = values.length ? Math.min(...values) : 0;
|
||||
const high = values.length ? Math.max(...values) : 100;
|
||||
const step = [0.1, 0.25, 0.5, 1, 2, 5, 10, 20, 50, 100].find(candidate => candidate * 5 >= high - low) || 100;
|
||||
const trendMin = Math.max(0, Math.floor((low - step / 3) / step) * step);
|
||||
const trendMax = Math.ceil((high + step / 3) / step) * step;
|
||||
const autoTrend = ['line', 'area'].includes(visual.type);
|
||||
const trendRange = trendAxisRange(visual);
|
||||
const trendMin = trendRange.min;
|
||||
const trendMax = trendRange.max;
|
||||
const step = trendRange.interval;
|
||||
const titleLines = reportMode ? [] : wrapLines(visual.title, 34, 3);
|
||||
const headerParts = reportMode ? [] : [
|
||||
visual.subtitle,
|
||||
@@ -1089,7 +1119,7 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
const categories = wrappedCategories.map(lines => lines.join('\n'));
|
||||
const donutShares = visual.type === 'donut' ? visualDonutShares(visual) : [];
|
||||
const valueAxisLabel = (value: number) => visual.unit === 'ratio'
|
||||
? `${chartNumber(value)}%`
|
||||
? `${value.toFixed(2)}%`
|
||||
: formatChartValue(value, visual.unit, false);
|
||||
const allSeriesSelected = Object.fromEntries(visual.series.map(series => [plainRichText(series.label), true]));
|
||||
const legendOption = visual.type === 'donut'
|
||||
@@ -1212,7 +1242,7 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
},
|
||||
yAxis: [
|
||||
{ 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: allScopeWeight ? '累计占全部重量' : '累计占比(本图已列类别)', nameTextStyle: { color: '#65748b', fontSize: 10 }, axisLabel: { color: '#65748b', formatter: (value: number) => `${chartNumber(value)}%` }, axisLine: { show: false }, splitLine: { show: false } },
|
||||
{ type: 'value', min: 0, max: 100, position: 'right', name: allScopeWeight ? '累计占全部重量' : '累计占比(本图已列类别)', nameTextStyle: { color: '#65748b', fontSize: 10 }, axisLabel: { color: '#65748b', formatter: (value: number) => `${value.toFixed(2)}%` }, axisLine: { show: false }, splitLine: { show: false } },
|
||||
],
|
||||
series: [
|
||||
{ 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 }) => paretoWeightLabel(visualParetoPoints(visual)[params.dataIndex]?.valueKg ?? null, allScopeWeight) }, ...(allScopeWeight ? { labelLayout: { hideOverlap: true } } : {}) },
|
||||
@@ -1240,9 +1270,9 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
? {
|
||||
xAxis: {
|
||||
type: 'value',
|
||||
min: rateTrend ? trendMin : visual.unit === 'ratio' ? 0 : undefined,
|
||||
max: rateTrend ? trendMax : ratioAxisMax(visual),
|
||||
interval: rateTrend ? step : undefined,
|
||||
min: autoTrend ? trendMin : visual.unit === 'ratio' ? 0 : undefined,
|
||||
max: autoTrend ? trendMax : ratioAxisMax(visual),
|
||||
interval: autoTrend ? step : undefined,
|
||||
scale: visual.unit !== 'ratio' ? false : undefined,
|
||||
splitNumber: 3,
|
||||
axisLabel: { color: '#65748b', formatter: valueAxisLabel, hideOverlap: true },
|
||||
@@ -1270,9 +1300,9 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
},
|
||||
yAxis: {
|
||||
type: 'value',
|
||||
min: rateTrend ? trendMin : visual.unit === 'ratio' ? 0 : undefined,
|
||||
max: rateTrend ? trendMax : ratioAxisMax(visual),
|
||||
interval: rateTrend ? step : undefined,
|
||||
min: autoTrend ? trendMin : visual.unit === 'ratio' ? 0 : undefined,
|
||||
max: autoTrend ? trendMax : ratioAxisMax(visual),
|
||||
interval: autoTrend ? step : undefined,
|
||||
scale: visual.unit !== 'ratio' ? false : undefined,
|
||||
axisLabel: { color: '#65748b', formatter: valueAxisLabel },
|
||||
axisLine: { show: false },
|
||||
@@ -1287,6 +1317,11 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
};
|
||||
if (rateTrend && visual.series.length === 1) {
|
||||
option.series = ((option.series || []) as any[]).map(series => ({ ...series,
|
||||
labelLayout: ({ dataIndex, rect }: { dataIndex: number; rect: { x: number; width: number } }) => ({
|
||||
hideOverlap: true,
|
||||
...(dataIndex === 0 ? { x: rect.x + rect.width + 3, align: 'left' }
|
||||
: dataIndex === visual.categories.length - 1 ? { x: rect.x - 3, align: 'right' } : {}),
|
||||
}),
|
||||
label: { show: true, position: 'top', color: '#344155', fontSize: 12,
|
||||
formatter: ({ dataIndex }: { dataIndex: number }) => {
|
||||
const value = visual.series[0].values[dataIndex];
|
||||
|
||||
@@ -14,6 +14,32 @@ const Markdown = new Function('React', 'tableTextAlignment', 'sanitizeAnalysisDi
|
||||
ts.transpileModule(`${source}\nreturn AiMarkdown;`, { compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText
|
||||
)(React, tableTextAlignment, sanitizeAnalysisDisplayText, analysisEvidenceParts);
|
||||
|
||||
test('image syntax renders as a chart reference or caption without rewriting source or fetching URLs', () => {
|
||||
const answer = '前文。 后文。\n\n\n\n``';
|
||||
const html = renderToStaticMarkup(React.createElement(Markdown, { content: answer, preserveSource: true, imageTargets: { 'chart:actual-chart': 'actual-chart' } }));
|
||||
assert.match(html, /href="#actual-chart">趋势标题<\/a>/);
|
||||
assert.match(html, /前文。/); assert.match(html, /后文。/);
|
||||
assert.match(html, /ai-markdown-image-caption[^>]*>未绑定标题<\/span>/);
|
||||
assert.match(html, /<code>!\[代码示例\]\(chart:example\)<\/code>/);
|
||||
assert.doesNotMatch(html, /<img|tracker\.png|chart:actual-chart/);
|
||||
assert.ok(answer.includes(''));
|
||||
});
|
||||
|
||||
test('a bound chart image renders in place while surrounding prose and code examples remain intact', () => {
|
||||
const answer = '分析前文。\n\n\n\n分析后文。\n\n```markdown\n\n```';
|
||||
const source = 'data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%2F%3E';
|
||||
const html = renderToStaticMarkup(React.createElement(Markdown, {
|
||||
content: answer, preserveSource: true,
|
||||
renderImage: (alt, target, key) => target === 'chart:verified' ? React.createElement('img', { key, src: source, alt }) : undefined,
|
||||
}));
|
||||
assert.match(html, /<img[^>]+alt="产品趋势"/);
|
||||
assert.equal((html.match(/<img /g) || []).length, 1);
|
||||
assert.ok(html.indexOf('分析前文') < html.indexOf('<img'));
|
||||
assert.ok(html.indexOf('<img') < html.indexOf('分析后文'));
|
||||
assert.match(html, /<pre><code>!\[代码示例\]\(chart:verified\)/);
|
||||
assert.ok(answer.includes(''));
|
||||
});
|
||||
|
||||
test('original answers preserve wording, table headers, headings and escaped markup', () => {
|
||||
const answer = '## 模型原始回答\n\n数学说明保留。\n\n| 月份 | 原始值 |\n| --- | --- |\n| 8月 | 98.35% |\n\n<script>alert(1)</script>';
|
||||
const html = renderToStaticMarkup(React.createElement(Markdown, { content: answer, preserveSource: true }));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { agentReportVisuals, buildAgentReportLayout, agentReportPrimary, agentReportChartWidth, agentReportSupplementary } from '../src/agent/agentReportLayout.ts';
|
||||
import { agentReportVisuals, buildAgentReportLayout, agentReportPrimary, agentReportChartWidth, agentReportSupplementary, partitionAgentReportVisuals } from '../src/agent/agentReportLayout.ts';
|
||||
import { parseAnalysisVisuals } from '../src/analysisVisualsModel.ts';
|
||||
|
||||
const trend = (metric, scope = {}, values = [.9515, .9529, .9546]) => ({
|
||||
@@ -194,3 +194,14 @@ test('an available Top10 snapshot displays the requested Top5 without changing s
|
||||
assert.equal(figures[1].categories.length,4);assert.equal(JSON.stringify([ten,pie]),before);
|
||||
assert.equal(parseAnalysisVisuals([figures[0]],1).visuals[0]?.chartable,true,'the cropped visual must remain renderable by the export parser');
|
||||
});
|
||||
|
||||
test('report primary and supplementary lists cannot render the same image twice', () => {
|
||||
const black = {...trend('black_total_weight'),unit:'kg'};
|
||||
const bright = {...trend('bright_total_weight'),unit:'kg'};
|
||||
const inputs = [black,bright,black];
|
||||
const {primary,secondary,supplemental}=partitionAgentReportVisuals(inputs,'总体质量分析报告,重点展示月度趋势和黑片亮片报废结构');
|
||||
const all=[primary,...secondary,...supplemental].filter(Boolean);
|
||||
assert.equal(all.length,2);
|
||||
assert.equal(new Set(all.map(v=>v.id)).size,2);
|
||||
assert.equal(agentReportSupplementary(primary,inputs,'总体质量分析报告,重点展示月度趋势和黑片亮片报废结构'),false);
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
buildAnalysisVisualExportOption,
|
||||
combineStageDefectVisuals,
|
||||
formatVisualValue,
|
||||
distinctAnalysisVisuals,
|
||||
parseAnalysisVisuals,
|
||||
renderVisualTableHtml,
|
||||
visualCategoryLabel,
|
||||
@@ -16,6 +17,7 @@ import {
|
||||
} from '../src/analysisVisualsModel.ts';
|
||||
import { buildAnalysisNarrative } from '../src/analysisReportModel.ts';
|
||||
import { buildConclusionDocument, checkedConclusionComparison } from '../src/analysisConclusionModel.ts';
|
||||
import { analysisChartReferences } from '../src/analysisChartReferences.ts';
|
||||
|
||||
function visual(overrides = {}) {
|
||||
return {
|
||||
@@ -136,7 +138,7 @@ test('weight ranking export retains the all-scope denominator label and readable
|
||||
assert.deepEqual(report.xAxis.data.map(name=>name.replaceAll('\n','')),names);
|
||||
assert.equal(report.xAxis.axisLabel.rotate,0);
|
||||
assert.ok(report.grid.height>=240);
|
||||
assert.equal(report.series[1].label.formatter({dataIndex:9,data:55}),'55%');
|
||||
assert.equal(report.series[1].label.formatter({dataIndex:9,data:55}),'55.00%');
|
||||
assert.deepEqual(report.series[0].data,input.series[0].values);
|
||||
});
|
||||
|
||||
@@ -189,11 +191,11 @@ test('same-scope black and bright defect changes become one stage-colored chart'
|
||||
assert.equal(combineStageDefectVisuals(combined).length, 2);
|
||||
});
|
||||
|
||||
test('ratio charts use 0 to 100 percent and convert raw ratios only for plotting', () => {
|
||||
test('ratio trends adapt to their data and convert raw ratios only for plotting', () => {
|
||||
const parsed = parseAnalysisVisuals([visual()]);
|
||||
const option = buildAnalysisVisualOption(parsed.visuals[0]);
|
||||
assert.equal(option.yAxis.min, 0);
|
||||
assert.equal(option.yAxis.max, 100);
|
||||
assert.ok(option.yAxis.min < 82 && option.yAxis.min > 80);
|
||||
assert.ok(option.yAxis.max > 84 && option.yAxis.max < 86);
|
||||
assert.deepEqual(option.series[0].data, [82, 84]);
|
||||
assert.equal(formatVisualValue(0.8425, 'ratio'), '84.25%');
|
||||
});
|
||||
@@ -207,15 +209,15 @@ test('stage scrap rates preserve values above 100 percent and expand every ratio
|
||||
assert.ok(buildAnalysisVisualOption(parsed.visuals[0]).yAxis.max > 123);
|
||||
assert.ok(buildAnalysisVisualExportOption(parsed.visuals[0], 1280, 'standalone').option.yAxis.max > 123);
|
||||
assert.ok(buildAnalysisVisualExportOption(parsed.visuals[0], 1280, 'report').option.yAxis.max > 123);
|
||||
assert.equal(formatVisualValue(1.23, 'ratio'), '123%');
|
||||
assert.equal(formatVisualValue(1.23, 'ratio'), '123.00%');
|
||||
}
|
||||
const horizontal = parseAnalysisVisuals([scrapRate('black', [1.23, 0.94], { type: 'bar' })]).visuals[0];
|
||||
assert.ok(buildAnalysisVisualOption(horizontal).xAxis.max > 123);
|
||||
assert.ok(buildAnalysisVisualExportOption(horizontal, 1280, 'report').option.xAxis.max > 123);
|
||||
|
||||
const below100 = parseAnalysisVisuals([scrapRate('black', [0.91, 0.84])]).visuals[0];
|
||||
assert.equal(buildAnalysisVisualOption(below100).yAxis.max, 100);
|
||||
assert.equal(buildAnalysisVisualExportOption(below100, 1280, 'report').option.yAxis.max, 100);
|
||||
assert.ok(buildAnalysisVisualOption(below100).yAxis.max > 91);
|
||||
assert.equal(buildAnalysisVisualExportOption(below100, 1280, 'report').option.yAxis.max, buildAnalysisVisualOption(below100).yAxis.max);
|
||||
});
|
||||
|
||||
test('formal black and composite rates above 100 percent remain visible in live and exported charts', () => {
|
||||
@@ -303,7 +305,7 @@ test('negative percentage point changes remain signed and keep a zero baseline',
|
||||
assert.equal(option.xAxis.scale, false);
|
||||
assert.equal(option.xAxis.max, undefined);
|
||||
assert.equal(formatVisualValue(-2.75, 'pp'), '-2.75 pp');
|
||||
assert.equal(formatVisualValue(0.5, 'pp'), '+0.5 pp');
|
||||
assert.equal(formatVisualValue(0.5, 'pp'), '+0.50 pp');
|
||||
});
|
||||
|
||||
test('legacy rate-drop charts normalize once and chat tables and exports use current minus prior', () => {
|
||||
@@ -339,8 +341,8 @@ test('legacy rate-drop charts normalize once and chat tables and exports use cur
|
||||
const chart = buildAnalysisVisualOption(model);
|
||||
assert.deepEqual(chart.series[0].data, [-2.5, 4]);
|
||||
const table = renderVisualTableHtml(legacy);
|
||||
assert.match(table, /-2\.5 pp/);
|
||||
assert.match(table, /\+4 pp/);
|
||||
assert.match(table, /-2\.50 pp/);
|
||||
assert.match(table, /\+4\.00 pp/);
|
||||
const exported = buildAnalysisVisualExportOption(model, 1280, 'report');
|
||||
assert.deepEqual(exported.option.series[0].data, [-2.5, 4]);
|
||||
|
||||
@@ -577,7 +579,7 @@ test('heatmap omits null cells, plots actual zero, and uses a sign-neutral diver
|
||||
assert.equal(exported.option.xAxis.data[0], '2026-08');
|
||||
const ratio = parseAnalysisVisuals([visual({ type: 'heatmap' })]).visuals[0];
|
||||
const ratioOption = buildAnalysisVisualOption(ratio);
|
||||
assert.match(ratioOption.tooltip.formatter({ data: [1, 0, 84] }), /84%/);
|
||||
assert.match(ratioOption.tooltip.formatter({ data: [1, 0, 84] }), /84\.00%/);
|
||||
assert.doesNotMatch(ratioOption.tooltip.formatter({ data: [1, 0, 84] }), /8400/);
|
||||
});
|
||||
|
||||
@@ -602,20 +604,20 @@ test('donut accepts only a complete official mutually-exclusive category set and
|
||||
const option = buildAnalysisVisualOption(model);
|
||||
assert.equal(option.series[0].type, 'pie');
|
||||
assert.deepEqual(option.series[0].data.map(item => item.value), [0, 2, 8]);
|
||||
assert.match(option.graphic[0].style.text, /10 kg/);
|
||||
assert.match(option.graphic[0].style.text, /10\.00 kg/);
|
||||
assert.match(option.graphic[1].style.text, /不代表正式总报废占比/);
|
||||
assert.match(option.series[0].label.formatter({ dataIndex: 1 }), /20%/);
|
||||
assert.match(option.series[0].label.formatter({ dataIndex: 1 }), /20\.00%/);
|
||||
const table = renderVisualTableHtml(model);
|
||||
assert.match(table, /占比以本图所列类别重量合计为分母/);
|
||||
assert.match(table, /20%/);
|
||||
assert.match(table, /20\.00%/);
|
||||
|
||||
const exported = buildAnalysisVisualExportOption(model);
|
||||
assert.equal(exported.option.series[0].type, 'pie');
|
||||
assert.equal(exported.option.grid, undefined);
|
||||
assert.equal(exported.option.legend.show, true);
|
||||
assert.match(exported.option.title.subtext, /不代表正式总报废占比/);
|
||||
assert.match(exported.option.graphic.elements.map(item => item.style.text || '').join('\n'), /责废:0 kg/);
|
||||
assert.match(exported.option.graphic.elements[0].style.text, /10 kg/);
|
||||
assert.match(exported.option.graphic.elements.map(item => item.style.text || '').join('\n'), /责废:0\.00 kg/);
|
||||
assert.match(exported.option.graphic.elements[0].style.text, /10\.00 kg/);
|
||||
assert.equal(exported.option.series[0].center[0], 640);
|
||||
assert.ok(exported.height > 600);
|
||||
|
||||
@@ -718,9 +720,9 @@ test('Pareto is an official-category dual-axis chart with computed listed-catego
|
||||
const tooltip = option.tooltip.formatter([
|
||||
{ dataIndex: 1, seriesIndex: 0 }, { dataIndex: 1, seriesIndex: 1 },
|
||||
]);
|
||||
assert.match(tooltip, /报废重量:2 kg/);
|
||||
assert.match(tooltip, /本图类别占比:20%/);
|
||||
assert.match(tooltip, /累计占本图已列类别合计:100%/);
|
||||
assert.match(tooltip, /报废重量:2\.00 kg/);
|
||||
assert.match(tooltip, /本图类别占比:20\.00%/);
|
||||
assert.match(tooltip, /累计占本图已列类别合计:100\.00%/);
|
||||
assert.doesNotMatch(tooltip, /正式总报废/);
|
||||
|
||||
const exported = buildAnalysisVisualExportOption(model);
|
||||
@@ -881,7 +883,7 @@ test('declining waterfall total remains negative and hides unused total labels',
|
||||
}
|
||||
});
|
||||
|
||||
test('kg and pp chart labels round to two decimals while tooltips and tables keep source precision', () => {
|
||||
test('kg and pp labels tooltips and tables show two decimals while source data retains 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] }],
|
||||
@@ -890,14 +892,14 @@ test('kg and pp chart labels round to two decimals while tooltips and tables kee
|
||||
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/);
|
||||
assert.match(option.tooltip.formatter([{ dataIndex: 0, seriesIndex: 0 }]), /2\.35 pp/);
|
||||
assert.match(renderVisualTableHtml(model), /2\.35 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/);
|
||||
assert.match(ringOption.tooltip.formatter([{ dataIndex: 0, seriesIndex: 0 }]), /2\.35 kg/);
|
||||
assert.match(renderVisualTableHtml(ring), /2\.35 kg/);
|
||||
});
|
||||
|
||||
test('report export fully wraps long donut, Pareto, and trend category names', () => {
|
||||
@@ -991,15 +993,52 @@ test('scrap-rate data and export unit labels preserve the requested indicator',
|
||||
});
|
||||
|
||||
|
||||
test('low scrap-rate trends use a readable zero-based percentage axis without changing values', () => {
|
||||
test('low scrap-rate trends adapt within their range without changing values', () => {
|
||||
const item = parseAnalysisVisuals([scrapRate('black', [.03657, .02995])]).visuals[0];
|
||||
const option = buildAnalysisVisualOption(item);
|
||||
assert.equal(option.yAxis.min, 0);
|
||||
assert.ok(option.yAxis.min >= 0 && option.yAxis.min < 2.995);
|
||||
assert.ok(option.yAxis.max > 3.657 && option.yAxis.max < 20);
|
||||
assert.deepEqual(item.series[0].values, [.03657, .02995]);
|
||||
assert.equal(buildAnalysisVisualExportOption(item, 1280, 'report').option.yAxis.max, option.yAxis.max);
|
||||
const zero = parseAnalysisVisuals([scrapRate('bright', [0, 0])]).visuals[0];
|
||||
assert.ok(buildAnalysisVisualOption(zero).yAxis.max > 0);
|
||||
const goodRate = parseAnalysisVisuals([visual({ metric: 'black_rate', stage: 'black', requiredFields: ['black_good_weight', 'black_total_weight'], series: [{ key: 'black_rate', label: '黑片合格率', values: [.03657, .02995] }] })]).visuals[0];
|
||||
assert.equal(buildAnalysisVisualOption(goodRate).yAxis.max, 100);
|
||||
assert.ok(buildAnalysisVisualOption(goodRate).yAxis.max > 3.657 && buildAnalysisVisualOption(goodRate).yAxis.max < 5);
|
||||
});
|
||||
|
||||
test('chart references bind only authorized current-turn visuals and never guess among multiple trends', () => {
|
||||
const item = visual({ sectionKey: 'trend' });
|
||||
assert.deepEqual(analysisChartReferences([item], 'turn-1'), { 'chart:visual-1': 'visual-1', 'chart:quality-trend-turn-1': 'visual-1' });
|
||||
assert.deepEqual(analysisChartReferences([item], 'other-turn'), {});
|
||||
const pair = analysisChartReferences([item, { ...item, id: 'second', series: [{ key: 'other', label: '另一指标', values: [.99, .98] }] }], 'turn-1');
|
||||
assert.equal(pair['chart:quality-trend-turn-1'], undefined);
|
||||
assert.equal(pair['chart:second'], 'second');
|
||||
const duplicate = { ...item, id: 'repeated', evidenceRefs: ['another-proof'] };
|
||||
const parsed = parseAnalysisVisuals([item, duplicate]).visuals;
|
||||
assert.equal(distinctAnalysisVisuals(parsed).length, 1);
|
||||
assert.equal(analysisChartReferences([item, duplicate], 'turn-1')['chart:repeated'], 'visual-1');
|
||||
assert.equal(distinctAnalysisVisuals(parseAnalysisVisuals([item, { ...duplicate, scope: { department: '不同产业部' } }]).visuals).length, 2);
|
||||
});
|
||||
|
||||
test('adaptive trends cover every series, preserve missing values, and keep non-trend bars zero based', () => {
|
||||
for (const values of [[.9517, .9670], [.98, .98], [0, 0], [1, 1], [1.24, 1.27], [null, .97]]) {
|
||||
const item = parseAnalysisVisuals([visual({ metric: 'composite_rate', series: [{ key: 'rate', label: '率', values }] })]).visuals[0];
|
||||
const before = JSON.stringify(item.series);
|
||||
const live = buildAnalysisVisualOption(item).yAxis;
|
||||
for (const context of ['standalone', 'report', 'agent-document']) {
|
||||
const exported = buildAnalysisVisualExportOption(item, 1280, context).option.yAxis;
|
||||
assert.equal(exported.min, live.min); assert.equal(exported.max, live.max);
|
||||
}
|
||||
assert.ok(live.max > live.min);
|
||||
for (const value of values.filter(value => value !== null)) assert.ok(live.min <= value * 100 && live.max >= value * 100);
|
||||
assert.equal(JSON.stringify(item.series), before);
|
||||
}
|
||||
const item = parseAnalysisVisuals([visual({ series: [{ key: 'a', label: '甲', values: [.95, null] }, { key: 'b', label: '乙', values: [.99, .98] }] })]).visuals[0];
|
||||
const option = buildAnalysisVisualOption(item);
|
||||
assert.ok(option.yAxis.min <= 95 && option.yAxis.max >= 99);
|
||||
assert.equal(option.yAxis.axisLabel.formatter(96.5), '96.50%');
|
||||
const bar = parseAnalysisVisuals([visual({ type: 'bar' })]).visuals[0];
|
||||
assert.equal(buildAnalysisVisualOption(bar).xAxis.min, 0);
|
||||
assert.equal(formatVisualValue(.9639601707533932, 'ratio'), '96.40%');
|
||||
assert.equal(formatVisualValue(3, 'kg'), '3.00 kg');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user