新增:智能分析图表与报告快照,支持环状图和柏拉图

This commit is contained in:
2026-10-23 20:25:12 +08:00
parent 8684ce1a4d
commit 13695da433
23 changed files with 5252 additions and 57 deletions
+68 -23
View File
@@ -1,9 +1,10 @@
import { useMemo, useRef, useState } from 'react';
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 { analysisDisplayTextRemovalRanges, sanitizeAnalysisDisplayText } from './analysisDisplayText';
import { ReportVisualSections, reportVisualHtml, 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 : {};
@@ -17,11 +18,12 @@ const metricName = (value: unknown) => ({ BLACK_RATE: '黑片合格率', BRIGHT_
const escape = (value: string) => value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;');
const reportCss = `
.q-report{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 .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}}
`;
function ReportDocument({ turn, stamp }: { turn: Row; stamp: string }) {
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);
@@ -43,7 +45,8 @@ function ReportDocument({ turn, stamp }: { turn: Row; stamp: string }) {
<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><div className="q-prose">{answer}</div></section>
<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); } };
@@ -190,30 +193,49 @@ export function AnalysisReportExport({ turn }: { turn: Row }) {
const [open, setOpen] = useState(false);
const [exporting, setExporting] = useState(false);
const [stamp, setStamp] = useState('');
const exportGeneration = useRef(0);
useEffect(() => { exportGeneration.current += 1; setExporting(false); return () => { exportGeneration.current += 1; }; }, [open, turn.id]);
const node = useRef<HTMLDivElement>(null);
const visualReport = useReportVisualImages(turn, open);
const title = String(turn.question || '质量分析报告').replace(/[\\/:*?"<>|\n\r]/g, '').slice(0, 60);
const saveHtml = () => {
const saveHtml = async () => {
if (!node.current) return;
const generation = ++exportGeneration.current;
setExporting(true);
try {
await visualReport.authorize();
if (generation !== exportGeneration.current || !node.current) return;
const html = `<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:"><title>${escape(title)}</title><style>body{margin:0;background:#edf1f5}.q-report{margin:0 auto}</style></head><body>${node.current.innerHTML}</body></html>`;
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 报告已生成');
} catch (error) { if (generation === exportGeneration.current) message.error(error instanceof Error ? error.message : '报告导出失败,请重试。'); }
finally { if (generation === exportGeneration.current) setExporting(false); }
};
const saveImage = async () => {
const report = node.current?.querySelector<HTMLElement>('.q-report');
if (!report) return;
const generation = ++exportGeneration.current;
setExporting(true);
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 });
if (generation !== exportGeneration.current) return;
download(png, `${title}.png`);
message.success('报告图片已生成');
} catch { message.error('图片生成失败,请重试或下载 HTML 报告。'); }
finally { setExporting(false); }
message.success(visualReport.failed ? '报告图片已生成,未能绘制的图表已保留数据表。' : '报告图片已生成');
} catch (error) { if (generation === exportGeneration.current) message.error(error instanceof Error ? error.message : '图片生成失败,请重试或下载 HTML 报告。'); }
finally { if (generation === exportGeneration.current) setExporting(false); }
};
return <>
<Button type="text" size="small" icon={<DownloadOutlined />} onClick={() => { setStamp(new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })); setOpen(true); }}>生成报告</Button>
<Modal title="分析报告" open={open} onCancel={() => { if (!exporting) setOpen(false); }} width={980} footer={<><Button disabled={exporting} onClick={saveHtml}>下载 HTML</Button><Button type="primary" loading={exporting} onClick={() => void saveImage()}>下载图片</Button></>}>
<div className="analysis-report-preview" ref={node}><ReportDocument turn={turn} stamp={stamp} /></div>
<Modal title="分析报告" open={open} onCancel={() => setOpen(false)} width={980} footer={<><Button disabled={exporting || visualReport.loading || !visualReport.authorized} onClick={() => void saveHtml()}>下载 HTML</Button><Button type="primary" loading={exporting} disabled={visualReport.loading || !visualReport.authorized} onClick={() => void saveImage()}>下载图片</Button></>}>
{visualReport.loading && <p role="status">{visualReport.progress || '正在准备报告图表…'}</p>}
{visualReport.failed && <Alert type="warning" showIcon title="部分图表未生成,报告保留相应数据表。" />}
{visualReport.authorizationError && <Alert type="error" showIcon title={visualReport.authorizationError} />}
{visualReport.authorized && <div className="analysis-report-preview" ref={node}><ReportDocument turn={turn} stamp={stamp} visualImages={visualReport.images} /></div>}
</Modal>
</>;
}
@@ -228,20 +250,35 @@ export function NativeAnalysisReport({ turn, reportMarkdown, reportHtml }: {
const [exporting, setExporting] = useState(false);
const [frameHeight, setFrameHeight] = useState(1);
const [frameReady, setFrameReady] = useState(false);
const exportGeneration = useRef(0);
useEffect(() => { exportGeneration.current += 1; setExporting(false); return () => { exportGeneration.current += 1; }; }, [open, turn.id]);
const iframe = useRef<HTMLIFrameElement>(null);
const fallbackNode = useRef<HTMLElement>(null);
const safeHtml = useMemo(() => reportHtml?.trim() ? safeNativeHtml(reportHtml) : '', [reportHtml]);
const visualReport = useReportVisualImages(turn, open);
const safeHtml = useMemo(() => {
const html = reportHtml?.trim() ? safeNativeHtml(reportHtml) : '';
if (!html) return '';
return html.replace(/<\/body>/i, `${reportVisualHtml(turn, visualReport.images)}</body>`);
}, [reportHtml, turn, visualReport.images]);
const title = useMemo(() => {
const nativeTitle = safeHtml ? new DOMParser().parseFromString(safeHtml, 'text/html').title : '';
const heading = reportMarkdown.match(/^#\s+(.+)$/m)?.[1];
return String(nativeTitle || heading || turn.question || '质量分析报告').replace(/[\\/:*?"<>|\n\r]/g, '').slice(0, 60) || '质量分析报告';
}, [safeHtml, reportMarkdown, turn.question]);
const saveHtml = () => {
const saveHtml = async () => {
if (!safeHtml) 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' }));
download(url, `${title}.html`);
setTimeout(() => URL.revokeObjectURL(url), 10000);
message.success(visualReport.failed ? 'HTML 已生成,未能绘制的图表已保留数据表。' : 'HTML 报告已生成');
} catch (error) { if (generation === exportGeneration.current) message.error(error instanceof Error ? error.message : '报告导出失败,请重试。'); }
finally { if (generation === exportGeneration.current) setExporting(false); }
};
const handleFrameLoad = () => {
@@ -256,8 +293,11 @@ export function NativeAnalysisReport({ turn, reportMarkdown, reportHtml }: {
};
const saveImage = async () => {
const generation = ++exportGeneration.current;
setExporting(true);
try {
await visualReport.authorize();
if (generation !== exportGeneration.current) return;
let png: string;
if (safeHtml) {
const doc = iframe.current?.contentDocument;
@@ -265,35 +305,40 @@ export function NativeAnalysisReport({ turn, reportMarkdown, reportHtml }: {
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) });
} 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 });
}
if (generation !== exportGeneration.current) return;
download(png, `${title}.png`);
message.success('报告图片已生成');
} catch {
message.error('图片生成失败,请重试。');
message.success(visualReport.failed ? '报告图片已生成,未能绘制的图表已保留数据表。' : '报告图片已生成');
} catch (error) {
if (generation === exportGeneration.current) message.error(error instanceof Error ? error.message : '图片生成失败,请重试。');
} finally {
setExporting(false);
if (generation === exportGeneration.current) setExporting(false);
}
};
return <>
<Button type="text" size="small" icon={<DownloadOutlined />} onClick={() => setOpen(true)}>查看报告</Button>
<Modal title="分析报告" open={open} onCancel={() => { if (!exporting) setOpen(false); }} width={980} footer={<>
<Button disabled={exporting || !safeHtml} onClick={saveHtml}>下载 HTML</Button>
<Button type="primary" loading={exporting} disabled={Boolean(safeHtml) && !frameReady} onClick={() => void saveImage()}>下载图片</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 type="primary" loading={exporting} disabled={visualReport.loading || !visualReport.authorized || Boolean(safeHtml) && !frameReady} onClick={() => void saveImage()}>下载图片</Button>
</>}>
{!safeHtml && <Alert type="info" showIcon message="未提供原生 HTML" description="当前预览和 PNG 使用 Markdown 报告内容。" />}
<div className="analysis-report-preview">
{visualReport.loading && <p role="status">{visualReport.progress || '正在准备报告图表…'}</p>}
{visualReport.failed && <Alert type="warning" showIcon title="部分图表未生成,报告保留相应数据表。" />}
{visualReport.authorizationError && <Alert type="error" showIcon title={visualReport.authorizationError} />}
{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} /></article>}
</div>
: <article className="native-analysis-report" ref={fallbackNode}><AiMarkdown content={reportMarkdown} /><ReportVisualSections turn={turn} images={visualReport.images} /></article>}
</div>}
</Modal>
</>;
}