同步:完善质量分析工作台并更新主题字体
同步已上线的智能分析执行协议、来源查询、图表报告与管理页面配套代码。 补齐数据库迁移、运行依赖和回归测试,保留原有指标计算口径。 统一午夜黑及其他主题的控件细节、中文和业务数字字体。 排除本地业务数据、凭据、预览、发布与验收产物。 验证:生产构建通过,320项前端回归通过;本轮仅同步Git,不再次部署。
This commit is contained in:
+70
-7
@@ -1,10 +1,10 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { sanitizeAnalysisDisplayText } from './analysisDisplayText';
|
||||
import { analysisEvidenceParts } from './analysisEvidenceRefs';
|
||||
|
||||
function inlineMarkdown(value: string, keyPrefix = 'inline', evidenceLabels?: Record<string, string>, evidencePrefix = ''): ReactNode[] {
|
||||
const references = (part: string, key: string): ReactNode => !evidenceLabels ? part : part.split(/(\[?Q[A-F0-9]{8}\]?)/g).map((token, index) => {
|
||||
const ref = token.replace(/^\[|\]$/g, '');
|
||||
return evidenceLabels[ref] ? <a className="analysis-evidence-ref" key={`${key}-${index}`} href={`#${evidencePrefix}${ref}`} title={ref}>{evidenceLabels[ref]}</a> : token;
|
||||
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) => {
|
||||
if (part.startsWith('**') && part.endsWith('**') && part.length >= 4) {
|
||||
@@ -36,12 +36,64 @@ function isBlockStart(lines: string[], index: number): boolean {
|
||||
|| isTableStart(lines, index);
|
||||
}
|
||||
|
||||
/** Break prose at its own punctuation; never split a number, code or parenthesis. */
|
||||
function readingSentences(value: string, boundaries = '。!?;'): string[] {
|
||||
const parts: string[] = [];
|
||||
let start = 0, depth = 0, code = false, bold = false;
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
const char = value[index];
|
||||
if (char === '`') code = !code;
|
||||
if (code) continue;
|
||||
if (value.slice(index, index + 2) === '**') { bold = !bold; index += 1; continue; }
|
||||
if (bold) continue;
|
||||
if ('(([【'.includes(char)) depth += 1;
|
||||
if ('))]】'.includes(char)) depth = Math.max(0, depth - 1);
|
||||
const nextFinding = boundaries.includes(';') && char === ',' && value.slice(index + 1).trimStart().startsWith('**') && index - start >= 35;
|
||||
if (!depth && (boundaries.includes(char) || nextFinding)) { parts.push(value.slice(start, index + 1).trim()); start = index + 1; }
|
||||
}
|
||||
if (value.slice(start).trim()) parts.push(value.slice(start).trim());
|
||||
return parts.filter(Boolean);
|
||||
}
|
||||
|
||||
/** Renders the small Markdown subset used by analysis answers with React text nodes only. */
|
||||
export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix }: { content: string; className?: string; evidenceLabels?: Record<string, string>; evidencePrefix?: string }) {
|
||||
export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix, layout }: { content: string; className?: string; evidenceLabels?: Record<string, string>; evidencePrefix?: string; layout?: 'conclusions' | 'sections' }) {
|
||||
const inline = (value: string, key: string) => inlineMarkdown(value, key, evidenceLabels, evidencePrefix);
|
||||
const lines = sanitizeAnalysisDisplayText(content).replaceAll('\r\n', '\n').replaceAll('\r', '\n').split('\n');
|
||||
const blocks: ReactNode[] = [];
|
||||
let index = 0;
|
||||
let leadPending = layout === 'conclusions';
|
||||
let tableNote = '';
|
||||
const note = (value: string) => <p className="analysis-conclusion-context" key={`context-${blocks.length}`}>{inline(value, `context-${blocks.length}`)}</p>;
|
||||
const renderReadingParagraph = (value: string) => {
|
||||
let body = value;
|
||||
let followsLead = false;
|
||||
// Some saved, checked answers use a bold paragraph as a section heading.
|
||||
// Promote only explicit heading syntax, never infer a business conclusion.
|
||||
const title = body.match(/^\*\*([^*\n]{1,45})\*\*\s*(?:([((][\s\S]*[))])\s*[::]?\s*$|[::]\s*([\s\S]*)$|$)/);
|
||||
if (title && /[\p{L}]/u.test(title[1])) {
|
||||
blocks.push(<h3 key={`heading-${blocks.length}`}>{inline(title[1], `heading-${blocks.length}`)}</h3>);
|
||||
if (title[2]) {
|
||||
let next = index;
|
||||
while (next < lines.length && !lines[next].trim()) next += 1;
|
||||
if (isTableStart(lines, next)) tableNote = title[2];
|
||||
else blocks.push(note(title[2]));
|
||||
}
|
||||
body = title[3] || '';
|
||||
}
|
||||
if (!body.trim()) return;
|
||||
if (leadPending) {
|
||||
const sentences = readingSentences(body, '。!?');
|
||||
blocks.push(<p className="analysis-conclusion-lead" key={`lead-${blocks.length}`}>{inline(sentences[0], `lead-${blocks.length}`)}</p>);
|
||||
body = sentences.slice(1).join('');
|
||||
leadPending = false;
|
||||
followsLead = true;
|
||||
}
|
||||
if (!body.trim()) return;
|
||||
const sentences = readingSentences(body);
|
||||
if (sentences.length > 1 && (followsLead || body.length > 85)) {
|
||||
blocks.push(<ul className="analysis-conclusion-points" key={`points-${blocks.length}`}>{sentences.map((item, itemIndex) => <li key={itemIndex}>{inline(item, `point-${blocks.length}-${itemIndex}`)}</li>)}</ul>);
|
||||
} else blocks.push(<p key={`paragraph-${blocks.length}`}>{inline(body, `paragraph-${blocks.length}`)}</p>);
|
||||
};
|
||||
|
||||
while (index < lines.length) {
|
||||
const line = lines[index];
|
||||
@@ -49,6 +101,7 @@ export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix
|
||||
|
||||
const fence = line.match(/^\s*```([^`]*)$/);
|
||||
if (fence) {
|
||||
leadPending = false;
|
||||
const code: string[] = [];
|
||||
index += 1;
|
||||
while (index < lines.length && !/^\s*```\s*$/.test(lines[index])) code.push(lines[index++]);
|
||||
@@ -73,19 +126,23 @@ export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix
|
||||
}
|
||||
|
||||
if (isTableStart(lines, index)) {
|
||||
leadPending = false;
|
||||
const headers = tableCells(lines[index]);
|
||||
const hasIndex = headers[0]?.replace(/[*`]/g, '').trim() === '序号';
|
||||
index += 2;
|
||||
const body: string[][] = [];
|
||||
while (index < lines.length && lines[index].trim() && lines[index].includes('|')) body.push(tableCells(lines[index++]));
|
||||
blocks.push(<div className="ai-markdown-table-wrap" key={`table-${blocks.length}`}><table>
|
||||
<thead><tr><th className="ai-markdown-index">序号</th>{headers.map((cell, cellIndex) => <th key={cellIndex}>{inline(cell, `th-${cellIndex}`)}</th>)}</tr></thead>
|
||||
<tbody>{body.map((row, rowIndex) => <tr key={rowIndex}><td className="ai-markdown-index">{rowIndex + 1}</td>{headers.map((_, cellIndex) => <td key={cellIndex}>{inline(row[cellIndex] || '', `td-${rowIndex}-${cellIndex}`)}</td>)}</tr>)}</tbody>
|
||||
<thead><tr>{!hasIndex && <th className="ai-markdown-index">序号</th>}{headers.map((cell, cellIndex) => <th key={cellIndex} className={hasIndex && cellIndex === 0 ? 'ai-markdown-index' : undefined}>{inline(cell, `th-${cellIndex}`)}</th>)}</tr></thead>
|
||||
<tbody>{body.map((row, rowIndex) => <tr key={rowIndex}>{!hasIndex && <td className="ai-markdown-index">{rowIndex + 1}</td>}{headers.map((_, cellIndex) => <td key={cellIndex} className={hasIndex && cellIndex === 0 ? 'ai-markdown-index' : undefined}>{inline(row[cellIndex] || '', `td-${rowIndex}-${cellIndex}`)}</td>)}</tr>)}</tbody>
|
||||
</table></div>);
|
||||
if (tableNote) { blocks.push(note(tableNote)); tableNote = ''; }
|
||||
continue;
|
||||
}
|
||||
|
||||
const listItem = line.match(/^\s*(?:([-*+])\s+|(\d+)[.)]\s+)(.*)$/);
|
||||
if (listItem) {
|
||||
leadPending = false;
|
||||
const ordered = Boolean(listItem[2]);
|
||||
const list: string[] = [];
|
||||
const firstNumber = ordered ? Number(listItem[2]) : undefined;
|
||||
@@ -104,11 +161,17 @@ export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix
|
||||
const paragraph: string[] = [];
|
||||
while (index < lines.length && lines[index].trim() && !isBlockStart(lines, index)) paragraph.push(lines[index++]);
|
||||
if (!paragraph.length) { index += 1; continue; }
|
||||
if (layout) {
|
||||
// The presentation only changes line grouping. Tables, order and all
|
||||
// checked words/values remain intact, including limits and uncertainty.
|
||||
renderReadingParagraph(paragraph.join('\n'));
|
||||
continue;
|
||||
}
|
||||
blocks.push(<p key={`paragraph-${blocks.length}`}>{paragraph.flatMap((part, partIndex) => [
|
||||
...(partIndex ? [<br key={`break-${partIndex}`} />] : []),
|
||||
...inline(part, `paragraph-${blocks.length}-${partIndex}`),
|
||||
])}</p>);
|
||||
}
|
||||
|
||||
return <div className={className ? `ai-markdown ${className}` : 'ai-markdown'}>{blocks}</div>;
|
||||
return <div className={['ai-markdown', className, layout && 'analysis-conclusion-layout'].filter(Boolean).join(' ')}>{blocks}</div>;
|
||||
}
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
import { usePageCache } from './pageCache';
|
||||
import { useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Form, Input, Modal, Select, Spin, Tag } from 'antd';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Form, Input, Modal, Select, Spin, Switch, Tag } from 'antd';
|
||||
import { SettingOutlined } from '@ant-design/icons';
|
||||
import { api } from './api';
|
||||
import { effectiveThinkingEffort, supportsThinkingEffort } from './analysisThinking';
|
||||
|
||||
export type AnalysisModelProfile = { id: string; name: string; baseUrl: string; model: string; hasApiKey: boolean };
|
||||
export type AnalysisModelSettings = { baseUrl: string; model: string; hasApiKey: boolean; revision: string; activeProfileId: string; profiles: AnalysisModelProfile[] };
|
||||
export type AnalysisModelSettingsInput = { baseUrl: string; model: string; apiKey?: string; revision?: string; profileId?: string };
|
||||
export type AnalysisModelProfile = { id: string; name: string; baseUrl: string; model: string; hasApiKey: boolean; thinkingEnabled: boolean; thinkingEffort: string };
|
||||
export type AnalysisModelSettings = { baseUrl: string; model: string; hasApiKey: boolean; revision: string; activeProfileId: string; thinkingEnabled: boolean; thinkingEffort: string; profiles: AnalysisModelProfile[] };
|
||||
export type AnalysisModelSettingsInput = { baseUrl: string; model: string; apiKey?: string; revision?: string; profileId?: string; thinkingEnabled?: boolean; thinkingEffort?: string };
|
||||
|
||||
export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { message } = App.useApp();
|
||||
const [form] = Form.useForm<AnalysisModelSettingsInput>();
|
||||
const { active } = usePageCache();
|
||||
const thinkingEnabled = Form.useWatch('thinkingEnabled', form);
|
||||
const model = Form.useWatch('model', form);
|
||||
const effortSupported = supportsThinkingEffort(model);
|
||||
useEffect(() => { if (!effortSupported) form.setFieldValue('thinkingEffort', 'auto'); }, [effortSupported, form]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
@@ -28,7 +33,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
||||
try {
|
||||
const value = await api.analysisSettings();
|
||||
if (sequence.current !== current) return;
|
||||
setSettings(value); setProfileId(value.activeProfileId); form.setFieldsValue({ baseUrl: value.baseUrl, model: value.model, apiKey: '' });
|
||||
setSettings(value); setProfileId(value.activeProfileId); form.setFieldsValue({ baseUrl: value.baseUrl, model: value.model, apiKey: '', thinkingEnabled: value.thinkingEnabled ?? true, thinkingEffort: effectiveThinkingEffort(value.model, value.thinkingEffort) });
|
||||
} catch (error) {
|
||||
if (sequence.current === current && !onUnauthorized(error)) setNotice({ type: 'error', text: error instanceof Error ? error.message : '读取配置失败' });
|
||||
} finally { if (sequence.current === current) setLoading(false); }
|
||||
@@ -47,7 +52,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
||||
} else {
|
||||
const result = await api.saveAnalysisSettings(body);
|
||||
if (sequence.current !== current) return;
|
||||
setSettings(result); setProfileId(result.activeProfileId); form.setFieldsValue({ baseUrl: result.baseUrl, model: result.model, apiKey: '' });
|
||||
setSettings(result); setProfileId(result.activeProfileId); form.setFieldsValue({ baseUrl: result.baseUrl, model: result.model, apiKey: '', thinkingEnabled: result.thinkingEnabled ?? true, thinkingEffort: effectiveThinkingEffort(result.model, result.thinkingEffort) });
|
||||
setNotice({ type: 'success', text: '已使用此配置,后续新分析将使用它;正在运行的分析继续完成。' }); message.success('API 配置已切换');
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -71,7 +76,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
||||
const profile = settings.profiles.find(item => item.id === id);
|
||||
if (!profile) return;
|
||||
sequence.current += 1; setProfileId(id); setNotice(undefined);
|
||||
form.resetFields(); form.setFieldsValue({ baseUrl: profile.baseUrl, model: profile.model, apiKey: '' });
|
||||
form.resetFields(); form.setFieldsValue({ baseUrl: profile.baseUrl, model: profile.model, apiKey: '', thinkingEnabled: profile.thinkingEnabled ?? true, thinkingEffort: effectiveThinkingEffort(profile.model, profile.thinkingEffort) });
|
||||
}} />
|
||||
<Button disabled={saving || testing || profileId === settings.activeProfileId} loading={saving} onClick={() => void submit(false)}>立即使用</Button>
|
||||
</div>
|
||||
@@ -80,6 +85,8 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
|
||||
<Form.Item name="baseUrl" label="接口地址" rules={[{ required: true, whitespace: true, message: '请填写接口地址' }]} extra="支持 OpenAI 兼容接口,可填写含 /v1 的基础地址或完整的 /chat/completions 地址。"><Input placeholder="https://api.example.com/v1" autoComplete="off" maxLength={2048} /></Form.Item>
|
||||
<Form.Item name="apiKey" label="API Key" extra={selectedProfile?.hasApiKey ? '此配置已保存密钥;留空保留。更换接口地址时需重新填写。' : '密钥仅保存在服务端,保存后不回显。'} rules={selectedProfile?.hasApiKey ? [] : [{ required: true, whitespace: true, message: '请填写 API Key' }]}><Input.Password placeholder={selectedProfile?.hasApiKey ? '已配置,留空保留' : '请输入 API Key'} autoComplete="new-password" maxLength={4096} /></Form.Item>
|
||||
<Form.Item name="model" label="模型名称" rules={[{ required: true, whitespace: true, message: '请填写模型名称' }]}><Input placeholder="例如 qwen3.8-27b-local" autoComplete="off" maxLength={160} /></Form.Item>
|
||||
<Form.Item name="thinkingEnabled" label="思考模式" valuePropName="checked"><Switch checkedChildren="开启" unCheckedChildren="关闭" /></Form.Item>
|
||||
<Form.Item name="thinkingEffort" label="思考强度" extra={!effortSupported ? '该模型暂不区分强度,开启后由模型自动决定。' : undefined}><Select disabled={!thinkingEnabled || !effortSupported || saving || testing} options={effortSupported ? [{value:'auto',label:'模型默认'},{value:'low',label:'低'},{value:'medium',label:'中'},{value:'high',label:'高'}] : [{value:'auto',label:'模型自动'}]} /></Form.Item>
|
||||
</Form>
|
||||
{notice && <Alert showIcon type={notice.type} message={notice.text} />}
|
||||
{!settings && notice && <Button style={{ marginTop: 12 }} onClick={() => void load()}>重新读取</Button>}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Button, Input } from 'antd';
|
||||
import { analysisClarificationRequest, clarificationContinuation } from './analysisClarificationModel';
|
||||
|
||||
export function AnalysisClarification({ turn, disabled = false, onContinue }: {
|
||||
turn: Record<string, unknown>; disabled?: boolean; onContinue: (question: string) => void | Promise<void>;
|
||||
}) {
|
||||
const request = analysisClarificationRequest(turn);
|
||||
const requestKey = JSON.stringify([turn.id, request]);
|
||||
const [selected, setSelected] = useState('');
|
||||
const [supplement, setSupplement] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const pending = useRef(false);
|
||||
useEffect(() => { setSelected(''); setSupplement(''); setSubmitting(false); setError(''); pending.current = false; }, [requestKey]);
|
||||
if (!request) return null;
|
||||
const continuation = clarificationContinuation(request, selected, supplement);
|
||||
const submit = async () => {
|
||||
if (disabled || pending.current || !continuation) return;
|
||||
pending.current = true;
|
||||
setSubmitting(true); setError('');
|
||||
try { await onContinue(continuation); }
|
||||
catch (value) { setError(value instanceof Error ? value.message : '提交未完成,请重试。'); }
|
||||
finally { pending.current = false; setSubmitting(false); }
|
||||
};
|
||||
return <div className="analysis-clarification" aria-label="补充分析条件">
|
||||
<fieldset disabled={disabled || submitting}>
|
||||
<legend>{request.question}</legend>
|
||||
{!!request.options.length && <div className="analysis-clarification-options">{request.options.map((option, index) => <label key={option.value} className={`analysis-clarification-option ${selected === option.value ? 'is-selected' : ''}`}>
|
||||
<input type="radio" name={`clarification-${String(turn.id || 'current')}`} value={option.value} checked={selected === option.value} onChange={() => setSelected(option.value)} />
|
||||
<span><strong>{option.label}</strong>{option.description && <small>{option.description}</small>}</span><span className="analysis-clarification-index" aria-hidden="true">{index + 1}</span>
|
||||
</label>)}</div>}
|
||||
{request.allowCustom && <Input.TextArea value={supplement} onChange={event => setSupplement(event.target.value)} aria-label="补充说明" placeholder={request.options.length ? '也可以补充或修改条件…' : '请补充具体条件…'} autoSize={{ minRows: 2, maxRows: 5 }} maxLength={1200} disabled={disabled || submitting} />}
|
||||
<div className="analysis-clarification-actions"><Button type="primary" disabled={disabled || !continuation || submitting} loading={submitting} onClick={() => void submit()}>确认并继续</Button></div>
|
||||
{error && <p className="analysis-chat-notice" role="alert">{error}</p>}
|
||||
</fieldset>
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
import { buildConclusionDocument } from './analysisConclusionModel';
|
||||
import type { AnalysisReadingSummary } from './analysisReadingModel';
|
||||
import type { AnalysisVisual } from './analysisVisualsModel';
|
||||
|
||||
/** Shared chapter order and formal-value readout for chat and all report formats. */
|
||||
export function AnalysisConclusion({ reading, visuals, renderVisuals }: {
|
||||
reading: AnalysisReadingSummary; visuals: AnalysisVisual[]; renderVisuals: (visuals: AnalysisVisual[]) => ReactNode;
|
||||
}) {
|
||||
const { comparison, sections } = buildConclusionDocument(reading, visuals);
|
||||
return <div className="analysis-conclusion-document">
|
||||
{sections.map((section, index) => <section key={section.id} className="analysis-conclusion-section" data-conclusion-section={section.id}>
|
||||
<h3 className="analysis-conclusion-title">{section.title}</h3>
|
||||
{index === 0 && comparison && <div className="analysis-comparison" aria-label={comparison.original}>
|
||||
<div className="analysis-comparison-name">{comparison.metric}</div>
|
||||
<div className="analysis-comparison-values">
|
||||
<div className="analysis-comparison-previous"><span>{comparison.previousLabel}</span><strong>{comparison.previous}</strong></div>
|
||||
<span className="analysis-comparison-arrow" aria-hidden="true">→</span>
|
||||
<div className="analysis-comparison-current"><span>{comparison.currentLabel}</span><strong>{comparison.current}</strong></div>
|
||||
<div className={`analysis-comparison-change ${/下降|降低/.test(comparison.direction) ? 'is-worse' : 'is-better'}`}><strong>{comparison.direction} {comparison.change}</strong><span>{comparison.unit}</span></div>
|
||||
</div>
|
||||
</div>}
|
||||
{section.markdown && <AiMarkdown className="ai-answer" content={section.markdown} layout="sections" />}
|
||||
{section.note && <p className="analysis-conclusion-context">{section.note}</p>}
|
||||
{!!section.visuals.length && renderVisuals(section.visuals)}
|
||||
</section>)}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Alert, Empty, Pagination, Select, Spin, Tag } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { QualityTable as Table } from './QualityTable';
|
||||
import { authorizeAnalysisSnapshot } from './analysisSnapshot';
|
||||
import {
|
||||
analysisMemberListFullyRead,
|
||||
analysisMemberListPage,
|
||||
analysisMemberListPeriod,
|
||||
authorizedMemberListRead,
|
||||
parseAnalysisMemberList,
|
||||
type AnalysisMemberList,
|
||||
} from './analysisMembersModel';
|
||||
|
||||
type VisibleRow = AnalysisMemberList['rows'][number] & { index: number };
|
||||
type ViewState = { status: 'checking' | 'ready' | 'denied'; page: number; pageSize: number; error: string };
|
||||
|
||||
export function AnalysisMemberListPanel({ turn, value, onUnauthorized }: {
|
||||
turn: Record<string, unknown>;
|
||||
value: unknown;
|
||||
onUnauthorized: (error: unknown) => boolean;
|
||||
}) {
|
||||
const parsed = useMemo(() => parseAnalysisMemberList(value), [value]);
|
||||
const turnRef = useRef(turn);
|
||||
turnRef.current = turn;
|
||||
const requestId = useRef(0);
|
||||
const [view, setView] = useState<ViewState>({ status: 'checking', page: 1, pageSize: 50, error: '' });
|
||||
|
||||
const verify = useCallback(async (page: number, pageSize: number) => {
|
||||
const currentRequest = ++requestId.current;
|
||||
setView({ status: 'checking', page, pageSize, error: '' });
|
||||
if (!parsed) {
|
||||
setView({ status: 'denied', page, pageSize, error: '成员清单格式无效,已隐藏。' });
|
||||
return;
|
||||
}
|
||||
const result = await authorizedMemberListRead(parsed, () => authorizeAnalysisSnapshot(turnRef.current), onUnauthorized);
|
||||
if (currentRequest !== requestId.current) return;
|
||||
setView(result.data
|
||||
? { status: 'ready', page, pageSize, error: '' }
|
||||
: { status: 'denied', page, pageSize, error: result.error });
|
||||
}, [parsed, onUnauthorized]);
|
||||
|
||||
const turnId = String(turn.id || turn.turnId || '');
|
||||
useEffect(() => {
|
||||
void verify(1, 50);
|
||||
return () => { requestId.current += 1; };
|
||||
}, [turnId, verify]);
|
||||
|
||||
if (!parsed) return <Alert className="analysis-member-list-error" type="warning" showIcon message="成员清单格式无效,已隐藏。" />;
|
||||
const page = analysisMemberListPage(parsed, view.page, view.pageSize);
|
||||
const rows: VisibleRow[] = page.rows.map((row, index) => ({ ...row, index: page.offset + index }));
|
||||
const columns: ColumnsType<VisibleRow> = [
|
||||
...parsed.fields.map(field => ({
|
||||
title: field.label,
|
||||
key: field.key,
|
||||
ellipsis: true,
|
||||
render: (_value: unknown, row: VisibleRow) => {
|
||||
const cell = row.values[field.key];
|
||||
return cell === null || cell === undefined || cell === '' ? <span className="muted-dash">—</span> : <span className="analysis-member-cell">{cell}</span>;
|
||||
},
|
||||
})),
|
||||
{
|
||||
title: '阶段', key: 'stages', width: 125,
|
||||
render: (_value, row) => row.stages.length
|
||||
? <span className="analysis-member-stages">{row.stages.map(stage => <Tag key={stage} color={stage === 'black' ? 'default' : 'blue'}>{stage === 'black' ? '黑片' : '亮片'}</Tag>)}</span>
|
||||
: <span className="muted-dash">—</span>,
|
||||
},
|
||||
];
|
||||
const fullyRead = analysisMemberListFullyRead(parsed);
|
||||
const readStatus = fullyRead
|
||||
? `已读取全部 ${parsed.rowsReturned} 条`
|
||||
: parsed.queryComplete
|
||||
? `已读取 ${parsed.rowsReturned} / ${parsed.totalCount} 条`
|
||||
: `读取未完成 · 当前 ${parsed.rowsReturned} / ${parsed.totalCount} 条`;
|
||||
|
||||
return <section className="analysis-member-list" aria-label="成员清单">
|
||||
<div className="analysis-member-list-heading">
|
||||
<strong>成员清单</strong>
|
||||
<span>{analysisMemberListPeriod(parsed.period)} · {readStatus}</span>
|
||||
</div>
|
||||
{view.status === 'checking' ? <div className="analysis-member-list-state"><Spin size="small" />正在复核快照访问权限…</div>
|
||||
: view.status === 'denied' ? <Alert type="warning" showIcon message="成员清单已隐藏" description={view.error} />
|
||||
: <>
|
||||
{parsed.rowsReturned ? <>
|
||||
<div className="analysis-member-list-table">
|
||||
<Table size="small" bordered columns={columns} dataSource={rows} rowKey={row => String(row.index)} pagination={false} indexOffset={page.offset} scroll={{ x: 'max-content' }} />
|
||||
</div>
|
||||
<div className="analysis-member-list-controls">
|
||||
<span>显示 {page.offset + 1}–{page.offset + rows.length} / {parsed.rowsReturned} 条已读取记录</span>
|
||||
<Select aria-label="每页显示数量" value={view.pageSize} options={[20, 50, 100].map(size => ({ label: `${size} 条/页`, value: size }))}
|
||||
onChange={size => void verify(1, size)} />
|
||||
{page.pageCount > 1 && <Pagination current={page.page} pageSize={page.pageSize} total={parsed.rowsReturned} showSizeChanger={false} showQuickJumper={page.pageCount > 10}
|
||||
onChange={nextPage => { if (nextPage !== view.page) void verify(nextPage, view.pageSize); }} />}
|
||||
</div>
|
||||
</> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="没有成员记录" />}
|
||||
</>}
|
||||
</section>;
|
||||
}
|
||||
@@ -1,9 +1,26 @@
|
||||
import { useEffect, useMemo, useRef } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Button } from 'antd';
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
import { AnalysisConclusion } from './AnalysisConclusion';
|
||||
import { AnalysisVisuals } from './AnalysisVisuals';
|
||||
import { buildAnalysisNarrative, useCompactRateComparison, type NarrativeSection } from './analysisReportModel';
|
||||
import { buildAnalysisNarrative, useCompactRateComparison, type FocusProductRow, type NarrativeSection } from './analysisReportModel';
|
||||
import { visualPeriodSummary, visualScopeSummary, type AnalysisVisual } from './analysisVisualsModel';
|
||||
import { AnalysisProductDrilldown, type ProductDrilldownSelection } from './ProductDrilldownDrawer';
|
||||
import { resolveProductDrilldown, type ProductDrilldownView } from './analysisProductDrilldown';
|
||||
import './analysis-narrative.css';
|
||||
import { buildAnalysisReadingModel, type AnalysisReadingSummary } from './analysisReadingModel';
|
||||
|
||||
export function ReadingSummary({ reading, evidenceLabels, evidencePrefix }: {
|
||||
reading: AnalysisReadingSummary; evidenceLabels: Record<string, string>; evidencePrefix: string;
|
||||
}) {
|
||||
const text = (content: string) => <AiMarkdown className="ai-answer" content={content} evidenceLabels={evidenceLabels} evidencePrefix={evidencePrefix} />;
|
||||
return <section className="analysis-reading-summary" aria-label="核心结论">
|
||||
<h3 className="analysis-narrative-title">核心结论</h3>
|
||||
{text(reading.lead)}
|
||||
{!!reading.evidence.length && <div className="analysis-reading-evidence"><h4>关键依据</h4><ul>{reading.evidence.map((item, index) => <li key={index}>{text(item)}</li>)}</ul></div>}
|
||||
{!!reading.notices.length && <div className="analysis-reading-notices" role="note">{reading.notices.map((item, index) => <div key={index}>{text(item)}</div>)}</div>}
|
||||
</section>;
|
||||
}
|
||||
|
||||
function metricName(visual: AnalysisVisual): string {
|
||||
return ({ composite_rate: '综合合格率', black_rate: '黑片合格率', bright_rate: '亮片合格率' } as Record<string, string>)[visual.metric] || visual.series[0].label;
|
||||
@@ -44,21 +61,61 @@ export function NarrativeEvidence({ model, prefix }: { model: ReturnType<typeof
|
||||
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 和图片报告共用同一套章节与图表关联。 */
|
||||
export function AnalysisNarrative({ answer, visuals, visualState, question, turnId, beforeExport }: {
|
||||
answer: string; visuals: unknown; visualState?: unknown; question?: string; turnId?: string; beforeExport?: () => Promise<void>;
|
||||
/** The same cited rows are used in chat and exported reports; no metrics are calculated here. */
|
||||
export function FocusProductTable({ rows, evidenceLabels, evidencePrefix, onDrilldown, drilldownUnavailableReason }: {
|
||||
rows: FocusProductRow[]; evidenceLabels: Record<string, string>; evidencePrefix: string;
|
||||
onDrilldown?: (row: FocusProductRow, view: ProductDrilldownView, trigger: HTMLElement) => void;
|
||||
drilldownUnavailableReason?: (row: FocusProductRow) => string | undefined;
|
||||
}) {
|
||||
const model = useMemo(() => buildAnalysisNarrative(answer, visuals, question), [answer, visuals, question]);
|
||||
if (!rows.length) return null;
|
||||
const table = (items: FocusProductRow[], offset = 0) => <div className="analysis-focus-table-wrap"><table className="analysis-focus-table">
|
||||
<thead><tr><th scope="col" className="is-index">序号</th><th scope="col">产品规格</th><th scope="col" className="is-number">报废增量(kg)</th><th scope="col" className="is-number">合格率变化</th><th scope="col">入选依据</th></tr></thead>
|
||||
<tbody>{items.map((row, index) => <tr key={`${offset + index}-${row.evidenceRefs.join('-')}`}>
|
||||
<td className="is-index">{offset + index + 1}</td><th scope="row" className="analysis-focus-product" title={row.product}>{row.product}{onDrilldown && (drilldownUnavailableReason?.(row)
|
||||
? <span className="analysis-product-unavailable">{drilldownUnavailableReason(row)}</span>
|
||||
: <div className="analysis-product-actions">{(['defects', 'trend', 'records'] as ProductDrilldownView[]).map(view => <Button type="link" size="small" key={view} onClick={event => onDrilldown(row, view, event.currentTarget)}>{({ defects: '看缺陷', trend: '看趋势', records: '看来源明细' })[view]}</Button>)}</div>)}</th>
|
||||
<td className="is-number">{row.scrapDelta}</td><td className={`is-number analysis-focus-rate ${row.rateChange.startsWith('下降') ? 'is-worse' : row.rateChange.startsWith('上升') ? 'is-better' : ''}`}><span>{row.rateLabel}</span>{row.rateChange}</td>
|
||||
<td className="analysis-focus-basis">{row.basis}{row.evidenceRefs.map(ref => <a key={ref} className="analysis-evidence-ref" href={`#${evidencePrefix}${ref}`}>{evidenceLabels[ref] || '数据依据'}</a>)}</td>
|
||||
</tr>)}</tbody>
|
||||
</table></div>;
|
||||
return <div className="analysis-focus-products">
|
||||
{table(rows.slice(0, 5))}
|
||||
{rows.length > 5 && <details className="analysis-narrative-details analysis-focus-more"><summary>其余重点产品({rows.length - 5})</summary>{table(rows.slice(5), 5)}</details>}
|
||||
<details className="analysis-narrative-details analysis-focus-details"><summary>两期投入与阶段数据</summary>{rows.map((row, index) => <AiMarkdown key={index} className="analysis-focus-detail" content={row.detail} evidenceLabels={evidenceLabels} evidencePrefix={evidencePrefix} />)}</details>
|
||||
</div>;
|
||||
}
|
||||
|
||||
/** 聊天、HTML 和图片报告共用同一套章节与图表关联。 */
|
||||
export function AnalysisNarrative({ answer, visuals, visualState, question, turnId, beforeExport, turn }: {
|
||||
answer: string; visuals: unknown; visualState?: unknown; question?: string; turnId?: string; beforeExport?: () => Promise<void>; turn?: Record<string, unknown>;
|
||||
}) {
|
||||
const [drilldown, setDrilldown] = useState<ProductDrilldownSelection | null>(null);
|
||||
const { model, reading, primaryVisuals } = useMemo(() => buildAnalysisReadingModel(answer, visuals, question, turn), [answer, visuals, question, turn]);
|
||||
const appendix = useRef<HTMLDetailsElement>(null);
|
||||
const turnStatus = String(turn?.status || '').toUpperCase();
|
||||
const fallbackVisualState = ['FAILED', 'CANCELLED'].includes(turnStatus) ? undefined : visualState;
|
||||
const prefix = `chat-${String(turnId || 'answer').replace(/[^a-zA-Z0-9_-]/g, '')}-`;
|
||||
const renderText = (content: string) => <AiMarkdown className="ai-answer" content={content} evidenceLabels={model.evidenceLabels} evidencePrefix={prefix} />;
|
||||
const compact = (visual: AnalysisVisual) => useCompactRateComparison(visual, question);
|
||||
useEffect(() => {
|
||||
const reveal = () => {
|
||||
if (model.evidence.some(item => `#${prefix}${item.ref}` === window.location.hash) && appendix.current) appendix.current.open = true;
|
||||
};
|
||||
reveal(); window.addEventListener('hashchange', reveal);
|
||||
return () => window.removeEventListener('hashchange', reveal);
|
||||
}, [model.evidence, prefix]);
|
||||
const primaryIds = new Set(primaryVisuals.map(visual => visual.id));
|
||||
const compact = (visual: AnalysisVisual) => !reading.hasAppendix && useCompactRateComparison(visual, question);
|
||||
const comparisons = model.sections.flatMap(section => section.visuals).filter(compact);
|
||||
const renderSection = (section: NarrativeSection) => {
|
||||
const figures = section.visuals.filter(visual => !compact(visual));
|
||||
const figures = section.visuals.filter(visual => !compact(visual) && !primaryIds.has(visual.id));
|
||||
const hasFigures = figures.some(visual => visual.chartable);
|
||||
const sectionComparisons = section.visuals.filter(compact);
|
||||
if (primaryIds.size > 0 && !section.narrative && !section.tables.length && !section.focusProducts?.length && !figures.length && !sectionComparisons.length) return null;
|
||||
return <section key={section.id} className={`analysis-narrative-section is-${section.kind}`} data-section-kind={section.kind}>
|
||||
{section.title && <h3 className="analysis-narrative-title">{section.title}</h3>}
|
||||
{section.focusProducts && <FocusProductTable rows={section.focusProducts} evidenceLabels={model.evidenceLabels} evidencePrefix={prefix}
|
||||
drilldownUnavailableReason={turn ? row => resolveProductDrilldown(turn, row).reason : undefined}
|
||||
onDrilldown={turn ? (row, view, trigger) => { const resolved = resolveProductDrilldown(turn, row); if (resolved.binding) setDrilldown({ row, view, trigger, binding: resolved.binding }); } : undefined} />}
|
||||
{section.narrative && renderText(section.narrative)}
|
||||
{!!sectionComparisons.length && <div className="analysis-rate-grid">{sectionComparisons.map(visual => <RateComparisonReadout key={visual.id} visual={visual} />)}</div>}
|
||||
{!!figures.length && <AnalysisVisuals visuals={figures} visualState="ready" beforeExport={beforeExport} embedded />}
|
||||
@@ -67,9 +124,13 @@ export function AnalysisNarrative({ answer, visuals, visualState, question, turn
|
||||
: section.tables.map((table, index) => <div key={index}>{renderText(table)}</div>))}
|
||||
</section>;
|
||||
};
|
||||
return <div className={`analysis-narrative ${comparisons.length ? 'has-comparisons' : ''}`}>
|
||||
const fullContent = <>
|
||||
{model.sections.map(renderSection)}
|
||||
{!model.sections.some(section => section.visuals.length) && <AnalysisVisuals visuals={visuals} visualState={visualState} beforeExport={beforeExport} />}
|
||||
{!model.sections.some(section => section.visuals.length) && <AnalysisVisuals visuals={visuals} visualState={fallbackVisualState} beforeExport={beforeExport} />}
|
||||
<NarrativeEvidence model={model} prefix={prefix} />
|
||||
</>;
|
||||
return <div className={`analysis-narrative ${comparisons.length ? 'has-comparisons' : ''}`}>
|
||||
{reading.hasAppendix ? <AnalysisConclusion reading={reading} visuals={primaryVisuals} renderVisuals={figures => <AnalysisVisuals visuals={figures} visualState="ready" beforeExport={beforeExport} embedded hideEvidence combineStages={false} />} /> : fullContent}
|
||||
{turn && drilldown && <AnalysisProductDrilldown turn={turn} selection={drilldown} onClose={() => setDrilldown(null)} />}
|
||||
</div>;
|
||||
}
|
||||
|
||||
+24
-18
@@ -1,12 +1,15 @@
|
||||
import { Spin } from 'antd';
|
||||
import { useEffect, useState, type ReactNode } from 'react';
|
||||
import { CheckCircleOutlined, CloseCircleOutlined, ClockCircleOutlined, RightOutlined } from '@ant-design/icons';
|
||||
import { analysisIsRunning, compactAnalysisTimeline, duplicatesFinalAnalysisAnswer } from './analysisConversationState';
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
import { sanitizeAnalysisDisplayText } from './analysisDisplayText';
|
||||
import { AnalysisThinkingBlock } from './ModelThinkingPanel';
|
||||
import { orderedAnalysisProcess, groupAdjacentThinking, type ModelThinking } from './analysisModelThinking';
|
||||
|
||||
const record = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
const callLabel = (step: Record<string, unknown>) => String(step.label || ({ read: '读取分析资料', mcp_call: '查询质量数据' } as Record<string, string>)[String(step.tool)] || step.tool || '分析步骤');
|
||||
const INPUT_LABELS: Record<string, string> = { mode: '分析方式', scope: '范围', period: '期间', comparisonPeriod: '对比期间', filters: '筛选', view: '汇总维度', stage: '阶段', dimension: '排名维度', defect: '具体缺陷', category: '缺陷大类', limit: '返回数量', sort: '排序', action: '核查步骤', offset: '明细起点', recordFilter: '明细范围', year: '年', month: '月', quarter: '季度', department: '产业部', group: '业务分组', product: '规格', projectGroup: '项目组', includeUnassigned: '包含未分类行' };
|
||||
const INPUT_LABELS: Record<string, string> = { mode: '分析方式', scope: '范围', period: '期间', comparisonPeriod: '对比期间', filters: '筛选', view: '汇总维度', stage: '阶段', dimension: '排名维度', defect: '具体缺陷', category: '缺陷大类', limit: '返回数量', sort: '排序', action: '核查步骤', offset: '明细起点', recordFilter: '明细范围', year: '年', month: '月', quarter: '季度', monthStart: '起始月份', monthEnd: '结束月份', department: '产业部', group: '业务分组', product: '规格', projectGroup: '项目组', includeUnassigned: '包含未分类行' };
|
||||
const INPUT_VALUES: Record<string, string> = { overall: '全公司', auto_combined: '汽车交通合计', auto_domestic: '汽车交通国内', auto_overseas: '汽车交通海外', black: '黑片', bright: '亮片', category: '缺陷大类', defect: '具体缺陷', product: '规格', department: '产业部', group: '业务分组', projectGroup: '项目组', scrap_delta: '报废增量', current_scrap: '当前报废重量', rate_drop: '合格率降幅', catalog: '确认可用数据', query: '指标查询', compare: '期间比较', top: '重点对象排名', changes: '变化对象追查', defects: '具体缺陷分析', details: '来源明细核查', investigate: '全量来源调查', source: '原表核验', rows: '分页明细', fields: '字段字典', overview: '完整范围统计', differences: '全部差额行', unexpectedDifferences: '扣除预期口径后的差额行' };
|
||||
function inputText(input: Record<string, unknown>): string {
|
||||
return Object.entries(input).map(([key, value]) => {
|
||||
@@ -36,7 +39,7 @@ function ToolCall({ entry, running }: { entry: Record<string, unknown>; running:
|
||||
</details>;
|
||||
}
|
||||
|
||||
export function AnalysisProcess({ turn }: { turn: Record<string, unknown> }) {
|
||||
export function AnalysisProcess({ turn, metadata }: { turn: Record<string, unknown>; metadata?: ReactNode }) {
|
||||
const result = record(turn.result);
|
||||
const plan = record(turn.plan || result.plan);
|
||||
const running = analysisIsRunning(turn.status || result.status);
|
||||
@@ -45,20 +48,23 @@ export function AnalysisProcess({ turn }: { turn: Record<string, unknown> }) {
|
||||
const answer = String(result.answer || turn.answer || '');
|
||||
const rawSteps = turn.steps || result.steps || plan.steps;
|
||||
const steps = Array.isArray(rawSteps) ? rawSteps.map(record) : [];
|
||||
if (timeline.length) return <section className="analysis-event-stream" aria-label="实时分析对话">
|
||||
{timeline.map((entry, index) => {
|
||||
const text = sanitizeAnalysisDisplayText(String(entry.text || ''));
|
||||
if (entry.kind === 'assistant' && !text.trim()) return null;
|
||||
// The full final answer is rendered immediately after this stream. Avoid a duplicate.
|
||||
if (!running && index === timeline.length - 1 && entry.kind === 'assistant' && duplicatesFinalAnalysisAnswer(String(entry.text || ''), answer)) return null;
|
||||
if (entry.kind === 'assistant') return <div className="analysis-answer analysis-event-note" key={String(entry.sequence)}><AiMarkdown content={text} className="ai-answer" /></div>;
|
||||
const step = steps.find(item => item.toolCallId && item.toolCallId === entry.toolCallId);
|
||||
return <ToolCall key={String(entry.sequence)} entry={{ ...entry, ...(step?.recovered ? { recovered: true, text: step.outputSummary || '调整调用后已重试成功' } : {}) }} running={running} />;
|
||||
})}
|
||||
</section>;
|
||||
if (!steps.length) return running ? <p className="analysis-chat-notice" role="status">{sanitizeAnalysisDisplayText(String(turn.progressMessage || plan.progressMessage || '正在准备分析…'))}</p> : null;
|
||||
return <section className="analysis-event-stream" aria-label="已保存的分析调用">
|
||||
<p className="analysis-chat-notice">此历史记录仅保存了工具摘要,未记录交错对话事件。</p>
|
||||
{steps.map((step, index) => <ToolCall key={index} entry={step} running={running} />)}
|
||||
</section>;
|
||||
const fallback = steps.map((step, index) => ({ ...step, kind: 'tool', sequence: index, at: step.startedAt, hasResult: ['completed', 'failed'].includes(String(step.status)) }));
|
||||
const events = groupAdjacentThinking(orderedAnalysisProcess(turn, timeline.length ? timeline : fallback));
|
||||
const [open, setOpen] = useState(running);
|
||||
useEffect(() => { setOpen(running); }, [running, turn.id]);
|
||||
const content = events.map(entry => {
|
||||
if (entry.kind === 'thinking') return <AnalysisThinkingBlock key={String(entry.key)} entry={entry as unknown as ModelThinking} running={running} />;
|
||||
const text = sanitizeAnalysisDisplayText(String(entry.text || ''));
|
||||
if (entry.kind === 'assistant') {
|
||||
if (!text.trim() || !running && entry.sequence === timeline.at(-1)?.sequence && timeline.at(-1)?.kind === 'assistant' && duplicatesFinalAnalysisAnswer(text, answer)) return null;
|
||||
return <div className="analysis-answer analysis-event-note" key={String(entry.key)}><AiMarkdown content={text} className="ai-answer" /></div>;
|
||||
}
|
||||
const step = steps.find(item => item.toolCallId && item.toolCallId === entry.toolCallId);
|
||||
return <ToolCall key={String(entry.key)} entry={{ ...entry, ...(step?.recovered ? { recovered: true, text: step.outputSummary || '调整调用后已重试成功' } : {}) }} running={running} />;
|
||||
});
|
||||
if (!events.length) return <>{metadata}{running && <p className="analysis-chat-notice" role="status">{sanitizeAnalysisDisplayText(String(turn.progressMessage || plan.progressMessage || '正在准备分析…'))}</p>}</>;
|
||||
return <details className="analysis-process-history analysis-agent-process" open={open} onToggle={event => setOpen(event.currentTarget.open)}>
|
||||
<summary aria-label={running ? '分析运行信息,展开分析过程' : '分析运行信息,展开已保存过程'}>{metadata || <span>{running ? '分析中' : '已完成'}</span>}<RightOutlined aria-hidden="true" /></summary>
|
||||
<div className="analysis-agent-stream" aria-label={running ? '实时分析对话' : '已保存的分析过程'}>{content}</div>
|
||||
</details>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Alert, Empty, Pagination, Select, Spin } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { QualityTable as Table } from './QualityTable';
|
||||
import { authorizeAnalysisSnapshot, reportSnapshotIdentity } from './analysisSnapshot';
|
||||
import {
|
||||
analysisSourceRecordCompletenessNotice,
|
||||
analysisSourceRecordEmptyState,
|
||||
analysisSourceRecordPage,
|
||||
analysisSourceRecordSetLabel,
|
||||
analysisSourceRecordSetReadStatus,
|
||||
authorizedSourceRecordRead,
|
||||
parseAnalysisSourceRecordList,
|
||||
type AnalysisSourceRecordSet,
|
||||
} from './analysisRecordsModel';
|
||||
|
||||
type VisibleRow = AnalysisSourceRecordSet['rows'][number] & { index: number };
|
||||
type ViewState = {
|
||||
status: 'checking' | 'ready' | 'denied';
|
||||
turnId: string;
|
||||
snapshot: string;
|
||||
setId: string;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
error: string;
|
||||
};
|
||||
|
||||
function display(value: string | number | boolean | null | undefined) {
|
||||
if (value === null || value === undefined || value === '') return <span className="muted-dash">—</span>;
|
||||
return <span className="analysis-record-cell">{String(value)}</span>;
|
||||
}
|
||||
|
||||
function normalizedHeader(value: string) {
|
||||
return value.replace(/[\s\u3000·//::、,,()()_.-]+/g, '').toLocaleLowerCase();
|
||||
}
|
||||
|
||||
function dimensionAlreadySelected(fields: string[], kind: 'product' | 'group') {
|
||||
const aliases = kind === 'product'
|
||||
? ['产品', '产品名称', '产品规格', '品名', 'product', 'productname']
|
||||
: ['组', '分组', '组别', '小组', '业务分组', '项目组', 'group', 'groupname'];
|
||||
const wanted = new Set(aliases.map(normalizedHeader));
|
||||
return fields.some(field => wanted.has(normalizedHeader(field)));
|
||||
}
|
||||
|
||||
function dimensionHasValue(set: AnalysisSourceRecordSet, kind: 'product' | 'group') {
|
||||
return set.rows.some(row => Boolean(row[kind]?.trim()));
|
||||
}
|
||||
|
||||
function visibleSetLabel(set: AnalysisSourceRecordSet) {
|
||||
return analysisSourceRecordSetLabel(set);
|
||||
}
|
||||
|
||||
export function AnalysisRecordListPanel({ turn, value, onUnauthorized }: {
|
||||
turn: Record<string, unknown>;
|
||||
value: unknown;
|
||||
onUnauthorized: (error: unknown) => boolean;
|
||||
}) {
|
||||
const parsed = useMemo(() => parseAnalysisSourceRecordList(value), [value]);
|
||||
const turnId = String(turn.id || turn.turnId || '');
|
||||
const snapshot = useMemo(() => reportSnapshotIdentity(turn), [turn]);
|
||||
const turnRef = useRef(turn);
|
||||
turnRef.current = turn;
|
||||
const parsedRef = useRef(parsed);
|
||||
parsedRef.current = parsed;
|
||||
const unauthorizedRef = useRef(onUnauthorized);
|
||||
unauthorizedRef.current = onUnauthorized;
|
||||
const identityRef = useRef({ turnId, snapshot });
|
||||
identityRef.current = { turnId, snapshot };
|
||||
const requestId = useRef(0);
|
||||
const [selectedSetId, setSelectedSetId] = useState('');
|
||||
const [view, setView] = useState<ViewState>({ status: 'checking', turnId: '', snapshot: '', setId: '', page: 1, pageSize: 50, error: '' });
|
||||
const selectedSet = parsed?.sets.find(set => set.id === selectedSetId) || parsed?.sets[0];
|
||||
const activeSetId = selectedSet?.id || '';
|
||||
|
||||
const verify = useCallback(async (setId: string, page: number, pageSize: number) => {
|
||||
const requestIdentity = identityRef.current;
|
||||
const currentRequest = ++requestId.current;
|
||||
setView({ status: 'checking', turnId: requestIdentity.turnId, snapshot: requestIdentity.snapshot, setId, page, pageSize, error: '' });
|
||||
const currentParsed = parsedRef.current;
|
||||
if (!currentParsed) {
|
||||
setView({ status: 'denied', turnId: requestIdentity.turnId, snapshot: requestIdentity.snapshot, setId, page, pageSize, error: '原始记录格式无效,已隐藏。' });
|
||||
return;
|
||||
}
|
||||
const result = await authorizedSourceRecordRead(currentParsed, () => authorizeAnalysisSnapshot(turnRef.current), error => unauthorizedRef.current(error));
|
||||
if (currentRequest !== requestId.current) return;
|
||||
const currentIdentity = identityRef.current;
|
||||
if (currentIdentity.turnId !== requestIdentity.turnId || currentIdentity.snapshot !== requestIdentity.snapshot) return;
|
||||
setView(result.data
|
||||
? { status: 'ready', turnId: requestIdentity.turnId, snapshot: requestIdentity.snapshot, setId, page, pageSize, error: '' }
|
||||
: { status: 'denied', turnId: requestIdentity.turnId, snapshot: requestIdentity.snapshot, setId, page, pageSize, error: result.error });
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const firstSetId = parsed?.sets[0]?.id || '';
|
||||
setSelectedSetId(firstSetId);
|
||||
void verify(firstSetId, 1, 50);
|
||||
return () => { requestId.current += 1; };
|
||||
}, [turnId, snapshot, verify]);
|
||||
|
||||
if (!parsed) return <Alert className="analysis-record-list-error" type="warning" showIcon message="原始记录格式无效,已隐藏。" />;
|
||||
|
||||
const page = selectedSet ? analysisSourceRecordPage(selectedSet, view.page, view.pageSize) : null;
|
||||
const rows: VisibleRow[] = selectedSet && page
|
||||
? page.rows.map((row, index) => ({ ...row, index: page.offset + index }))
|
||||
: [];
|
||||
const viewMatches = view.turnId === turnId && view.snapshot === snapshot && view.setId === activeSetId
|
||||
&& view.page === (page?.page || 1) && view.pageSize === (page?.pageSize || 50);
|
||||
const viewStatus = viewMatches ? view.status : 'checking';
|
||||
const fields = selectedSet?.fields || [];
|
||||
const columns: ColumnsType<VisibleRow> = [
|
||||
{ title: '来源文件', key: 'sourceFile', width: 190, ellipsis: true, render: (_value, row) => display(row.sourceFile) },
|
||||
{ title: '工作表', key: 'sheet', width: 130, ellipsis: true, render: (_value, row) => display(row.sheet) },
|
||||
{ title: '原始行号', key: 'sourceRowNumber', width: 96, align: 'right', render: (_value, row) => display(row.rowNumber) },
|
||||
...(selectedSet && dimensionHasValue(selectedSet, 'product') && !dimensionAlreadySelected(fields, 'product')
|
||||
? [{ title: '产品', key: 'product', width: 150, ellipsis: true, render: (_value: unknown, row: VisibleRow) => display(row.product) }]
|
||||
: []),
|
||||
...(selectedSet && dimensionHasValue(selectedSet, 'group') && !dimensionAlreadySelected(fields, 'group')
|
||||
? [{ title: '组别', key: 'group', width: 120, ellipsis: true, render: (_value: unknown, row: VisibleRow) => display(row.group) }]
|
||||
: []),
|
||||
...fields.map(field => ({
|
||||
title: field || '未命名字段',
|
||||
key: `field:${field}`,
|
||||
width: 150,
|
||||
ellipsis: true,
|
||||
render: (_value: unknown, row: VisibleRow) => display(row.values[field]),
|
||||
})),
|
||||
];
|
||||
|
||||
return <section className="analysis-member-list analysis-record-list" aria-label="原始记录">
|
||||
<div className="analysis-member-list-heading">
|
||||
<strong>原始记录</strong>
|
||||
<span>{selectedSet
|
||||
? `${visibleSetLabel(selectedSet)} · ${analysisSourceRecordSetReadStatus(selectedSet)}`
|
||||
: parsed.queryComplete ? `已完成查询 · ${parsed.loadedRows} / ${parsed.totalRows} 条` : '查询尚未完成 · 尚未取得总行数'}</span>
|
||||
</div>
|
||||
{analysisSourceRecordCompletenessNotice(parsed) && <p className="analysis-record-list-completeness" role="status">{analysisSourceRecordCompletenessNotice(parsed)}</p>}
|
||||
{parsed.sets.length > 1 && <Select aria-label="记录集" value={activeSetId} options={parsed.sets.map(set => ({ value: set.id, label: visibleSetLabel(set) }))}
|
||||
onChange={setId => { setSelectedSetId(setId); void verify(setId, 1, view.pageSize); }} />}
|
||||
{viewStatus === 'checking' ? <div className="analysis-member-list-state"><Spin size="small" />正在复核快照访问权限…</div>
|
||||
: viewStatus === 'denied' ? <Alert type="warning" showIcon message="原始记录已隐藏" description={view.error} />
|
||||
: selectedSet && selectedSet.loadedRows > 0 && page ? <>
|
||||
<div className="analysis-member-list-table">
|
||||
<Table size="small" bordered columns={columns} dataSource={rows} rowKey={row => String(row.index)} pagination={false}
|
||||
indexOffset={page.offset} scroll={{ x: 'max-content', y: 420 }} />
|
||||
</div>
|
||||
<div className="analysis-member-list-controls">
|
||||
<span>显示 {page.offset + 1}–{page.offset + rows.length} / {selectedSet.loadedRows} 条已读取记录</span>
|
||||
<Select aria-label="每页显示数量" value={viewMatches ? view.pageSize : 50} options={[20, 50, 100].map(size => ({ label: `${size} 条/页`, value: size }))}
|
||||
onChange={size => void verify(activeSetId, 1, size)} />
|
||||
{page.pageCount > 1 && <Pagination current={page.page} pageSize={page.pageSize} total={selectedSet.loadedRows} showSizeChanger={false} showQuickJumper={page.pageCount > 10}
|
||||
onChange={nextPage => { if (nextPage !== view.page) void verify(activeSetId, nextPage, view.pageSize); }} />}
|
||||
</div>
|
||||
</> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={analysisSourceRecordEmptyState(parsed, selectedSet)} />}
|
||||
</section>;
|
||||
}
|
||||
|
||||
export function AnalysisRecordListReport({ value }: { value: unknown }) {
|
||||
const recordList = parseAnalysisSourceRecordList(value);
|
||||
if (!recordList) return null;
|
||||
return <section className="q-source-record-list">
|
||||
<h2>原始记录</h2>
|
||||
<p className="q-note">{recordList.queryComplete ? `已读取全部 ${recordList.loadedRows} / ${recordList.totalRows} 条` : `读取未完成 ${recordList.loadedRows} / ${recordList.totalRows} 条`}</p>
|
||||
{recordList.sets.map(set => <section className="q-source-record-set" key={set.id}>
|
||||
<h3>{visibleSetLabel(set)}</h3>
|
||||
<p className="q-note">{analysisSourceRecordSetReadStatus(set)}</p>
|
||||
{set.rows.length ? <table><thead><tr><th>序号</th><th>来源文件</th><th>工作表</th><th>原始行号</th>
|
||||
{dimensionHasValue(set, 'product') && !dimensionAlreadySelected(set.fields, 'product') && <th>产品</th>}
|
||||
{dimensionHasValue(set, 'group') && !dimensionAlreadySelected(set.fields, 'group') && <th>组别</th>}
|
||||
{set.fields.map(field => <th key={field}>{field || '未命名字段'}</th>)}
|
||||
</tr></thead><tbody>{set.rows.map((row, index) => <tr key={`${set.id}:${index}`}>
|
||||
<td>{index + 1}</td><td>{row.sourceFile}</td><td>{row.sheet}</td><td>{row.rowNumber}</td>
|
||||
{dimensionHasValue(set, 'product') && !dimensionAlreadySelected(set.fields, 'product') && <td>{row.product || '—'}</td>}
|
||||
{dimensionHasValue(set, 'group') && !dimensionAlreadySelected(set.fields, 'group') && <td>{row.group || '—'}</td>}
|
||||
{set.fields.map(field => <td key={field}>{formatRecordValue(row.values[field])}</td>)}
|
||||
</tr>)}</tbody></table> : <p className="q-note">{analysisSourceRecordEmptyState(recordList, set)}</p>}
|
||||
</section>)}
|
||||
{recordList.sets.length === 0 && <p className="q-note">{analysisSourceRecordEmptyState(recordList)}</p>}
|
||||
</section>;
|
||||
}
|
||||
|
||||
function formatRecordValue(value: string | number | boolean | null) {
|
||||
if (value === null || value === '') return '—';
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/** Add the same all-row appendix to reports that arrive as server-rendered HTML. */
|
||||
export function appendAnalysisRecordReportHtml(source: string, value: unknown): string {
|
||||
const recordList = parseAnalysisSourceRecordList(value);
|
||||
if (!recordList) return source;
|
||||
const doc = new DOMParser().parseFromString(source, 'text/html');
|
||||
const container = doc.createElement('section');
|
||||
container.className = 'q-source-record-list';
|
||||
const heading = doc.createElement('h2'); heading.textContent = '原始记录'; container.append(heading);
|
||||
const status = doc.createElement('p'); status.className = 'q-note';
|
||||
status.textContent = recordList.queryComplete ? `已读取全部 ${recordList.loadedRows} / ${recordList.totalRows} 条` : `读取未完成 ${recordList.loadedRows} / ${recordList.totalRows} 条`;
|
||||
container.append(status);
|
||||
const style = doc.createElement('style');
|
||||
style.textContent = '.q-source-record-list{margin-top:30px}.q-source-record-list h2{font-size:18px;margin:30px 0 12px}.q-source-record-set{margin:22px 0}.q-source-record-set h3{font-size:15px;margin:18px 0 6px}.q-source-record-list .q-note{font-size:12px;color:#69778b}.q-source-record-list table{width:100%;border:1px solid #dfe5ef;border-collapse:collapse;font-size:12px;table-layout:auto}.q-source-record-list th:first-child,.q-source-record-list td:first-child{width:48px;min-width:48px;white-space:nowrap;overflow-wrap:normal;word-break:normal;font-variant-numeric:tabular-nums}.q-source-record-list th:nth-child(2),.q-source-record-list td:nth-child(2){width:140px}.q-source-record-list th{background:#f2f6fb;color:#53657c;text-align:center}.q-source-record-list th,.q-source-record-list td{padding:7px 8px;border:1px solid #dfe5ef;text-align:center;vertical-align:middle;white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word}';
|
||||
doc.head.append(style);
|
||||
for (const set of recordList.sets) {
|
||||
const section = doc.createElement('section'); section.className = 'q-source-record-set';
|
||||
const setHeading = doc.createElement('h3'); setHeading.textContent = visibleSetLabel(set); section.append(setHeading);
|
||||
const setStatus = doc.createElement('p'); setStatus.className = 'q-note'; setStatus.textContent = analysisSourceRecordSetReadStatus(set); section.append(setStatus);
|
||||
if (!set.rows.length) {
|
||||
const empty = doc.createElement('p'); empty.className = 'q-note'; empty.textContent = analysisSourceRecordEmptyState(recordList, set);
|
||||
section.append(empty); container.append(section); continue;
|
||||
}
|
||||
const table = doc.createElement('table'); const thead = doc.createElement('thead'); const headRow = doc.createElement('tr');
|
||||
const headers = ['序号', '来源文件', '工作表', '原始行号',
|
||||
...(dimensionHasValue(set, 'product') && !dimensionAlreadySelected(set.fields, 'product') ? ['产品'] : []),
|
||||
...(dimensionHasValue(set, 'group') && !dimensionAlreadySelected(set.fields, 'group') ? ['组别'] : []),
|
||||
...set.fields.map(field => field || '未命名字段')];
|
||||
for (const header of headers) { const th = doc.createElement('th'); th.textContent = header; headRow.append(th); }
|
||||
thead.append(headRow); table.append(thead);
|
||||
const tbody = doc.createElement('tbody');
|
||||
for (const [index, row] of set.rows.entries()) {
|
||||
const tr = doc.createElement('tr');
|
||||
const cells: Array<string | number> = [index + 1, row.sourceFile, row.sheet, row.rowNumber,
|
||||
...(dimensionHasValue(set, 'product') && !dimensionAlreadySelected(set.fields, 'product') ? [row.product || '—'] : []),
|
||||
...(dimensionHasValue(set, 'group') && !dimensionAlreadySelected(set.fields, 'group') ? [row.group || '—'] : []),
|
||||
...set.fields.map(field => formatRecordValue(row.values[field]))];
|
||||
for (const cell of cells) { const td = doc.createElement('td'); td.textContent = String(cell); tr.append(td); }
|
||||
tbody.append(tr);
|
||||
}
|
||||
table.append(tbody); section.append(table); container.append(section);
|
||||
}
|
||||
if (!recordList.sets.length) { const empty = doc.createElement('p'); empty.className = 'q-note'; empty.textContent = analysisSourceRecordEmptyState(recordList); container.append(empty); }
|
||||
doc.body.append(container);
|
||||
return '<!doctype html>\n' + doc.documentElement.outerHTML;
|
||||
}
|
||||
+206
-149
@@ -1,14 +1,23 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Modal } from 'antd';
|
||||
import { Alert, Button, Modal } from 'antd';
|
||||
import { DownloadOutlined } from '@ant-design/icons';
|
||||
import { toPng } from 'html-to-image';
|
||||
import { AnalysisLegacyResults } from './AnalysisLegacyResults';
|
||||
import { AnalysisReportNarrative } from './AnalysisReportNarrative';
|
||||
import { parseServerReadingSummary } from './analysisReadingModel';
|
||||
import { buildAnalysisNarrative } from './analysisReportModel';
|
||||
import { integrateNativeReportNarrative } from './nativeReportNarrative';
|
||||
import { integrateNativeReportNarrative, compactNativeReportReading } from './nativeReportNarrative';
|
||||
import narrativeCss from './analysis-narrative.css?inline';
|
||||
import exportCss from './analysis-report-export.css?inline';
|
||||
import './analysis-report-export.css';
|
||||
import { analysisScopeText } from './analysisScope';
|
||||
import { captureReportLongImage } from './analysisReportCapture';
|
||||
import { downloadAuthorizedReport, reportDownloadName } from './analysisReportFiles';
|
||||
import { reportSnapshotIdentity } from './analysisSnapshot';
|
||||
import { analysisDisplayTextRemovalRanges, sanitizeAnalysisDisplayText } from './analysisDisplayText';
|
||||
import { resolveAnalysisReportTitle, stripDuplicateFirstMarkdownH1 } from './analysisReportTitle';
|
||||
import { useReportVisualImages, type ReportVisualImage } from './AnalysisReportVisuals';
|
||||
import { analysisMemberListFullyRead, analysisMemberListPeriod, parseAnalysisMemberList } from './analysisMembersModel';
|
||||
import { AnalysisRecordListReport, appendAnalysisRecordReportHtml } from './AnalysisRecordList';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
const record = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||
@@ -17,44 +26,56 @@ const escape = (value: string) => value.replaceAll('&', '&').replaceAll('<',
|
||||
|
||||
const reportCss = `
|
||||
${narrativeCss}
|
||||
${exportCss}
|
||||
|
||||
.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}}
|
||||
.q-report .q-member-list td{white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word}.q-report .q-member-list th:last-child,.q-report .q-member-list td:last-child{width:90px}
|
||||
.q-report .q-source-record-list{margin-top:30px}.q-report .q-source-record-set{margin:22px 0}.q-report .q-source-record-set h3{font-size:15px;margin:18px 0 6px}.q-report .q-source-record-list .q-note{font-size:12px;color:#69778b}.q-report .q-source-record-list table{table-layout:auto}.q-report .q-source-record-list th:first-child,.q-report .q-source-record-list td:first-child{width:48px;min-width:48px;white-space:nowrap;overflow-wrap:normal;word-break:normal;color:inherit;font-variant-numeric:tabular-nums}.q-report .q-source-record-list th:nth-child(2),.q-report .q-source-record-list td:nth-child(2){width:140px}.q-report .q-source-record-list td{white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word}
|
||||
`;
|
||||
|
||||
function ReportDocument({ turn, stamp, visualImages }: { turn: Row; stamp: string; visualImages: ReportVisualImage[] }) {
|
||||
export function ReportDocument({ turn, stamp, visualImages }: { turn: Row; stamp: string; visualImages: ReportVisualImage[] }) {
|
||||
const result = Object.keys(record(turn.result)).length ? record(turn.result) : turn;
|
||||
const answer = sanitizeAnalysisDisplayText(text(result.reportMarkdown || turn.reportMarkdown || result.answer || turn.answer));
|
||||
const model = buildAnalysisNarrative(answer, result.visuals || turn.visuals, String(turn.question || ''));
|
||||
const reportMarkdown = String(result.reportMarkdown || turn.reportMarkdown || '');
|
||||
const sourceAnswer = sanitizeAnalysisDisplayText(text(reportMarkdown || result.answer || turn.answer));
|
||||
const model = buildAnalysisNarrative(sourceAnswer, result.visuals || turn.visuals);
|
||||
const scope = analysisScopeText(turn);
|
||||
const title = resolveAnalysisReportTitle(result.reportTitle, turn.reportTitle, reportMarkdown, model.period, scope);
|
||||
const answer = sanitizeAnalysisDisplayText(stripDuplicateFirstMarkdownH1(sourceAnswer, title));
|
||||
const memberList = parseAnalysisMemberList(result.memberList ?? turn.memberList);
|
||||
const recordListValue = result.recordList ?? turn.recordList;
|
||||
const memberListStatus = memberList && analysisMemberListFullyRead(memberList)
|
||||
? `已读取全部 ${memberList.rowsReturned} 条`
|
||||
: memberList ? `${memberList.queryComplete ? '已读取' : '读取未完成'} ${memberList.rowsReturned} / ${memberList.totalCount} 条` : '';
|
||||
return <div className="q-report">
|
||||
<style>{reportCss}</style>
|
||||
<header><div className="q-eyebrow">质量数据分析平台 · 分析报告</div><h1>{model.title.length > 90 ? `${model.title.slice(0, 90)}…` : model.title}</h1>
|
||||
<div className="q-subtitle">{[model.period, model.scope, stamp].filter(Boolean).join(' · ')}</div>
|
||||
{String(turn.question || '') !== model.title && <p className="q-report-question">{sanitizeAnalysisDisplayText(String(turn.question || ''))}</p>}
|
||||
<header><div className="q-eyebrow">质量数据分析平台 · 分析报告</div><h1>{title}</h1>
|
||||
<div className="q-subtitle">{stamp}</div>
|
||||
{scope && <p className="q-report-scope">{scope}</p>}
|
||||
</header>
|
||||
{String(turn.status || result.status) === 'PARTIAL' && <p className="q-partial">本次分析部分完成,以下保留已获得的结果。</p>}
|
||||
<AnalysisReportNarrative turn={turn} answer={answer} images={visualImages} />
|
||||
<AnalysisReportNarrative turn={turn} answer={answer} images={visualImages} mode="full" />
|
||||
<AnalysisLegacyResults turn={turn} />
|
||||
<footer>数据来源:质量数据分析平台。指标沿用正式计算口径;数据明细保留在 HTML 附录,现场原因以实际核查为准。</footer>
|
||||
{recordListValue !== undefined && recordListValue !== null && <details className="q-report-appendix"><summary>附录:完整来源记录</summary><AnalysisRecordListReport value={recordListValue} /></details>}
|
||||
{memberList && <details className="q-report-appendix"><summary>附录:完整成员清单</summary><section className="q-member-list">
|
||||
<h2>成员清单</h2>
|
||||
<p className="q-note">{analysisMemberListPeriod(memberList.period)} · {memberListStatus}</p>
|
||||
<table><thead><tr><th>序号</th>{memberList.fields.map(field => <th key={field.key}>{field.label}</th>)}<th>阶段</th></tr></thead>
|
||||
<tbody>{memberList.rows.map((row, index) => <tr key={index}>
|
||||
<td>{index + 1}</td>{memberList.fields.map(field => <td key={field.key}>{text(row.values[field.key])}</td>)}
|
||||
<td>{row.stages.map(stage => stage === 'black' ? '黑片' : '亮片').join('、')}</td>
|
||||
</tr>)}</tbody>
|
||||
</table>
|
||||
</section></details>}
|
||||
{!parseServerReadingSummary(turn) && <footer>数据来源:质量数据分析平台。指标沿用正式计算口径;现场原因以实际核查为准。</footer>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function download(href: string, name: string) { const link = document.createElement('a'); link.href = href; link.download = name; link.click(); }
|
||||
|
||||
/** 图片无法展开明细,生成前临时展开全部附录。 */
|
||||
async function captureReportImage(node: HTMLElement, options: NonNullable<Parameters<typeof toPng>[1]> = {}) {
|
||||
const details = [...node.querySelectorAll('details')].map(element => ({ element, open: element.open }));
|
||||
details.forEach(({ element }) => { element.open = true; });
|
||||
try {
|
||||
await node.ownerDocument.fonts?.ready;
|
||||
await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
|
||||
const height = Math.max(node.scrollHeight, node.offsetHeight);
|
||||
if (height > 16000) throw new Error('报告较长,请下载 HTML 查看完整图文与明细。');
|
||||
return await toPng(node, { height, backgroundColor: '#ffffff', ...options });
|
||||
} finally {
|
||||
details.forEach(({ element, open }) => { element.open = open; });
|
||||
}
|
||||
function reportHtmlFromElement(element: HTMLElement): string {
|
||||
const copy = element.cloneNode(true) as HTMLElement;
|
||||
const title = copy.querySelector('.q-report header h1')?.textContent?.trim() || '质量分析报告';
|
||||
return `<!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>${copy.innerHTML}</body></html>`;
|
||||
}
|
||||
|
||||
function removeDisplayMetadataFromElement(element: Element): void {
|
||||
@@ -87,7 +108,7 @@ function removeDisplayMetadataFromElement(element: Element): void {
|
||||
});
|
||||
}
|
||||
|
||||
function safeNativeHtml(source: string): string {
|
||||
function safeNativeHtml(source: string, title: string): string {
|
||||
const parsed = new DOMParser().parseFromString(source, 'text/html');
|
||||
parsed.querySelectorAll('script,iframe,object,embed,base,form,link,video,audio,source,track').forEach(element => element.remove());
|
||||
parsed.querySelectorAll('meta[http-equiv]').forEach(meta => {
|
||||
@@ -140,7 +161,18 @@ function safeNativeHtml(source: string): string {
|
||||
if (node.nodeType === Node.COMMENT_NODE) node.parentNode?.removeChild(node);
|
||||
else if (node.nodeValue) node.nodeValue = sanitizeAnalysisDisplayText(node.nodeValue);
|
||||
}
|
||||
parsed.title = sanitizeAnalysisDisplayText(parsed.title);
|
||||
parsed.title = title;
|
||||
const headings = [...parsed.body.querySelectorAll('h1')];
|
||||
if (headings.length) {
|
||||
headings[0].textContent = title;
|
||||
for (const heading of headings.slice(1)) {
|
||||
if ((heading.textContent || '').replace(/\s+/g, '').trim() === title.replace(/\s+/g, '').trim()) heading.remove();
|
||||
}
|
||||
} else {
|
||||
const heading = parsed.createElement('h1');
|
||||
heading.textContent = title;
|
||||
parsed.body.prepend(heading);
|
||||
}
|
||||
|
||||
const policy = parsed.createElement('meta');
|
||||
policy.setAttribute('http-equiv', 'Content-Security-Policy');
|
||||
@@ -154,6 +186,8 @@ function safeNativeHtml(source: string): string {
|
||||
}
|
||||
|
||||
function frameContentHeight(doc: Document): number {
|
||||
const children = [...doc.body.children].filter(element => !['STYLE','SCRIPT'].includes(element.tagName));
|
||||
if (children.length) return Math.ceil(Math.max(...children.map(element => element.getBoundingClientRect().bottom - doc.body.getBoundingClientRect().top), 1));
|
||||
return Math.ceil(Math.max(
|
||||
doc.body.scrollHeight,
|
||||
doc.body.offsetHeight,
|
||||
@@ -179,149 +213,172 @@ function frameFontCss(doc: Document): string {
|
||||
return fontRules.join('\n');
|
||||
}
|
||||
|
||||
export function AnalysisReportExport({ turn }: { turn: Row }) {
|
||||
const { message } = App.useApp();
|
||||
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 = 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;
|
||||
const png = await captureReportImage(report, { pixelRatio: 2, skipFonts: true });
|
||||
if (generation !== exportGeneration.current) return;
|
||||
download(png, `${title}.png`);
|
||||
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={() => 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>
|
||||
</>;
|
||||
}
|
||||
|
||||
export function NativeAnalysisReport({ turn, reportMarkdown, reportHtml }: {
|
||||
turn: Row;
|
||||
reportMarkdown: string;
|
||||
reportHtml?: string;
|
||||
function ReportExportDialog({ turn, reportMarkdown, reportHtml, native = false }: {
|
||||
turn: Row; reportMarkdown?: string; reportHtml?: string; native?: boolean;
|
||||
}) {
|
||||
const { message } = App.useApp();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [progress, setProgress] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [stamp, setStamp] = useState('');
|
||||
const [frameHeight, setFrameHeight] = useState(1);
|
||||
const [frameReady, setFrameReady] = useState(false);
|
||||
const [prepared, setPrepared] = useState<{ url: string; name: string } | null>(null);
|
||||
const [preparedHtml, setPreparedHtml] = useState<{ url: string; name: string } | null>(null);
|
||||
const preparedUrl = useRef('');
|
||||
const preparedHtmlUrl = useRef('');
|
||||
const exportGeneration = useRef(0);
|
||||
useEffect(() => { exportGeneration.current += 1; setExporting(false); return () => { exportGeneration.current += 1; }; }, [open, turn.id]);
|
||||
const node = useRef<HTMLDivElement>(null);
|
||||
const iframe = useRef<HTMLIFrameElement>(null);
|
||||
const fallbackNode = useRef<HTMLElement>(null);
|
||||
const frameToggleCleanup = useRef<() => void>(() => undefined);
|
||||
const reportTurn = useMemo(() => reportMarkdown === undefined ? turn : { ...turn, reportMarkdown,
|
||||
result: { ...(Object.keys(record(turn.result)).length ? record(turn.result) : turn), reportMarkdown } }, [turn, reportMarkdown]);
|
||||
const snapshot = reportSnapshotIdentity(turn);
|
||||
const turnId = String(turn.id || turn.turnId || '');
|
||||
const currentExport = useRef({ open, turnId, snapshot, reportHtml, reportMarkdown });
|
||||
currentExport.current = { open, turnId, snapshot, reportHtml, reportMarkdown };
|
||||
const visualReport = useReportVisualImages(turn, open);
|
||||
const safeHtml = useMemo(() => {
|
||||
const html = reportHtml?.trim() ? safeNativeHtml(reportHtml) : '';
|
||||
if (!html) return '';
|
||||
return integrateNativeReportNarrative(html, turn, visualReport.images);
|
||||
}, [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]);
|
||||
if (parseServerReadingSummary(reportTurn)) return '';
|
||||
if (!reportHtml?.trim()) return '';
|
||||
const result = Object.keys(record(reportTurn.result)).length ? record(reportTurn.result) : reportTurn;
|
||||
const markdown = String(result.reportMarkdown || reportTurn.reportMarkdown || '');
|
||||
const answer = sanitizeAnalysisDisplayText(text(markdown || result.answer || reportTurn.answer));
|
||||
const metadata = buildAnalysisNarrative(answer, result.visuals || reportTurn.visuals);
|
||||
const title = resolveAnalysisReportTitle(result.reportTitle, reportTurn.reportTitle, markdown,
|
||||
metadata.period, analysisScopeText(reportTurn));
|
||||
const withNarrative = integrateNativeReportNarrative(safeNativeHtml(reportHtml, title), reportTurn, visualReport.images);
|
||||
return compactNativeReportReading(appendAnalysisRecordReportHtml(withNarrative, result.recordList ?? reportTurn.recordList), reportTurn);
|
||||
}, [reportHtml, reportTurn, visualReport.images]);
|
||||
const showNative = Boolean(safeHtml);
|
||||
const filename = useMemo(() => {
|
||||
const result = Object.keys(record(reportTurn.result)).length ? record(reportTurn.result) : reportTurn;
|
||||
const period = buildAnalysisNarrative('', result.visuals || reportTurn.visuals).period;
|
||||
return reportDownloadName(period);
|
||||
}, [reportTurn]);
|
||||
useEffect(() => {
|
||||
exportGeneration.current += 1; setExporting(false); setProgress(''); setError(''); setPrepared(null); setPreparedHtml(null);
|
||||
if (preparedUrl.current) { URL.revokeObjectURL(preparedUrl.current); preparedUrl.current = ''; }
|
||||
if (preparedHtmlUrl.current) { URL.revokeObjectURL(preparedHtmlUrl.current); preparedHtmlUrl.current = ''; }
|
||||
return () => { exportGeneration.current += 1; if (preparedUrl.current) { URL.revokeObjectURL(preparedUrl.current); preparedUrl.current = ''; } if (preparedHtmlUrl.current) { URL.revokeObjectURL(preparedHtmlUrl.current); preparedHtmlUrl.current = ''; } };
|
||||
}, [open, turnId, snapshot, reportHtml, reportMarkdown]);
|
||||
useEffect(() => { setFrameReady(false); setFrameHeight(1); }, [safeHtml, showNative]);
|
||||
useEffect(() => () => frameToggleCleanup.current(), [safeHtml, open]);
|
||||
|
||||
const currentHtml = () => {
|
||||
if (showNative) {
|
||||
const doc = new DOMParser().parseFromString(safeHtml, 'text/html');
|
||||
return `<!doctype html>\n${doc.documentElement.outerHTML}`;
|
||||
}
|
||||
if (!node.current) throw new Error('报告尚未准备好,请稍后重试。');
|
||||
return reportHtmlFromElement(node.current);
|
||||
};
|
||||
const saveHtml = async () => {
|
||||
const html = safeHtml || `<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><title>${escape(title)}</title><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:"></head><body>${fallbackNode.current?.innerHTML || ''}</body></html>`;
|
||||
if (!safeHtml && !fallbackNode.current) return;
|
||||
const generation = ++exportGeneration.current;
|
||||
setExporting(true);
|
||||
try {
|
||||
await visualReport.authorize();
|
||||
if (generation !== exportGeneration.current) return;
|
||||
const url = URL.createObjectURL(new Blob([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 handleFrameLoad = () => {
|
||||
const doc = iframe.current?.contentDocument;
|
||||
if (!doc?.body) return;
|
||||
setFrameReady(false);
|
||||
void doc.fonts?.ready.then(() => requestAnimationFrame(() => {
|
||||
const height = frameContentHeight(doc);
|
||||
setFrameHeight(Math.max(height, 1));
|
||||
setFrameReady(true);
|
||||
}));
|
||||
};
|
||||
|
||||
const saveImage = async () => {
|
||||
const generation = ++exportGeneration.current;
|
||||
setExporting(true);
|
||||
setExporting(true); setError('');
|
||||
try {
|
||||
await visualReport.authorize();
|
||||
if (generation !== exportGeneration.current) return;
|
||||
let png: string;
|
||||
if (safeHtml) {
|
||||
const doc = iframe.current?.contentDocument;
|
||||
if (!doc?.body) throw new Error('原生报告尚未载入');
|
||||
png = await captureReportImage(doc.body, { width: 900, pixelRatio: 1, fontEmbedCSS: frameFontCss(doc) });
|
||||
} else {
|
||||
const report = fallbackNode.current;
|
||||
if (!report) throw new Error('Markdown 报告尚未载入');
|
||||
png = await captureReportImage(report, { width: 900, pixelRatio: 1, skipFonts: true });
|
||||
}
|
||||
if (generation !== exportGeneration.current) return;
|
||||
download(png, `${title}.png`);
|
||||
message.success(visualReport.failed ? '报告图片已生成,未能绘制的图表已保留数据表。' : '报告图片已生成');
|
||||
} catch (error) {
|
||||
if (generation === exportGeneration.current) message.error(error instanceof Error ? error.message : '图片生成失败,请重试。');
|
||||
} finally {
|
||||
if (generation === exportGeneration.current) setExporting(false);
|
||||
}
|
||||
if (preparedHtmlUrl.current) URL.revokeObjectURL(preparedHtmlUrl.current);
|
||||
preparedHtmlUrl.current = URL.createObjectURL(new Blob([currentHtml()], { type: 'text/html;charset=utf-8' }));
|
||||
setPreparedHtml({ url: preparedHtmlUrl.current, name: `${filename}.html` });
|
||||
setProgress('HTML 已准备好。点击“下载 HTML”保存。');
|
||||
} catch (value) { if (generation === exportGeneration.current) setError(value instanceof Error ? value.message : '报告导出失败,请重试。'); }
|
||||
finally { if (generation === exportGeneration.current) setExporting(false); }
|
||||
};
|
||||
|
||||
const prepareImages = async () => {
|
||||
const generation = ++exportGeneration.current;
|
||||
setExporting(true); setError(''); setProgress('正在准备长图…');
|
||||
try {
|
||||
await visualReport.authorize();
|
||||
if (generation !== exportGeneration.current) return;
|
||||
const doc = showNative ? iframe.current?.contentDocument : null;
|
||||
const report = showNative ? doc?.body : node.current?.querySelector<HTMLElement>('.q-report');
|
||||
if (!report) throw new Error('报告尚未准备好,请稍后重试。');
|
||||
const blob = await captureReportLongImage(report, doc ? { fontEmbedCSS: frameFontCss(doc) } : { skipFonts: true },
|
||||
() => generation !== exportGeneration.current);
|
||||
if (generation !== exportGeneration.current) return;
|
||||
if (preparedUrl.current) URL.revokeObjectURL(preparedUrl.current);
|
||||
preparedUrl.current = URL.createObjectURL(blob);
|
||||
setPrepared({ url: preparedUrl.current, name: `${filename}.png` });
|
||||
setProgress('长图已准备好。点击“下载长图”保存。');
|
||||
} catch (value) { if (generation === exportGeneration.current) { setProgress(''); setError(value instanceof Error ? value.message : '图片生成失败,请重试或下载 HTML。'); } }
|
||||
finally { if (generation === exportGeneration.current) setExporting(false); }
|
||||
};
|
||||
const downloadPrepared = async (file: { url: string; name: string }, kind: 'html' | 'image') => {
|
||||
const generation = ++exportGeneration.current;
|
||||
const expected = currentExport.current;
|
||||
const isCurrent = () => {
|
||||
const current = currentExport.current;
|
||||
return current.open && generation === exportGeneration.current
|
||||
&& current.turnId === expected.turnId && current.snapshot === expected.snapshot
|
||||
&& current.reportHtml === expected.reportHtml && current.reportMarkdown === expected.reportMarkdown
|
||||
&& (kind === 'html' ? preparedHtmlUrl.current : preparedUrl.current) === file.url;
|
||||
};
|
||||
setExporting(true); setError('');
|
||||
try {
|
||||
await downloadAuthorizedReport({
|
||||
authorize: visualReport.authorize,
|
||||
isCurrent,
|
||||
onDenied: value => {
|
||||
if (preparedUrl.current) URL.revokeObjectURL(preparedUrl.current);
|
||||
if (preparedHtmlUrl.current) URL.revokeObjectURL(preparedHtmlUrl.current);
|
||||
preparedUrl.current = ''; preparedHtmlUrl.current = '';
|
||||
setPrepared(null); setPreparedHtml(null); setProgress('');
|
||||
setError(value instanceof Error ? value.message : '无法验证此报告的访问权限,请重新打开分析。');
|
||||
},
|
||||
download: () => {
|
||||
const link = document.createElement('a');
|
||||
link.href = file.url; link.download = file.name;
|
||||
document.body.appendChild(link); link.click(); link.remove();
|
||||
},
|
||||
});
|
||||
} finally { if (generation === exportGeneration.current) setExporting(false); }
|
||||
};
|
||||
const handleFrameLoad = () => {
|
||||
frameToggleCleanup.current();
|
||||
const doc = iframe.current?.contentDocument;
|
||||
if (!doc?.body) return;
|
||||
const resize = () => requestAnimationFrame(() => { if (iframe.current?.contentDocument === doc) setFrameHeight(Math.max(frameContentHeight(doc), 1)); });
|
||||
doc.addEventListener('toggle', resize, true);
|
||||
frameToggleCleanup.current = () => doc.removeEventListener('toggle', resize, true);
|
||||
setFrameReady(false);
|
||||
void Promise.resolve(doc.fonts?.ready).then(() => requestAnimationFrame(() => {
|
||||
if (iframe.current?.contentDocument !== doc) return;
|
||||
setFrameHeight(Math.max(frameContentHeight(doc), 1)); setFrameReady(true);
|
||||
}));
|
||||
};
|
||||
const disabled = exporting || visualReport.loading || !visualReport.authorized || showNative && !frameReady;
|
||||
return <>
|
||||
<Button type="text" size="small" icon={<DownloadOutlined />} onClick={() => setOpen(true)}>查看报告</Button>
|
||||
<Modal title="分析报告" open={open} onCancel={() => setOpen(false)} width={980} footer={<>
|
||||
<Button disabled={exporting || 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>
|
||||
<Button type="text" size="small" icon={<DownloadOutlined />} onClick={() => { setStamp(new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })); setOpen(true); }}>{native ? '查看报告' : '生成报告'}</Button>
|
||||
<Modal title="分析报告" open={open} onCancel={() => { exportGeneration.current += 1; currentExport.current.open = false; setOpen(false); }} width={980} footer={<>
|
||||
{preparedHtml
|
||||
? <Button disabled={disabled} onClick={() => void downloadPrepared(preparedHtml, 'html')}>下载 HTML</Button>
|
||||
: <Button disabled={disabled} onClick={() => void saveHtml()}>下载 HTML</Button>}
|
||||
{prepared
|
||||
? <Button type="primary" disabled={disabled} onClick={() => void downloadPrepared(prepared, 'image')}>下载长图</Button>
|
||||
: <Button type="primary" loading={exporting} disabled={disabled} onClick={() => void prepareImages()}>下载长图</Button>}
|
||||
</>}>
|
||||
{visualReport.loading && <p role="status">{visualReport.progress || '正在准备报告图表…'}</p>}
|
||||
{progress && <p className="analysis-report-export-status" role="status" aria-live="polite">{progress}</p>}
|
||||
{error && <Alert className="analysis-report-export-error" type="error" showIcon title={error} closable onClose={() => setError('')} />}
|
||||
{visualReport.failed && <Alert type="warning" showIcon title="部分图表未生成,报告保留相应数据表。" />}
|
||||
{visualReport.authorizationError && <Alert type="error" showIcon title={visualReport.authorizationError} />}
|
||||
{visualReport.authorizationError && visualReport.authorizationError !== error && <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 ref={fallbackNode}><ReportDocument turn={{ ...turn, reportMarkdown }} stamp="" visualImages={visualReport.images} /></article>}
|
||||
{showNative
|
||||
? <iframe ref={iframe} className="native-analysis-report-frame" title="分析报告预览" sandbox="allow-same-origin" srcDoc={safeHtml} width={900} height={frameHeight} onLoad={handleFrameLoad} />
|
||||
: <div ref={node}><ReportDocument turn={reportTurn} stamp={stamp} visualImages={visualReport.images} /></div>}
|
||||
</div>}
|
||||
</Modal>
|
||||
</>;
|
||||
}
|
||||
|
||||
export function AnalysisReportExport({ turn }: { turn: Row }) {
|
||||
return <ReportExportDialog turn={turn} />;
|
||||
}
|
||||
|
||||
export function NativeAnalysisReport({ turn, reportMarkdown, reportHtml }: {
|
||||
turn: Row; reportMarkdown: string; reportHtml?: string;
|
||||
}) {
|
||||
return <ReportExportDialog turn={turn} reportMarkdown={reportMarkdown} reportHtml={reportHtml} native />;
|
||||
}
|
||||
|
||||
@@ -1,34 +1,37 @@
|
||||
import { useMemo } from 'react';
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
import type { AnalysisVisual } from './analysisVisualsModel';
|
||||
import { RateComparisonReadout, NarrativeEvidence } from './AnalysisNarrative';
|
||||
import { buildAnalysisNarrative, useCompactRateComparison } from './analysisReportModel';
|
||||
import { AnalysisConclusion } from './AnalysisConclusion';
|
||||
import { NarrativeEvidence, FocusProductTable } from './AnalysisNarrative';
|
||||
import { buildAnalysisReadingModel } from './analysisReadingModel';
|
||||
import { ReportVisualDataTable, ReportVisualFigure, type ReportVisualImage, reportVisuals } from './AnalysisReportVisuals';
|
||||
import type { AnalysisReportMode } from './analysisReportSummary';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
|
||||
export function AnalysisReportNarrative({ turn, answer, images }: { turn: Row; answer: string; images: ReportVisualImage[] }) {
|
||||
/** HTML remains collapsible; long-image capture expands every detail before measuring. */
|
||||
export function AnalysisReportNarrative({ turn, answer, images }: { turn: Row; answer: string; images: ReportVisualImage[]; mode?: AnalysisReportMode }) {
|
||||
const visuals = reportVisuals(turn);
|
||||
const model = useMemo(() => buildAnalysisNarrative(answer, visuals, String(turn.question || '')), [answer, JSON.stringify(visuals), turn.question]);
|
||||
const signature = JSON.stringify(visuals);
|
||||
const { model, reading, primaryVisuals } = useMemo(() => buildAnalysisReadingModel(answer, visuals, String(turn.question || ''), turn), [answer, signature, turn]);
|
||||
const prefix = `report-${String(turn.id || turn.turnId || 'answer').replace(/[^a-zA-Z0-9_-]/g, '')}-`;
|
||||
const text = (content: string) => <AiMarkdown content={content} evidenceLabels={model.evidenceLabels} evidencePrefix={prefix} />;
|
||||
const compact = (visual: AnalysisVisual) => useCompactRateComparison(visual, String(turn.question || ''));
|
||||
const appendix = model.sections.filter(section => section.visuals.length || section.tables.length);
|
||||
return <div className="analysis-narrative report-narrative">
|
||||
{model.sections.length > 4 && <nav className="q-report-contents" aria-label="报告目录">{model.sections.filter(section => section.title).map(section => <a key={section.id} href={`#${prefix}${section.id}`}>{section.title}</a>)}</nav>}
|
||||
{model.sections.map(section => <section key={section.id} id={`${prefix}${section.id}`} className={`analysis-narrative-section is-${section.kind}`} data-section-kind={section.kind}>
|
||||
const primaryIds = new Set(primaryVisuals.map(visual => visual.id));
|
||||
const complete = <>
|
||||
{model.sections.filter(section => !primaryIds.size || section.narrative || section.tables.length || section.focusProducts?.length || section.visuals.some(visual => !primaryIds.has(visual.id))).map(section => <section key={section.id} id={`${prefix}${section.id}`} className={`analysis-narrative-section is-${section.kind}`} data-section-kind={section.kind}>
|
||||
{section.title && <h2 className="analysis-narrative-title">{section.title}</h2>}
|
||||
{section.focusProducts && <FocusProductTable rows={section.focusProducts} evidenceLabels={model.evidenceLabels} evidencePrefix={prefix} />}
|
||||
{section.narrative && text(section.narrative)}
|
||||
{!!section.visuals.filter(compact).length && <div className="analysis-rate-grid">{section.visuals.filter(compact).map(visual => <RateComparisonReadout key={visual.id} visual={visual} />)}</div>}
|
||||
{section.visuals.filter(visual => !compact(visual)).map(visual => <ReportVisualFigure key={visual.id} visual={visual} image={images.find(image => image.id === visual.id)} evidenceLabels={model.evidenceLabels} evidencePrefix={prefix} />)}
|
||||
{!section.visuals.length && section.tables.map((table, index) => <div key={index}>{text(table)}</div>)}
|
||||
{!!section.visuals.length && section.tables.length > 0 && <p className="q-note q-report-detail-link"><a href={`#${prefix}appendix`}>完整数据见附录</a></p>}
|
||||
</section>)}
|
||||
{!!appendix.length && <details className="q-report-appendix" id={`${prefix}appendix`}><summary>数据明细与图表依据</summary>{appendix.map(section => <div key={section.id}>
|
||||
<h3>{section.title || '分析数据'}</h3>
|
||||
{section.tables.map((table, index) => <div key={index}>{text(table)}</div>)}
|
||||
{section.visuals.map(visual => <div key={visual.id} className="q-report-appendix-visual"><h4>{visual.title}</h4><ReportVisualDataTable visual={visual} /></div>)}
|
||||
</div>)}</details>}
|
||||
{section.visuals.filter(visual => !primaryIds.has(visual.id)).map(visual => <div key={visual.id}>
|
||||
<ReportVisualFigure visual={visual} image={images.find(image => image.id === visual.id)} evidenceLabels={model.evidenceLabels} evidencePrefix={prefix} />
|
||||
<ReportVisualDataTable visual={visual} />
|
||||
</div>)}
|
||||
</section>)}
|
||||
<NarrativeEvidence model={model} prefix={prefix} />
|
||||
</>;
|
||||
return <div className="analysis-narrative report-narrative">
|
||||
{reading.hasAppendix ? <AnalysisConclusion reading={reading} visuals={primaryVisuals} renderVisuals={figures => figures.map(visual => <div key={visual.id}>
|
||||
<ReportVisualFigure visual={visual} image={images.find(image => image.id === visual.id)} hideEvidence />
|
||||
</div>)} /> : complete}
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { parseAnalysisVisuals, combineStageDefectVisuals, renderVisualPng, visualPeriodSummary, visualScopeSummary, visualCategoryLabel } from './analysisVisualsModel';
|
||||
import { analysisSnapshotResult, authorizeAnalysisSnapshot, reportSnapshotIdentity } from './analysisSnapshot';
|
||||
import type { AnalysisVisual } from './analysisVisualsModel';
|
||||
import { useCompactRateComparison } from './analysisReportModel';
|
||||
import { analysisVisualCumulativeShares, analysisVisualShares } from './analysisVisualPresentation';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
@@ -42,7 +41,7 @@ export function useReportVisualImages(turn: Row, open: boolean) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const plotted = visuals.filter(visual => !useCompactRateComparison(visual, String(turn.question || '')));
|
||||
const plotted = visuals;
|
||||
for (const [index, visual] of plotted.entries()) {
|
||||
if (controller.signal.aborted) return;
|
||||
setProgress(`正在准备图表 ${index + 1}/${plotted.length}`);
|
||||
@@ -73,18 +72,20 @@ export function useReportVisualImages(turn: Row, open: boolean) {
|
||||
authorizationError: current ? authorization.error : '', failed: images.some(image => image.failed), authorize };
|
||||
}
|
||||
|
||||
function shown(value: number | null, unit: string): string {
|
||||
function shown(value: number | null, unit: string, metric?: string): string {
|
||||
if (value === null) return '—';
|
||||
return `${(unit === 'ratio' ? value * 100 : value).toLocaleString('zh-CN', { maximumFractionDigits: 2 })}${unit === 'ratio' ? '%' : unit === 'pp' ? ' pp' : unit === 'kg' ? ' kg' : ''}`;
|
||||
const precision = unit === 'kg' && (metric === 'source_defect_weight' || metric === 'source_defect_delta_weight')
|
||||
? { maximumSignificantDigits: 15 } : { maximumFractionDigits: 2 };
|
||||
return `${(unit === 'ratio' ? value * 100 : value).toLocaleString('zh-CN', precision)}${unit === 'ratio' ? '%' : unit === 'pp' ? ' pp' : unit === 'kg' ? ' kg' : ''}`;
|
||||
}
|
||||
|
||||
export function ReportVisualDataTable({ visual }: { visual: AnalysisVisual }) {
|
||||
const shares = analysisVisualShares(visual), cumulativeShares = analysisVisualCumulativeShares(visual);
|
||||
return <table><thead><tr><th>序号</th><th>对象 / 期间</th>{visual.series.map(series => <th key={series.key}>{series.label}</th>)}{shares && <th>占已列类别合计</th>}{cumulativeShares && <th>累计占已列类别合计</th>}</tr></thead>
|
||||
<tbody>{visual.categories.map((category, index) => <tr key={category.key}><td>{index + 1}</td><td>{visualCategoryLabel(visual, index)}</td>{visual.series.map(series => <td key={series.key}>{shown(series.values[index] ?? null, visual.unit)}</td>)}{shares && <td>{(shares[index] * 100).toFixed(2)}%</td>}{cumulativeShares && <td>{(cumulativeShares[index] * 100).toFixed(2)}%</td>}</tr>)}</tbody></table>;
|
||||
return <table><thead><tr><th>序号</th><th>对象 / 期间</th>{visual.series.map(series => <th key={series.key}>{series.label}</th>)}{shares && <th>{visual.coverage.shareBasis === 'all_scope_weight' ? '占全部重量' : '占已列类别合计'}</th>}{cumulativeShares && <th>{visual.coverage.shareBasis === 'all_scope_weight' ? '累计占全部重量' : '累计占已列类别合计'}</th>}</tr></thead>
|
||||
<tbody>{visual.categories.map((category, index) => <tr key={category.key}><td>{index + 1}</td><td>{visualCategoryLabel(visual, index)}</td>{visual.series.map(series => <td key={series.key}>{shown(series.values[index] ?? null, visual.unit, visual.metric)}</td>)}{shares && <td>{(shares[index] * 100).toFixed(2)}%</td>}{cumulativeShares && <td>{(cumulativeShares[index] * 100).toFixed(2)}%</td>}</tr>)}</tbody></table>;
|
||||
}
|
||||
|
||||
export function ReportVisualFigure({ visual, image, evidenceLabels = {}, evidencePrefix = '' }: { visual: AnalysisVisual; image?: ReportVisualImage; evidenceLabels?: Record<string, string>; evidencePrefix?: string }) {
|
||||
export function ReportVisualFigure({ visual, image, evidenceLabels = {}, evidencePrefix = '', hideEvidence = false }: { visual: AnalysisVisual; image?: ReportVisualImage; evidenceLabels?: Record<string, string>; evidencePrefix?: string; hideEvidence?: boolean }) {
|
||||
|
||||
return <figure className="q-report-visual">
|
||||
<div className="q-report-visual-heading"><strong>{visual.title}</strong><span>{visual.unit === 'pp' ? '百分点' : visual.unit === 'ratio' ? '%' : visual.unit}</span></div>
|
||||
@@ -92,7 +93,7 @@ export function ReportVisualFigure({ visual, image, evidenceLabels = {}, evidenc
|
||||
{(!image?.png || image.failed || !visual.chartable) && <><p className="q-partial">此图以同一份结果的数据表显示。</p><ReportVisualDataTable visual={visual} /></>}
|
||||
<figcaption>{visualPeriodSummary(visual)}{visualScopeSummary(visual.scope) ? ` · ${visualScopeSummary(visual.scope)}` : ''}{visual.coverage.truncated ? ` · 展示 ${visual.coverage.returnedRows} / ${visual.coverage.totalRows} 项` : ''}
|
||||
{visual.note && <span> · {visual.note}</span>}
|
||||
{visual.evidenceRefs.map(ref => <a className="analysis-evidence-ref" key={ref} href={`#${evidencePrefix}${ref}`} title={ref}>{evidenceLabels[ref] || ref}</a>)}
|
||||
{!hideEvidence && visual.evidenceRefs.map(ref => <a className="analysis-evidence-ref" key={ref} href={`#${evidencePrefix}${ref}`} title={ref}>{evidenceLabels[ref] || ref}</a>)}
|
||||
</figcaption>
|
||||
</figure>;
|
||||
}
|
||||
@@ -109,17 +110,12 @@ export function reportVisualHtml(turn: Row, images: ReportVisualImage[]): string
|
||||
const image = images.find(item => item.id === visual.id);
|
||||
const shares = analysisVisualShares(visual);
|
||||
const cumulativeShares = analysisVisualCumulativeShares(visual);
|
||||
const headers = visual.series.map(series => `<th>${escapeHtml(series.label)}</th>`).join('') + (shares ? '<th>占已列类别合计</th>' : '') + (cumulativeShares ? '<th>累计占已列类别合计</th>' : '');
|
||||
const rows = visual.categories.map((_category, index) => `<tr><td>${index + 1}</td><td>${escapeHtml(visualCategoryLabel(visual, index))}</td>${visual.series.map(series => `<td>${escapeHtml(shown(series.values[index] ?? null, visual.unit))}</td>`).join('')}${shares ? `<td>${(shares[index] * 100).toFixed(2)}%</td>` : ''}${cumulativeShares ? `<td>${(cumulativeShares[index] * 100).toFixed(2)}%</td>` : ''}</tr>`).join('');
|
||||
const headers = visual.series.map(series => `<th>${escapeHtml(series.label)}</th>`).join('') + (shares ? `<th>${visual.coverage.shareBasis === 'all_scope_weight' ? '占全部重量' : '占已列类别合计'}</th>` : '') + (cumulativeShares ? `<th>${visual.coverage.shareBasis === 'all_scope_weight' ? '累计占全部重量' : '累计占已列类别合计'}</th>` : '');
|
||||
const rows = visual.categories.map((_category, index) => `<tr><td>${index + 1}</td><td>${escapeHtml(visualCategoryLabel(visual, index))}</td>${visual.series.map(series => `<td>${escapeHtml(shown(series.values[index] ?? null, visual.unit, visual.metric))}</td>`).join('')}${shares ? `<td>${(shares[index] * 100).toFixed(2)}%</td>` : ''}${cumulativeShares ? `<td>${(cumulativeShares[index] * 100).toFixed(2)}%</td>` : ''}</tr>`).join('');
|
||||
const png = image?.png && /^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(image.png) ? image.png : '';
|
||||
const context = `期间:${visualPeriodSummary(visual)}${visualScopeSummary(visual.scope) ? ` · 范围:${visualScopeSummary(visual.scope)}` : ''}`;
|
||||
const table = `<table style="width:100%;border-collapse:collapse;font-size:13px" border="1"><thead><tr><th>序号</th><th>对象 / 期间</th>${headers}</tr></thead><tbody>${rows}</tbody></table>`;
|
||||
let picture = png ? `<img alt="${escapeHtml(visual.title)}" src="${png}" style="display:block;width:100%;height:auto">` : '';
|
||||
if (useCompactRateComparison(visual, String(turn.question || ''))) {
|
||||
const [before, after] = visual.series[0].values as [number, number];
|
||||
const delta = (after - before) * 100;
|
||||
picture = `<div style="padding:16px 20px;background:#f4f7fb;display:flex;align-items:center;gap:20px;flex-wrap:wrap"><span style="font-size:22px;color:#65748b">${(before * 100).toFixed(2)}%</span><span>→</span><strong style="font-size:30px">${(after * 100).toFixed(2)}%</strong><span style="font-size:16px">${delta > 0 ? '+' : ''}${delta.toFixed(2)} 个百分点</span></div>`;
|
||||
}
|
||||
const picture = png ? `<img alt="${escapeHtml(visual.title)}" src="${png}" style="display:block;width:100%;height:auto">` : '';
|
||||
const detail = picture ? `<details style="margin:10px 0;font-size:12px"><summary style="cursor:pointer">查看本图数据</summary>${table}</details>` : `<p>此图以数据表显示。</p>${table}`;
|
||||
return `<section class="platform-report-visual" style="break-inside:avoid;padding:14px 0;color:#202b3c;background:white"><h3 style="margin:6px 0 10px;font-size:16px">${escapeHtml(visual.title)}</h3>${picture}<p style="font-size:12px;color:#65748b">${escapeHtml(context)}${visual.note ? ` · ${escapeHtml(visual.note)}` : ''}</p>${detail}<p style="font-size:11px;color:#65748b">数据依据:${escapeHtml(visual.evidenceRefs.join('、'))}</p></section>`;
|
||||
}).join('');
|
||||
|
||||
+77
-19
@@ -13,6 +13,7 @@ import {
|
||||
visualCategoryLabel,
|
||||
visualPeriodSummary,
|
||||
visualScopeSummary,
|
||||
visualUnitLabel,
|
||||
} from './analysisVisualsModel';
|
||||
import type { AnalysisVisual } from './analysisVisualsModel';
|
||||
import { analysisVisualCumulativeShares, analysisVisualShares, analysisVisualTypeLabel } from './analysisVisualPresentation';
|
||||
@@ -23,6 +24,8 @@ export interface AnalysisVisualsProps {
|
||||
visualState?: unknown;
|
||||
beforeExport?: () => Promise<void>;
|
||||
embedded?: boolean;
|
||||
hideEvidence?: boolean;
|
||||
combineStages?: boolean;
|
||||
}
|
||||
|
||||
interface VisualTableRow {
|
||||
@@ -83,9 +86,9 @@ function ChartDataTable({ visual, compact = false }: { visual: AnalysisVisual; c
|
||||
: <span className="analysis-visual-table-value">{formatVisualValue(value, visual.unit)}</span>;
|
||||
},
|
||||
})),
|
||||
...(shares ? [{ title: '占已列类别合计', key: 'compositionShare', align: 'center' as const, width: 160,
|
||||
...(shares ? [{ title: visual.coverage.shareBasis === 'all_scope_weight' ? '占全部重量' : '占已列类别合计', key: 'compositionShare', align: 'center' as const, width: 160,
|
||||
render: (_value: unknown, row: VisualTableRow) => `${(shares[row.index - 1] * 100).toFixed(2)}%` }] : []),
|
||||
...(cumulativeShares ? [{ title: '累计占已列类别合计', key: 'cumulativeShare', align: 'center' as const, width: 170,
|
||||
...(cumulativeShares ? [{ title: visual.coverage.shareBasis === 'all_scope_weight' ? '累计占全部重量' : '累计占已列类别合计', key: 'cumulativeShare', align: 'center' as const, width: 170,
|
||||
render: (_value: unknown, row: VisualTableRow) => `${(cumulativeShares[row.index - 1] * 100).toFixed(2)}%` }] : []),
|
||||
];
|
||||
return <div className={compact ? 'analysis-visual-table is-compact' : 'analysis-visual-table'}>
|
||||
@@ -110,7 +113,12 @@ function chartSummary(visual: AnalysisVisual): string {
|
||||
return `${visual.title}。${visual.subtitle}。期间:${visualPeriodSummary(visual)}。${visual.categories.length} 个对象,${visual.series.map(item => item.label).join('、')}。${visualScopeSummary(visual.scope)}`;
|
||||
}
|
||||
|
||||
function AnalysisVisualCard({ visual, beforeExport }: { visual: AnalysisVisual; beforeExport?: () => Promise<void> }) {
|
||||
export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAnalysisVisualECharts, hideEvidence = false }: {
|
||||
visual: AnalysisVisual;
|
||||
beforeExport?: () => Promise<void>;
|
||||
loadRuntime?: typeof loadAnalysisVisualECharts;
|
||||
hideEvidence?: boolean;
|
||||
}) {
|
||||
const cardRef = useRef<HTMLElement>(null);
|
||||
const chartNodeRef = useRef<HTMLDivElement>(null);
|
||||
const chartRef = useRef<Awaited<ReturnType<typeof loadAnalysisVisualECharts>> extends never ? never : import('echarts/core').ECharts | null>(null);
|
||||
@@ -123,6 +131,44 @@ function AnalysisVisualCard({ visual, beforeExport }: { visual: AnalysisVisual;
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [exportError, setExportError] = useState('');
|
||||
const [themeRevision, setThemeRevision] = useState(0);
|
||||
const [renderAttempt, setRenderAttempt] = useState(0);
|
||||
const [retrying, setRetrying] = useState(false);
|
||||
const [accessBlocked, setAccessBlocked] = useState(false);
|
||||
const retryGeneration = useRef(0);
|
||||
const retryPending = useRef(false);
|
||||
const visualIdentity = JSON.stringify(visual);
|
||||
const currentIdentity = useRef(visualIdentity);
|
||||
currentIdentity.current = visualIdentity;
|
||||
|
||||
useEffect(() => {
|
||||
setAccessBlocked(false); setRetrying(false); retryPending.current = false;
|
||||
setExportError(''); setChartError(''); setDataOpen(false);
|
||||
exportControllerRef.current?.abort(); exportControllerRef.current = null; setExporting(false);
|
||||
retryGeneration.current += 1;
|
||||
return () => { retryGeneration.current += 1; retryPending.current = false; };
|
||||
}, [visualIdentity]);
|
||||
|
||||
const retryChart = useCallback(async () => {
|
||||
if (retryPending.current) return;
|
||||
const generation = ++retryGeneration.current;
|
||||
const identity = visualIdentity;
|
||||
const current = () => generation === retryGeneration.current && identity === currentIdentity.current;
|
||||
retryPending.current = true; setRetrying(true);
|
||||
try {
|
||||
if (!beforeExport) throw new Error('请重新打开这条分析后再重试图表。');
|
||||
await beforeExport();
|
||||
if (!current()) return;
|
||||
setAccessBlocked(false); setExportError(''); setChartReady(false);
|
||||
setRenderAttempt(value => value + 1);
|
||||
} catch (error) {
|
||||
if (current()) {
|
||||
setAccessBlocked(true); setChartReady(false); setDataOpen(false);
|
||||
setExportError(error instanceof Error ? error.message : '无法验证此图表的访问权限,请重新打开分析。');
|
||||
}
|
||||
} finally {
|
||||
if (current()) { retryPending.current = false; setRetrying(false); }
|
||||
}
|
||||
}, [beforeExport, visualIdentity]);
|
||||
|
||||
useEffect(() => {
|
||||
const node = cardRef.current;
|
||||
@@ -137,16 +183,17 @@ function AnalysisVisualCard({ visual, beforeExport }: { visual: AnalysisVisual;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!nearViewport || !visual.chartable) return;
|
||||
if (!nearViewport || !visual.chartable || accessBlocked) return;
|
||||
let cancelled = false;
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
let instance: Awaited<ReturnType<typeof loadAnalysisVisualECharts>>['init'] extends (...args: never[]) => infer T ? T : never;
|
||||
let instance: (Awaited<ReturnType<typeof loadAnalysisVisualECharts>>['init'] extends (...args: never[]) => infer T ? T : never) | undefined;
|
||||
const mount = async () => {
|
||||
const node = chartNodeRef.current;
|
||||
if (!node || documentIsHidden() || cancelled) return;
|
||||
setChartLoading(true);
|
||||
setChartReady(false);
|
||||
try {
|
||||
const echarts = await loadAnalysisVisualECharts();
|
||||
const echarts = await loadRuntime();
|
||||
if (cancelled || !chartNodeRef.current || documentIsHidden()) return;
|
||||
instance = echarts.init(chartNodeRef.current, undefined, { renderer: 'svg' });
|
||||
chartRef.current = instance;
|
||||
@@ -157,14 +204,16 @@ function AnalysisVisualCard({ visual, beforeExport }: { visual: AnalysisVisual;
|
||||
const chartNode = chartNodeRef.current;
|
||||
if (cancelled || documentIsHidden() || !chartNode) return;
|
||||
const bounds = chartNode.getBoundingClientRect();
|
||||
if (bounds.width > 0 && bounds.height > 0) instance.resize();
|
||||
if (bounds.width > 0 && bounds.height > 0) instance?.resize();
|
||||
};
|
||||
resizeObserver = new ResizeObserver(resize);
|
||||
resizeObserver.observe(chartNodeRef.current);
|
||||
setChartError('');
|
||||
setChartReady(true);
|
||||
} catch {
|
||||
if (!cancelled) setChartError('图表渲染暂不可用,可以继续查看完整数据表。');
|
||||
instance?.dispose();
|
||||
if (chartRef.current === instance) chartRef.current = null;
|
||||
if (!cancelled) { setChartReady(false); setChartError('图表渲染暂不可用,可以继续查看完整数据表。'); }
|
||||
} finally {
|
||||
if (!cancelled) setChartLoading(false);
|
||||
}
|
||||
@@ -184,7 +233,7 @@ function AnalysisVisualCard({ visual, beforeExport }: { visual: AnalysisVisual;
|
||||
instance?.dispose();
|
||||
if (chartRef.current === instance) chartRef.current = null;
|
||||
};
|
||||
}, [nearViewport, visual.chartable, visual.id]);
|
||||
}, [nearViewport, visual.chartable, visual.id, visualIdentity, renderAttempt, accessBlocked, loadRuntime]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!nearViewport || !visual.chartable) return;
|
||||
@@ -241,6 +290,11 @@ function AnalysisVisualCard({ visual, beforeExport }: { visual: AnalysisVisual;
|
||||
? `本图展示 ${visual.coverage.returnedRows} / 共 ${visual.coverage.totalRows} 项`
|
||||
: `共 ${visual.coverage.totalRows} 项`;
|
||||
|
||||
if (accessBlocked) return <article className="analysis-visual-card" ref={cardRef}>
|
||||
<p role="alert">{exportError || '无法验证此图表的访问权限,已隐藏原数据。'}</p>
|
||||
<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}>
|
||||
<header className="analysis-visual-heading">
|
||||
<div className="analysis-visual-heading-copy">
|
||||
@@ -268,13 +322,14 @@ function AnalysisVisualCard({ visual, beforeExport }: { visual: AnalysisVisual;
|
||||
{visual.chartable ? <>
|
||||
<div
|
||||
className="analysis-visual-chart-wrap"
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
role={chartError ? 'group' : 'button'}
|
||||
tabIndex={chartError ? -1 : 0}
|
||||
aria-label={`${chartSummary(visual)}。按 Enter 或空格查看数据。`}
|
||||
aria-busy={chartLoading}
|
||||
style={visual.sectionKey === 'defect_combined' ? { height: Math.max(320, visual.categories.length * 38 + 48) } : undefined}
|
||||
onClick={openData}
|
||||
onClick={chartError ? undefined : openData}
|
||||
onKeyDown={event => {
|
||||
if (chartError) return;
|
||||
if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openData(); }
|
||||
}}
|
||||
>
|
||||
@@ -283,7 +338,10 @@ function AnalysisVisualCard({ visual, beforeExport }: { visual: AnalysisVisual;
|
||||
: visual.type === 'pareto' ? { minWidth: Math.max(600, visual.categories.length * 90 + 180) } : undefined} />
|
||||
{!nearViewport && <div className="analysis-visual-placeholder">图表将在进入视口时加载</div>}
|
||||
{nearViewport && chartLoading && <div className="analysis-visual-placeholder" role="status">正在加载图表…</div>}
|
||||
{chartError && <div className="analysis-visual-chart-error" role="status">{chartError}</div>}
|
||||
{chartError && <div className="analysis-visual-chart-error" role="status">{chartError}
|
||||
<Button size="small" loading={retrying || chartLoading} onKeyDown={event => event.stopPropagation()}
|
||||
onClick={event => { event.stopPropagation(); void retryChart(); }}>重试图表</Button>
|
||||
</div>}
|
||||
{!chartLoading && !chartError && !chartReady && nearViewport && <div className="analysis-visual-placeholder">图表准备中…</div>}
|
||||
</div>
|
||||
{visual.type === 'heatmap' && <p className="analysis-visual-scroll-hint">可横向滑动查看各期,或查看完整数据。</p>}
|
||||
@@ -306,21 +364,21 @@ function AnalysisVisualCard({ visual, beforeExport }: { visual: AnalysisVisual;
|
||||
>
|
||||
<div className="analysis-visual-modal-context">
|
||||
<span>{visual.subtitle}</span><span>期间:{period}</span>{scope && <span>范围:{scope}</span>}
|
||||
<span>单位:{visual.unit === 'ratio' ? '合格率' : visual.unit === 'kg' ? 'kg' : visual.unit === 'pp' ? '百分点' : '数量'}</span>
|
||||
<span>单位:{visualUnitLabel(visual)}</span>
|
||||
</div>
|
||||
<ChartDataTable visual={visual} />
|
||||
{visual.note && <p className="analysis-visual-modal-note">{visual.note}</p>}
|
||||
{visual.evidenceRefs.length > 0 && <div className="analysis-visual-evidence"><strong>证据引用</strong><ul>{visual.evidenceRefs.map(ref => <li key={ref}>{ref}</li>)}</ul></div>}
|
||||
{!hideEvidence && visual.evidenceRefs.length > 0 && <div className="analysis-visual-evidence"><strong>证据引用</strong><ul>{visual.evidenceRefs.map(ref => <li key={ref}>{ref}</li>)}</ul></div>}
|
||||
</Modal>
|
||||
</article>;
|
||||
}
|
||||
|
||||
/** 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, hideEvidence = false, combineStages = true }: AnalysisVisualsProps) {
|
||||
const parsed = useMemo(() => {
|
||||
const result = parseAnalysisVisuals(visuals);
|
||||
return { ...result, visuals: combineStageDefectVisuals(result.visuals) };
|
||||
}, [visuals]);
|
||||
return { ...result, visuals: combineStages ? combineStageDefectVisuals(result.visuals) : result.visuals };
|
||||
}, [visuals, combineStages]);
|
||||
if (!parsed.visuals.length) {
|
||||
const state = visualStateName(visualState);
|
||||
if (state === 'building') return <div className="analysis-visual-state" role="status">图表整理中</div>;
|
||||
@@ -328,7 +386,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} />)}
|
||||
{parsed.visuals.map(visual => <AnalysisVisualCard key={visual.id} visual={visual} beforeExport={beforeExport} hideEvidence={hideEvidence} />)}
|
||||
</section>;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { isInternalDataField, readableMetricFormula } from './publicDataDisplay';
|
||||
|
||||
const labels: Record<string, string> = {
|
||||
period: '期间', department: '产业部', group: '业务分组', product: '产品', projectGroup: '项目组',
|
||||
qualified: '合格重量', scrap: '报废重量', total: '总重量', qualifiedWeight: '合格重量', scrapWeight: '报废重量', totalWeight: '总重量',
|
||||
black_good_weight: '黑片合格重量', black_scrap_weight: '黑片报废重量', black_total_weight: '黑片总重量',
|
||||
bright_good_weight: '亮片合格重量', bright_scrap_weight: '亮片报废重量', bright_total_weight: '亮片总重量',
|
||||
black_responsibility_scrap: '黑片责废重量', black_material_scrap: '黑片料废重量', black_external_scrap: '黑片外废重量',
|
||||
black_reuse_good: '利用料及废品库合格扣减', black_reuse_scrap: '利用料及废品库报废扣减',
|
||||
bright_headquarters_scrap: '亮片本部报废重量', bright_plating_scrap: '亮片镀废重量', bright_processing_scrap: '亮片加工废重量', bright_material_scrap: '亮片材料废重量', bright_diffusion_scrap: '亮片扩散废重量',
|
||||
sourceFields: '来源字段', rowRules: '逐行计算', metricRules: '指标公式', stage: '阶段', target: '计算分量', formula: '计算公式',
|
||||
when: '适用条件', field: '条件字段', operator: '判断方式', value: '条件值', otherwiseFormula: '其他情况公式',
|
||||
nullPolicy: '运算空值处理', zeroDenominatorPolicy: '零分母处理', nullResultPolicy: '空结果处理',
|
||||
black: '黑片', bright: '亮片', name: '名称', enabled: '状态', monthKey: '月份', projectGroupStatus: '项目组归属状态',
|
||||
sourcePdtCode: 'PDT代码', sourceSalesRegion: '销售片区', sourceCustomerCode: '客户代码', categoryMappingStatus: '业务分组匹配状态',
|
||||
PROPAGATE: '任一输入为空则结果为空', ZERO: '按0处理', IGNORE: '忽略空值', ONE: '返回1', NULL: '保留空值', ERROR: '停止并报错',
|
||||
EQ: '等于', NE: '不等于', CONTAINS: '包含', NOT_CONTAINS: '不包含', IS_BLANK: '为空', IS_NOT_BLANK: '不为空', GT: '大于', GTE: '大于等于', LT: '小于', LTE: '小于等于',
|
||||
mapped: '已匹配', mapped_null: '已匹配(归属为空)', unmapped: '未匹配', unconfigured: '未配置', source_key_blank: '来源匹配字段为空', READY: '已配置', MAPPED: '已匹配', UNMAPPED: '未匹配', UNCONFIGURED: '未配置',
|
||||
};
|
||||
export function businessLabel(value: string): string {
|
||||
return labels[value] || readableMetricFormula(value);
|
||||
}
|
||||
export function BusinessValue({ value, field }: { value: unknown; field?: string }) {
|
||||
if (value === undefined || value === null || value === '') return <>—</>;
|
||||
if (typeof value === 'boolean') return <>{value ? '已启用' : '已停用'}</>;
|
||||
if (Array.isArray(value)) return value.every(item => typeof item !== 'object')
|
||||
? <>{value.map(item => field === 'dimensions' ? businessLabel(String(item)) : String(item)).join('、') || '—'}</>
|
||||
: <div>{value.map((item, index) => <div key={index} style={{ marginBottom: 12 }}><BusinessValue value={item} field={field} /></div>)}</div>;
|
||||
if (typeof value === 'object') {
|
||||
const entries = Object.entries(value).filter(([key]) => !isInternalDataField(key));
|
||||
return entries.length ? <dl className="basis-details">{entries.map(([key, child]) => <div key={key} style={{ display: 'contents' }}><dt>{businessLabel(key)}</dt><dd><BusinessValue value={child} field={key} /></dd></div>)}</dl> : <>暂无单独配置</>;
|
||||
}
|
||||
return <>{typeof value === 'string' ? ['formula', 'otherwiseFormula'].includes(field || '') ? readableMetricFormula(value) : ['stage', 'target', 'nullPolicy', 'nullResultPolicy', 'zeroDenominatorPolicy', 'operator', 'projectGroupStatus', 'categoryMappingStatus'].includes(field || '') ? businessLabel(value) : value : String(value)}</>;
|
||||
}
|
||||
export function currentMetricFormula(row: Record<string, unknown>): string {
|
||||
if (row.formulaStatus === 'NO_CURRENT_DATA') return '暂无已生效数据';
|
||||
return row.formulaStatus === 'CURRENT' && typeof row.currentFormula === 'string' && row.currentFormula.trim()
|
||||
? readableMetricFormula(row.currentFormula) : '当前生效公式暂不可用,请刷新重试';
|
||||
}
|
||||
@@ -6,8 +6,9 @@ import type { PageKey } from './QualityWorkspace';
|
||||
import { PageCacheContext, WORKSPACE_INVALIDATED } from './pageCache';
|
||||
|
||||
const QueryPage = lazy(() => import('./QueryPage'));
|
||||
const StageProductPage = lazy(() => import('./StageProductPage'));
|
||||
const ManagementPages = lazy(() => import('./ManagementPages'));
|
||||
const QUERY_PAGES: PageKey[] = ['overall', 'department', 'group', 'product'];
|
||||
const QUERY_PAGES: PageKey[] = ['overall', 'department', 'group', 'product', 'blackProduct', 'brightProduct'];
|
||||
const retained = (page: PageKey) => QUERY_PAGES.includes(page) || page === 'analysis';
|
||||
type ResultRef = { kind: 'TOP'; resultId: string; releaseId: string };
|
||||
type Entry = { initialSearch: string; search: string; key: number; scroll: number };
|
||||
@@ -103,7 +104,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
return <div key={`${name}-${entry.key}`} className="page-view" data-page={name} hidden={!active} style={!active ? { display: 'none' } : undefined}>
|
||||
<PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey, onLocationChange: search => { entry.search = search; } }}>
|
||||
<Suspense fallback={<div className="loading-panel"><Spin />正在打开页面…</div>}>
|
||||
{QUERY_PAGES.includes(name) ? <QueryPage page={name} onUnauthorized={onUnauthorized} onNavigate={navigate} /> : <ManagementPages page={name} user={user} onUnauthorized={onUnauthorized} onNavigate={navigate} />}
|
||||
{name === 'blackProduct' || name === 'brightProduct' ? <StageProductPage stage={name === 'blackProduct' ? 'black' : 'bright'} onUnauthorized={onUnauthorized} /> : QUERY_PAGES.includes(name) ? <QueryPage page={name} onUnauthorized={onUnauthorized} onNavigate={navigate} /> : <ManagementPages page={name} user={user} onUnauthorized={onUnauthorized} onNavigate={navigate} />}
|
||||
</Suspense>
|
||||
</PageCacheContext.Provider>
|
||||
</div>;
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Tooltip } from 'antd';
|
||||
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||
|
||||
/** The complaint ledger's single-line preview and hover/focus full-text treatment. */
|
||||
export function CompactTableCell({ children }: { children: ReactNode }) {
|
||||
const host = useRef<HTMLSpanElement>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [preview, setPreview] = useState({ interactive: false, overflow: false, text: '' });
|
||||
useLayoutEffect(() => {
|
||||
const node = host.current;
|
||||
if (!node) return;
|
||||
const measure = () => {
|
||||
const editor = node.querySelector<HTMLInputElement | HTMLTextAreaElement>('input:not([type="checkbox"]):not([type="radio"]),textarea');
|
||||
const linkText = node.querySelector<HTMLElement>(':scope > .ant-btn-link > span:not(.ant-btn-icon), :scope > a');
|
||||
const interactive = !!node.querySelector('input,textarea,button,a,select,[role="button"],[role="combobox"],[role="checkbox"],[role="switch"],[role="progressbar"]');
|
||||
const text = editor?.value || node.innerText || node.textContent || '';
|
||||
const overflow = editor ? editor.scrollWidth > editor.clientWidth || editor.scrollHeight > editor.clientHeight
|
||||
: linkText ? linkText.scrollWidth > linkText.clientWidth
|
||||
: !interactive && (node.scrollWidth > node.clientWidth || node.scrollHeight > node.clientHeight);
|
||||
if (editor && overflow && node.contains(document.activeElement)) setOpen(true);
|
||||
setPreview(previous => previous.interactive === interactive && previous.overflow === overflow && previous.text === text
|
||||
? previous : { interactive, overflow, text });
|
||||
};
|
||||
measure();
|
||||
const resize = new ResizeObserver(measure);
|
||||
resize.observe(node);
|
||||
const mutation = new MutationObserver(measure);
|
||||
mutation.observe(node, { childList: true, characterData: true, subtree: true });
|
||||
node.addEventListener('input', measure);
|
||||
return () => { resize.disconnect(); mutation.disconnect(); node.removeEventListener('input', measure); };
|
||||
}, [children]);
|
||||
|
||||
return <Tooltip open={preview.overflow && open} onOpenChange={setOpen}
|
||||
title={preview.overflow && preview.text ? <div className="quality-cell-fulltext">{preview.text}</div> : undefined}
|
||||
trigger={['hover', 'focus']} placement="topLeft" styles={{ root: { maxWidth: 'min(460px, calc(100vw - 24px))', pointerEvents: 'auto' } }}>
|
||||
<span ref={host} className={`quality-cell-preview${preview.interactive ? ' quality-cell-interactive' : ''}${preview.overflow ? ' quality-cell-overflow' : ''}`}
|
||||
tabIndex={preview.overflow && !preview.interactive ? 0 : undefined} onKeyDown={event => { if (event.key === 'Escape') setOpen(false); }}>{children}</span>
|
||||
</Tooltip>;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Alert, App, Button, Checkbox, Input, Select, Space, Table } from 'antd';
|
||||
import { Alert, App, Button, Checkbox, Input, Select, Space } from 'antd';
|
||||
import { QualityTable as Table } from './QualityTable';
|
||||
import { PlusOutlined } from '@ant-design/icons';
|
||||
import { api } from './api';
|
||||
import type { FilterField } from './types';
|
||||
@@ -28,15 +29,15 @@ export function FilterFieldSettings({ canManage, onUnauthorized }: { canManage:
|
||||
finally { setSaving(false); }
|
||||
};
|
||||
return <section className="panel filter-field-settings">
|
||||
<div className="section-heading-row"><strong>筛选字段</strong>{canManage && <Space><Button icon={<PlusOutlined />} disabled={loading || saving || fields.length >= 20} onClick={() => { setFields(items => [...items, { key: `field_${Date.now().toString(36)}`, label: '', blackColumn: '', brightColumn: '', enabled: true, allowEmpty: true, sortOrder: items.length }]); setDirty(true); }}>新增字段</Button><Button type="primary" loading={saving} disabled={!dirty || loading || fields.some(f => !f.label.trim() || !f.blackColumn || !f.brightColumn)} onClick={() => void save()}>保存筛选字段</Button></Space>}</div>
|
||||
<div className="section-heading-row"><strong>筛选字段</strong>{canManage && <Space size={6}><Button size="small" icon={<PlusOutlined />} disabled={loading || saving || fields.length >= 20} onClick={() => { setFields(items => [...items, { key: `field_${Date.now().toString(36)}`, label: '', blackColumn: '', brightColumn: '', enabled: true, allowEmpty: true, sortOrder: items.length }]); setDirty(true); }}>新增字段</Button><Button size="small" type="primary" loading={saving} disabled={!dirty || loading || fields.some(f => !f.label.trim() || !f.blackColumn || !f.brightColumn)} onClick={() => void save()}>保存筛选字段</Button></Space>}</div>
|
||||
<p>配置后可在查询页面的“更多筛选”中使用。黑片、亮片按各自来源列筛选,支持搜索、多选和空值;代码按文本保留。</p>
|
||||
{error && <Alert type="error" showIcon message={error} action={<Button onClick={() => setRevision(n => n + 1)}>重新加载</Button>} />}
|
||||
<Table rowKey="key" loading={loading} dataSource={fields} pagination={false} scroll={{ x: 780 }} columns={[
|
||||
{ title: '筛选名称', key: 'label', width: 180, render: (_, f) => <Input aria-label={`筛选名称 ${f.key}`} value={f.label} maxLength={80} disabled={!canManage || saving} onChange={e => update(f.key, { label: e.target.value })} /> },
|
||||
...(['black', 'bright'] as const).map(stage => ({ title: stage === 'black' ? '黑片来源列' : '亮片来源列', key: stage, width: 240, render: (_: unknown, f: FilterField) => <Select aria-label={`${stage === 'black' ? '黑片' : '亮片'}来源列 ${f.key}`} showSearch optionFilterProp="label" style={{ width: '100%' }} value={f[stage === 'black' ? 'blackColumn' : 'brightColumn'] || undefined} disabled={!canManage || saving} placeholder="选择来源列" options={[...new Set([...columns[stage], f[stage === 'black' ? 'blackColumn' : 'brightColumn']].filter(Boolean))].map(v => ({ label: v, value: v }))} onChange={v => update(f.key, { [stage === 'black' ? 'blackColumn' : 'brightColumn']: v })} /> })),
|
||||
<Table size="small" rowKey="key" loading={loading} dataSource={fields} pagination={false} scroll={{ x: 988 }} columns={[
|
||||
{ title: '筛选名称', key: 'label', width: 180, render: (_, f) => <Input size="small" aria-label={`筛选名称 ${f.key}`} value={f.label} maxLength={80} disabled={!canManage || saving} onChange={e => update(f.key, { label: e.target.value })} /> },
|
||||
...(['black', 'bright'] as const).map(stage => ({ title: stage === 'black' ? '黑片来源列' : '亮片来源列', key: stage, width: 240, render: (_: unknown, f: FilterField) => <Select size="small" aria-label={`${stage === 'black' ? '黑片' : '亮片'}来源列 ${f.key}`} showSearch optionFilterProp="label" style={{ width: '100%' }} value={f[stage === 'black' ? 'blackColumn' : 'brightColumn'] || undefined} disabled={!canManage || saving} placeholder="选择来源列" options={[...new Set([...columns[stage], f[stage === 'black' ? 'blackColumn' : 'brightColumn']].filter(Boolean))].map(v => ({ label: v, value: v }))} onChange={v => update(f.key, { [stage === 'black' ? 'blackColumn' : 'brightColumn']: v })} /> })),
|
||||
{ title: '允许空值', key: 'empty', width: 100, render: (_, f) => <Checkbox aria-label={`允许空值 ${f.label || f.key}`} checked={f.allowEmpty} disabled={!canManage || saving} onChange={e => update(f.key, { allowEmpty: e.target.checked })} /> },
|
||||
{ title: '启用', key: 'enabled', width: 80, render: (_, f) => <Checkbox aria-label={`启用 ${f.label || f.key}`} checked={f.enabled} disabled={!canManage || saving} onChange={e => update(f.key, { enabled: e.target.checked })} /> },
|
||||
...(canManage ? [{ title: '操作', key: 'actions', width: 80, render: (_: unknown, f: FilterField) => <Button type="link" danger disabled={saving} onClick={() => { setFields(items => items.filter(item => item.key !== f.key)); setDirty(true); }}>移除</Button> }] : []),
|
||||
...(canManage ? [{ title: '操作', key: 'actions', width: 80, render: (_: unknown, f: FilterField) => <Button size="small" type="link" danger disabled={saving} onClick={() => { setFields(items => items.filter(item => item.key !== f.key)); setDirty(true); }}>移除</Button> }] : []),
|
||||
]} />
|
||||
</section>;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { configurationDateTime } from './configurationName';
|
||||
import { alertObject, alertsForStatus, monitorLabel } from './taskMonitorModel';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Checkbox, Drawer, Empty, Form, Input, InputNumber, Modal, Select, Spin, Switch, Tabs, Tag } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { QualityTable as Table } from './QualityTable';
|
||||
@@ -495,11 +497,18 @@ export function BackupOperationsPanel({ user, onUnauthorized, onNavigate }: { us
|
||||
};
|
||||
const plan = obj(data?.plan); const backups = rows(data?.items);
|
||||
const columns: ColumnsType<Row> = [
|
||||
{ title: '备份时间', dataIndex: 'createdAt', key: 'createdAt', fixed: 'left', width: 190 },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 130, render: value => <Tag>{text(value)}</Tag> },
|
||||
{ title: '备份时间', dataIndex: 'createdAt', key: 'createdAt', fixed: 'left', width: 190, render: value => configurationDateTime(value) || '—' },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 150, render: value => <Tag>{monitorLabel(value,'状态待确认')}</Tag> },
|
||||
|
||||
{ title: '恢复验证时间', dataIndex: 'restoreVerifiedAt', key: 'restoreVerifiedAt', width: 190 },
|
||||
{ title: '还原用时', dataIndex: 'restoreElapsedSeconds', key: 'restoreElapsedSeconds', width: 110 },
|
||||
{ title: '恢复验证时间', dataIndex: 'restoreVerifiedAt', key: 'restoreVerifiedAt', width: 190, render: value => configurationDateTime(value) || '—' },
|
||||
{ title: '还原用时(秒)', dataIndex: 'restoreElapsedSeconds', key: 'restoreElapsedSeconds', width: 110 },
|
||||
{ title: '验证范围', key: 'verification', width: 210, render: (_, row) => {
|
||||
const verified = obj(row.verification);
|
||||
const checks = [['databaseRestoreVerified', '数据库恢复'], ['archiveFilesVerified', '来源文件'],
|
||||
['archiveReferencesVerified', '来源路径'], ['applicationFilesVerified', '应用文件'],
|
||||
['requiredApplicationInputsVerified', '构建输入'], ['applicationStartupVerified', '应用启动']];
|
||||
return <details><summary>查看分项</summary>{checks.map(([key, label]) => <div key={key}>{label}:{verified[key] === true ? '已验证' : '未验证'}</div>)}</details>;
|
||||
} },
|
||||
{ title: '操作', key: 'action', width: 130, render: (_, row) => <Button type="link" loading={busy} onClick={() => void runJob('BACKUP_VERIFY', String(row.id))}>复核备份</Button> },
|
||||
];
|
||||
return <section className="panel section-panel completion-tools">
|
||||
@@ -519,6 +528,7 @@ export function OperationsMonitorPanel({ user, onUnauthorized }: { user: AuthUse
|
||||
const [error, setError] = useState('');
|
||||
const [alertPolicy, setAlertPolicy] = useState<Row | null>(null);
|
||||
const [policyOpen, setPolicyOpen] = useState(false);
|
||||
const [alertStatus, setAlertStatus] = useState('OPEN');
|
||||
const [policyBusy, setPolicyBusy] = useState(false);
|
||||
const [policyError, setPolicyError] = useState('');
|
||||
const [policyForm] = Form.useForm<Row>();
|
||||
@@ -551,21 +561,23 @@ export function OperationsMonitorPanel({ user, onUnauthorized }: { user: AuthUse
|
||||
};
|
||||
const refresh = async () => {
|
||||
setRefreshing(true);
|
||||
try { const result = await api.refreshGovernanceMonitor(); setData(result); message.success('平台内巡检已完成'); setError(''); }
|
||||
try { const result = await api.refreshGovernanceMonitor(); setData(result); message.success('系统健康检查已完成'); setError(''); }
|
||||
catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '巡检失败'); }
|
||||
finally { setRefreshing(false); }
|
||||
};
|
||||
const summary = obj(data?.summary);
|
||||
const summaryEntries = Object.entries(summary).filter(([, value]) => ['string', 'number', 'boolean'].includes(typeof value));
|
||||
const alertRows = rows(data?.alerts);
|
||||
const allAlerts = rows(data?.alerts);
|
||||
const alertRows = alertsForStatus(allAlerts, alertStatus);
|
||||
const summaryLabels: Record<string,string> = {queuedTasks:'排队任务',runningTasks:'运行中任务',failedTasks:'失败任务',sourceAttention:'待处理来源',failedAnalysisTurns:'失败分析',openAlerts:'当前告警'};
|
||||
const requestMetricRows = rows(data?.requestMetrics);
|
||||
const alertColumns: ColumnsType<Row> = [
|
||||
{ title: '级别', dataIndex: 'severity', key: 'severity', width: 100, render: value => <Tag color={String(value).toUpperCase().includes('CRIT') || String(value).toUpperCase().includes('ERROR') ? 'red' : 'gold'}>{text(value)}</Tag> },
|
||||
{ title: '告警', dataIndex: 'title', key: 'title', width: 230, render: (_, row) => text(row.title || row.code) },
|
||||
{ title: '级别', dataIndex: 'severity', key: 'severity', width: 100, render: value => <Tag color={String(value).toUpperCase().includes('CRIT') || String(value).toUpperCase().includes('ERROR') ? 'red' : 'gold'}>{({INFO:'提示',WARNING:'警告',ERROR:'错误',CRITICAL:'严重'} as Record<string,string>)[String(value)] || '未知级别'}</Tag> },
|
||||
{ title: '告警', dataIndex: 'title', key: 'title', width: 230, render: (_, row) => monitorLabel(row.alertType,'平台告警') },
|
||||
{ title: '说明', dataIndex: 'message', key: 'message', width: 430 },
|
||||
{ title: '对象', key: 'target', width: 210, render: (_, row) => `${text(row.targetType)} · ${text(row.targetId)}` },
|
||||
{ title: '时间', dataIndex: 'createdAt', key: 'createdAt', width: 190 },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 120 },
|
||||
{ title: '对象', key: 'target', width: 210, render: (_, row) => alertObject(row) },
|
||||
{ title: alertStatus === 'RECOVERED' ? '恢复时间' : '最近发生', key: 'alertTime', width: 190, render: (_,row) => configurationDateTime(alertStatus === 'RECOVERED' ? row.recoveredAt : row.lastSeen) || '—' },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 120, render: (value,row) => <><Tag color={value === 'RECOVERED' ? 'green' : 'orange'}>{monitorLabel(value)}</Tag>{value === 'OPEN' && row.silenced === true && <Tag>静默中</Tag>}</> },
|
||||
];
|
||||
const requestMetricColumns: ColumnsType<Row> = [
|
||||
{ title: '路由', dataIndex: 'routePattern', key: 'routePattern', fixed: 'left', width: 280 },
|
||||
@@ -575,15 +587,15 @@ export function OperationsMonitorPanel({ user, onUnauthorized }: { user: AuthUse
|
||||
{ title: '慢请求数', dataIndex: 'slowCount', key: 'slowCount', align: 'right', width: 110 },
|
||||
{ title: '累计耗时 / ms', dataIndex: 'totalElapsedMillis', key: 'totalElapsedMillis', align: 'right', width: 140 },
|
||||
{ title: '最长耗时 / ms', dataIndex: 'maxElapsedMillis', key: 'maxElapsedMillis', align: 'right', width: 140 },
|
||||
{ title: '最近请求', dataIndex: 'lastSeen', key: 'lastSeen', width: 190 },
|
||||
{ title: '最近请求', dataIndex: 'lastSeen', key: 'lastSeen', width: 190, render: value => configurationDateTime(value) || '—' },
|
||||
];
|
||||
return <>
|
||||
<section className="panel section-panel governance-monitor">
|
||||
<div className="completion-panel-heading"><div><strong>运行指标、平台内告警与巡检</strong><span>只读取并更新服务端运行状态;不发送外部通知</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新</Button>{canRefresh && <><Button onClick={() => void editPolicy()} disabled={!alertPolicy}>告警阈值</Button><Button type="primary" loading={refreshing} onClick={() => void refresh()}>执行巡检</Button></>}</div></div>
|
||||
<div className="completion-panel-heading"><div><strong>运行监控与告警</strong><span>只读取并更新服务端运行状态;不发送外部通知</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新</Button>{canRefresh && <><Button onClick={() => void editPolicy()} disabled={!alertPolicy}>告警阈值</Button><Button type="primary" loading={refreshing} onClick={() => void refresh()}>系统健康检查</Button></>}</div></div>
|
||||
{error && <Alert showIcon type="error" message="运行监控暂不可用" description={error} />}
|
||||
{policyError && <Alert showIcon type="error" message="告警策略不可用" description={policyError} />}
|
||||
{loading ? <div className="completion-loading"><Spin />读取平台状态…</div> : <><div className="governance-monitor-grid">{summaryEntries.length ? summaryEntries.map(([key, value]) => <div key={key}><small>{key}</small><strong>{text(value)}</strong></div>) : <div className="completion-placeholder">服务端没有返回运行指标</div>}</div>{alertRows.length ? <Table size="small" bordered columns={alertColumns} dataSource={alertRows} rowKey={row => String(row.id || row.code)} pagination={{ pageSize: 10, showSizeChanger: false }} scroll={{ x: 1260 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有平台内告警" />}</>}
|
||||
<h3>接口请求指标</h3><p className="completion-note">按路由聚合请求数、失败数与耗时;服务端不保存请求正文。</p>
|
||||
{loading ? <div className="completion-loading"><Spin />读取平台状态…</div> : <><div className="governance-monitor-grid">{summaryEntries.length ? summaryEntries.map(([key, value]) => <div key={key}><small>{summaryLabels[key] || '其他指标'}</small><strong>{text(value)}</strong></div>) : <div className="completion-placeholder">服务端没有返回运行指标</div>}</div><Tabs activeKey={alertStatus} onChange={setAlertStatus} items={[{key:'OPEN',label:`当前告警(${alertsForStatus(allAlerts,'OPEN').length})`},{key:'RECOVERED',label:`已恢复(${alertsForStatus(allAlerts,'RECOVERED').length})`}]}/>{alertRows.length ? <Table size="small" bordered columns={alertColumns} dataSource={alertRows} rowKey={row => String(row.id || row.code)} pagination={{ pageSize: 10, showSizeChanger: false }} scroll={{ x: 1260 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={alertStatus === 'OPEN' ? '当前没有未恢复告警' : '暂无已恢复告警'} />}</>}
|
||||
<h3>接口请求指标</h3><p className="completion-note">累计请求数、失败数与耗时;最近请求时间不代表统计起点。</p>
|
||||
{loading ? <div className="completion-loading"><Spin />读取接口指标…</div> : requestMetricRows.length ? <Table size="small" bordered columns={requestMetricColumns} dataSource={requestMetricRows} rowKey={row => `${text(row.routePattern)}-${text(row.method)}`} pagination={{ pageSize: 12, showSizeChanger: false }} scroll={{ x: 1200 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端尚未记录接口请求指标" />}
|
||||
<Modal className="management-modal" open={policyOpen} title="告警阈值与静默策略" okText="保存策略" confirmLoading={policyBusy} onCancel={() => setPolicyOpen(false)} onOk={() => void savePolicy()}><Form form={policyForm} layout="vertical"><div className="governance-form-grid"><Form.Item name="queueAgeMinutes" label="队列告警(分钟)" rules={[{ required: true }]}><InputNumber min={1} max={1440} /></Form.Item><Form.Item name="diskFreeBytes" label="最低可用磁盘空间(字节)" rules={[{ required: true }]}><InputNumber min={104857600} max={1125899906842624} style={{ width: '100%' }} /></Form.Item><Form.Item name="backupAgeHours" label="备份超时(小时)" rules={[{ required: true }]}><InputNumber min={1} max={720} /></Form.Item><Form.Item name="quietPeriodMinutes" label="重复告警静默(分钟)" rules={[{ required: true }]}><InputNumber min={0} max={10080} /></Form.Item><Form.Item name="slowRequestMillis" label="慢请求阈值(毫秒)" rules={[{ required: true }]}><InputNumber min={100} max={120000} /></Form.Item><Form.Item name="silenceUntil" label="临时静默截止(ISO,可选)"><Input placeholder="2026-10-21T09:00:00Z" /></Form.Item></div><Form.Item name="severityOverrides" label="告警严重度覆盖(JSON)" rules={[{ required: true }]}><Input.TextArea rows={5} spellCheck={false} /></Form.Item><Form.Item name="reason" label="修改原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} /></Form.Item><p className="completion-note">保存后按新策略检查;严重度 key 只能使用服务端列出的告警类型。</p></Form></Modal>
|
||||
</section>
|
||||
@@ -692,32 +704,68 @@ export function UserAccessPolicyPanel({ onUnauthorized }: { onUnauthorized: (err
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [form] = Form.useForm<Row>();
|
||||
const selectedUser = useRef<string | undefined>(undefined);
|
||||
const policyGeneration = useRef(0);
|
||||
const savingRef = useRef(false);
|
||||
const mounted = useRef(true);
|
||||
const selectUser = (id: string) => {
|
||||
if (savingRef.current) return;
|
||||
selectedUser.current = id; policyGeneration.current++;
|
||||
setUserId(id); setPolicy(null); form.resetFields();
|
||||
setEffective(null); setScopePreview(null); setPreviewBusy(false); setError('');
|
||||
setLoading(true);
|
||||
};
|
||||
const userOptions = users.map(item => ({ label: `${text(item.displayName || item.username)} · ${text(item.username)}`, value: String(item.id) })).filter(item => item.value);
|
||||
const load = async (id: string) => {
|
||||
const generation = ++policyGeneration.current;
|
||||
const current = () => mounted.current && selectedUser.current === id && policyGeneration.current === generation;
|
||||
if (selectedUser.current !== id) return;
|
||||
setLoading(true);
|
||||
try { const result = await api.userAccessPolicy(id); const value = obj(result.policy || result); setPolicy(value); form.setFieldsValue({ detailAllowed: value.detailAllowed === true, evidenceAllowed: value.evidenceAllowed === true, originalDownloadAllowed: value.originalDownloadAllowed === true, inheritDepartmentChildren: value.inheritDepartmentChildren === true, allowedFields: Array.isArray(value.allowedFields) ? value.allowedFields.join('\n') : '*', validUntil: text(value.validUntil, ''), reason: '' }); setError(''); }
|
||||
catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '访问策略读取失败'); }
|
||||
finally { setLoading(false); }
|
||||
setPolicy(null); form.resetFields();
|
||||
try {
|
||||
const result = await api.userAccessPolicy(id);
|
||||
if (!current()) return;
|
||||
const value = obj(result.policy || result);
|
||||
if (value.userId !== id) throw new Error('访问策略与当前用户不匹配,请重新选择用户。');
|
||||
setPolicy(value); form.setFieldsValue({ detailAllowed: value.detailAllowed === true, evidenceAllowed: value.evidenceAllowed === true, originalDownloadAllowed: value.originalDownloadAllowed === true, inheritDepartmentChildren: value.inheritDepartmentChildren === true, allowedFields: Array.isArray(value.allowedFields) ? value.allowedFields.join('\n') : '*', validUntil: text(value.validUntil, ''), reason: '' }); setError('');
|
||||
} catch (value) { if (!onUnauthorized(value) && current()) setError(value instanceof Error ? value.message : '访问策略读取失败'); }
|
||||
finally { if (current()) setLoading(false); }
|
||||
};
|
||||
useEffect(() => {
|
||||
api.users().then(value => setUsers(collectionItems(value))).catch(errorValue => { if (!onUnauthorized(errorValue)) setError(errorValue instanceof Error ? errorValue.message : '用户列表读取失败'); });
|
||||
mounted.current = true;
|
||||
api.users().then(value => { if (mounted.current) setUsers(collectionItems(value)); }).catch(errorValue => { if (!onUnauthorized(errorValue) && mounted.current) setError(errorValue instanceof Error ? errorValue.message : '用户列表读取失败'); });
|
||||
return () => { mounted.current = false; policyGeneration.current++; };
|
||||
}, []);
|
||||
useEffect(() => { if (userId) void load(userId); else setPolicy(null); }, [userId]);
|
||||
const save = async () => {
|
||||
if (!userId || !policy) return;
|
||||
try { const value = await form.validateFields(); setSaving(true); const allowedFields = String(value.allowedFields || '').split(/[\n,,]/).map(item => item.trim()).filter(Boolean); await api.updateUserAccessPolicy(userId, { detailAllowed: value.detailAllowed === true, evidenceAllowed: value.evidenceAllowed === true, originalDownloadAllowed: value.originalDownloadAllowed === true, inheritDepartmentChildren: value.inheritDepartmentChildren === true, allowedFields, validUntil: value.validUntil || null, reason: String(value.reason || '').trim(), expectedRowVersion: Number(policy.rowVersion || 0) }); message.success('明细、证据及组织范围策略已更新'); await load(userId); }
|
||||
catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '授权策略已被更新,请重新读取。' : value instanceof Error ? value.message : '策略保存失败'); }
|
||||
finally { setSaving(false); }
|
||||
const id = selectedUser.current;
|
||||
if (!id || !policy || policy.userId !== id || loading || savingRef.current) return;
|
||||
const generation = policyGeneration.current;
|
||||
const current = () => mounted.current && selectedUser.current === id && policyGeneration.current === generation;
|
||||
savingRef.current = true; setSaving(true);
|
||||
try {
|
||||
const value = await form.validateFields();
|
||||
if (!current()) return;
|
||||
const allowedFields = String(value.allowedFields || '').split(/[\n,,]/).map(item => item.trim()).filter(Boolean);
|
||||
await api.updateUserAccessPolicy(id, { detailAllowed: value.detailAllowed === true, evidenceAllowed: value.evidenceAllowed === true, originalDownloadAllowed: value.originalDownloadAllowed === true, inheritDepartmentChildren: value.inheritDepartmentChildren === true, allowedFields, validUntil: value.validUntil || null, reason: String(value.reason || '').trim(), expectedRowVersion: Number(policy.rowVersion || 0) });
|
||||
if (!current()) return;
|
||||
message.success('明细、证据及组织范围策略已更新'); await load(id);
|
||||
} catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value) && current()) message.error(value instanceof ApiError && value.status === 409 ? '授权策略已被更新,请重新读取。' : value instanceof Error ? value.message : '策略保存失败'); }
|
||||
finally { savingRef.current = false; if (mounted.current) setSaving(false); }
|
||||
};
|
||||
const preview = async (kind: 'effective' | 'scope') => {
|
||||
if (!userId) return; setPreviewBusy(true);
|
||||
try { const result = kind === 'effective' ? await api.effectiveUserAccess(userId) : await api.userScopePreview(userId); if (kind === 'effective') setEffective(result); else setScopePreview(result); }
|
||||
catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '用户有效授权读取失败'); }
|
||||
finally { setPreviewBusy(false); }
|
||||
const id = selectedUser.current;
|
||||
if (!id || loading || savingRef.current || previewBusy) return;
|
||||
const generation = policyGeneration.current;
|
||||
const current = () => mounted.current && selectedUser.current === id && policyGeneration.current === generation;
|
||||
setPreviewBusy(true);
|
||||
try { const result = kind === 'effective' ? await api.effectiveUserAccess(id) : await api.userScopePreview(id); if (!current()) return; if (kind === 'effective') setEffective(result); else setScopePreview(result); }
|
||||
catch (value) { if (!onUnauthorized(value) && current()) message.error(value instanceof Error ? value.message : '用户有效授权读取失败'); }
|
||||
finally { if (current()) setPreviewBusy(false); }
|
||||
};
|
||||
const scopeCounts = rows(scopePreview?.counts);
|
||||
const effectiveDepartments = Array.isArray(effective?.departments) ? effective.departments.map(String).join('、') : '—';
|
||||
const grantedDepartments = Array.isArray(effective?.grantedDepartments) ? effective.grantedDepartments.map(String).join('、') : '—';
|
||||
const hierarchyRows = rows(effective?.hierarchySource);
|
||||
return <div className="governance-panel-body"><div className="completion-panel-heading"><div><strong>用户明细与证据访问策略</strong><span>明细、原文件下载与字段授权由服务端二次校验</span></div><div className="completion-actions"><Button disabled={!userId} loading={previewBusy} onClick={() => void preview('effective')}>预览有效授权</Button><Button disabled={!userId} loading={previewBusy} onClick={() => void preview('scope')}>预览授权行数</Button></div></div><div className="governance-policy-select"><Select showSearch optionFilterProp="label" placeholder="选择用户" value={userId} options={userOptions} onChange={value => { setUserId(value); setEffective(null); setScopePreview(null); }} /></div>{error && <Alert showIcon type="error" message="访问策略不可用" description={error} />}{loading ? <div className="completion-loading"><Spin />读取访问策略…</div> : policy && <Form form={form} layout="vertical" className="governance-policy-form"><div className="governance-form-grid"><Form.Item name="detailAllowed" label="允许读取来源明细" valuePropName="checked"><Switch /></Form.Item><Form.Item name="evidenceAllowed" label="允许查看来源变更证据" valuePropName="checked"><Switch /></Form.Item><Form.Item name="originalDownloadAllowed" label="允许下载原始文件" valuePropName="checked"><Switch /></Form.Item><Form.Item name="inheritDepartmentChildren" label="继承下级产业部范围" valuePropName="checked"><Switch /></Form.Item><Form.Item name="validUntil" label="授权有效截止时间(ISO,可选)"><Input placeholder="2026-12-31T23:59:59Z" /></Form.Item></div><Form.Item name="allowedFields" label="允许字段(每行一个;* 表示全部已授权字段)"><Input.TextArea rows={5} spellCheck={false} /></Form.Item><Form.Item name="reason" label="修改原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item><Button type="primary" loading={saving} onClick={() => void save()}>保存访问策略</Button><p className="completion-note">空字段集合将由服务端按其默认策略处理。</p></Form>}{effective && <section className="completion-insight-card"><div className="completion-card-heading"><strong>服务端有效授权</strong><Tag color={effective.authorizationEffective === true ? 'green' : 'red'}>{effective.authorizationEffective === true ? '有效' : '未生效'}</Tag></div><p>用户 {text(effective.userId)} · 身份 {effective.active === true ? '启用' : '停用'} · 数据范围已由服务端核验</p><p>角色:{Array.isArray(effective.roles) ? (effective.roles as unknown[]).map(String).join('、') : '—'}</p><p>原始授权产业部:{grantedDepartments} · 有效产业部:{effectiveDepartments}</p><p>业务分组:{Array.isArray(effective.groups) ? (effective.groups as unknown[]).map(String).join('、') : '—'}</p><p>动作:{Array.isArray(effective.allowedActions) ? (effective.allowedActions as unknown[]).map(String).join('、') : '—'}</p><p>字段策略:{JSON.stringify(withoutSystemMetadata(effective.fieldPolicy ?? {}))}</p>{hierarchyRows.length > 0 && <p>层级展开依据:当前映射配置</p>}</section>}{scopePreview && <section className="completion-insight-card"><div className="completion-card-heading"><strong>授权范围行数</strong><Tag>{scopePreview.dataReturned === false ? '仅计数,未返回数据' : '服务端返回状态'}</Tag></div><p>原始授权产业部:{Array.isArray(scopePreview.grantedDepartments) ? (scopePreview.grantedDepartments as unknown[]).map(String).join('、') : '—'} · 有效产业部:{Array.isArray(scopePreview.departments) ? (scopePreview.departments as unknown[]).map(String).join('、') : '—'}</p>{rows(scopePreview.hierarchySource).length > 0 && <p>层级依据:当前映射配置</p>}{scopeCounts.length ? <Table size="small" bordered dataSource={scopeCounts} rowKey={row => String(row.stage)} pagination={false} columns={[{ title: '阶段', dataIndex: 'stage', key: 'stage', width: 100, render: value => value === 'black' ? '黑片' : value === 'bright' ? '亮片' : text(value) }, { title: '总行数', dataIndex: 'totalRows', key: 'totalRows', align: 'right' }, { title: '授权行数', dataIndex: 'authorizedRows', key: 'authorizedRows', align: 'right' }]} /> : <Empty description="服务端没有返回授权计数" />}</section>}{!userId && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="选择用户后查看并编辑其访问范围" />}</div>;
|
||||
return <div className="governance-panel-body"><div className="completion-panel-heading"><div><strong>用户明细与证据访问策略</strong><span>明细、原文件下载与字段授权由服务端二次校验</span></div><div className="completion-actions"><Button disabled={!userId || loading || saving || previewBusy} loading={previewBusy} onClick={() => void preview('effective')}>预览有效授权</Button><Button disabled={!userId || loading || saving || previewBusy} loading={previewBusy} onClick={() => void preview('scope')}>预览授权行数</Button></div></div><div className="governance-policy-select"><Select disabled={saving} showSearch optionFilterProp="label" placeholder="选择用户" value={userId} options={userOptions} onChange={selectUser} /></div>{error && <Alert showIcon type="error" message="访问策略不可用" description={error} />}{loading ? <div className="completion-loading"><Spin />读取访问策略…</div> : policy && policy.userId === userId && <Form form={form} disabled={saving} layout="vertical" className="governance-policy-form"><div className="governance-form-grid"><Form.Item name="detailAllowed" label="允许读取来源明细" valuePropName="checked"><Switch /></Form.Item><Form.Item name="evidenceAllowed" label="允许查看来源变更证据" valuePropName="checked"><Switch /></Form.Item><Form.Item name="originalDownloadAllowed" label="允许下载原始文件" valuePropName="checked"><Switch /></Form.Item><Form.Item name="inheritDepartmentChildren" label="继承下级产业部范围" valuePropName="checked"><Switch /></Form.Item><Form.Item name="validUntil" label="授权有效截止时间(ISO,可选)"><Input placeholder="2026-12-31T23:59:59Z" /></Form.Item></div><Form.Item name="allowedFields" label="允许字段(每行一个;* 表示全部已授权字段)"><Input.TextArea rows={5} spellCheck={false} /></Form.Item><Form.Item name="reason" label="修改原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item><Button type="primary" disabled={loading || policy?.userId !== userId} loading={saving} onClick={() => void save()}>保存访问策略</Button><p className="completion-note">空字段集合将由服务端按其默认策略处理。</p></Form>}{effective && <section className="completion-insight-card"><div className="completion-card-heading"><strong>服务端有效授权</strong><Tag color={effective.authorizationEffective === true ? 'green' : 'red'}>{effective.authorizationEffective === true ? '有效' : '未生效'}</Tag></div><p>用户 {text(effective.userId)} · 身份 {effective.active === true ? '启用' : '停用'} · 数据范围已由服务端核验</p><p>角色:{Array.isArray(effective.roles) ? (effective.roles as unknown[]).map(String).join('、') : '—'}</p><p>原始授权产业部:{grantedDepartments} · 有效产业部:{effectiveDepartments}</p><p>业务分组:{Array.isArray(effective.groups) ? (effective.groups as unknown[]).map(String).join('、') : '—'}</p><p>动作:{Array.isArray(effective.allowedActions) ? (effective.allowedActions as unknown[]).map(String).join('、') : '—'}</p><p>字段策略:{JSON.stringify(withoutSystemMetadata(effective.fieldPolicy ?? {}))}</p>{hierarchyRows.length > 0 && <p>层级展开依据:当前映射配置</p>}</section>}{scopePreview && <section className="completion-insight-card"><div className="completion-card-heading"><strong>授权范围行数</strong><Tag>{scopePreview.dataReturned === false ? '仅计数,未返回数据' : '服务端返回状态'}</Tag></div><p>原始授权产业部:{Array.isArray(scopePreview.grantedDepartments) ? (scopePreview.grantedDepartments as unknown[]).map(String).join('、') : '—'} · 有效产业部:{Array.isArray(scopePreview.departments) ? (scopePreview.departments as unknown[]).map(String).join('、') : '—'}</p>{rows(scopePreview.hierarchySource).length > 0 && <p>层级依据:当前映射配置</p>}{scopeCounts.length ? <Table size="small" bordered dataSource={scopeCounts} rowKey={row => String(row.stage)} pagination={false} columns={[{ title: '阶段', dataIndex: 'stage', key: 'stage', width: 100, render: value => value === 'black' ? '黑片' : value === 'bright' ? '亮片' : text(value) }, { title: '总行数', dataIndex: 'totalRows', key: 'totalRows', align: 'right' }, { title: '授权行数', dataIndex: 'authorizedRows', key: 'authorizedRows', align: 'right' }]} /> : <Empty description="服务端没有返回授权计数" />}</section>}{!userId && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="选择用户后查看并编辑其访问范围" />}</div>;
|
||||
}
|
||||
|
||||
+361
-159
@@ -1,7 +1,14 @@
|
||||
import { TasksMonitorPage } from './TasksMonitorPage';
|
||||
import { configurationDateTime, currentConfigurationName } from './configurationName';
|
||||
import { BusinessValue, currentMetricFormula } from './BusinessValue';
|
||||
import { AnalysisNarrative } from './AnalysisNarrative';
|
||||
import { AnalysisClarification } from './AnalysisClarification';
|
||||
import { pendingClarificationTurnId } from './analysisClarificationModel';
|
||||
import { useAnalysisVisualRecovery } from './analysisVisualRecovery';
|
||||
import { mergeModelThinking, modelThinkingEntries } from './analysisModelThinking';
|
||||
import { usePageCache } from './pageCache';
|
||||
import { FilterFieldSettings } from './FilterFieldSettings';
|
||||
import { isInternalDataField, publicJson } from './publicDataDisplay';
|
||||
import { isInternalDataField, publicJson, readableRuleDescription } from './publicDataDisplay';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
@@ -23,7 +30,7 @@ import {
|
||||
Tag,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { QualityTable as Table } from './QualityTable';
|
||||
import { CompactManagementTables, QualityTable as Table } from './QualityTable';
|
||||
import { DeleteOutlined, EditOutlined, MoreOutlined, ReloadOutlined, RobotOutlined } from '@ant-design/icons';
|
||||
import { ApiError, api, collectionItems, decodeQueryValueList } from './api';
|
||||
import type { AuthUser, Collection, OptionsResponse, QueryParams, SourceItem, ViewKind } from './types';
|
||||
@@ -36,8 +43,13 @@ import { AnalysisReportExport, NativeAnalysisReport } from './AnalysisReportExpo
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
import { authorizeAnalysisSnapshot } from './analysisSnapshot';
|
||||
import { AnalysisApiSettings } from './AnalysisApiSettings';
|
||||
import { acceptAnalysisEvent, analysisScrollFollows, partialAnalysisNotice, partialAnswerIsOnlyProgress } from './analysisConversationState';
|
||||
import { acceptAnalysisEvent, analysisScrollFollows, partialAnalysisNotice, partialAnswerIsOnlyProgress, type AnalysisScrollIntent } from './analysisConversationState';
|
||||
import { AnalysisProcess } from './AnalysisProcess';
|
||||
import { AnalysisMemberListPanel } from './AnalysisMemberList';
|
||||
import { AnalysisRecordListPanel } from './AnalysisRecordList';
|
||||
import { analysisScopeText, restoredAnalysisDraft, analysisComposerState, analysisFollowRequestReady } from './analysisScope';
|
||||
import { isValidAnalysisPeriodContext } from './analysisPeriodModel';
|
||||
import { beginAnalysisSubmission, requestSubmissionCancellation, submissionOutcomeUnknown, type AnalysisSubmission } from './analysisSubmission';
|
||||
import { activeAnalysisTurn, analysisIsRunning, beginAnalysisSelection, defaultAnalysisSession, rememberAnalysisSession, rememberPendingAnalysisSession, settledAnalysisTurn } from './analysisConversationState';
|
||||
import './analysis-chat.css';
|
||||
|
||||
@@ -45,7 +57,7 @@ const TABLE_PAGE_SIZE = 20;
|
||||
import { DataWorkflowHub, MasterWorkbookUpload, ReadableConfigDefinition, SourceFilesPanel, type PendingSourceDeletion } from './NoCodeDataWorkflow';
|
||||
import { MappingDefinitionEditor, MasterDataDefinitionEditor, MatchRulesDefinitionEditor, RuleDefinitionEditor, TechnicalDefinitionEditor, validateStructuredMappingDefinition, type ConfigDefinition } from './StructuredConfigEditors';
|
||||
import { useDataWorkflowOperation } from './useDataWorkflowOperation';
|
||||
import { BackupOperationsPanel, CostConfigurationPanel, OperationsMonitorPanel, ServiceIdentityPanel, SourceGovernancePanel, UserAccessPolicyPanel } from './GovernanceCompletion';
|
||||
import { CostConfigurationPanel, ServiceIdentityPanel, SourceGovernancePanel, UserAccessPolicyPanel } from './GovernanceCompletion';
|
||||
|
||||
function apiMessage(error: unknown): string {
|
||||
if (error instanceof ApiError && error.status === 409) return '当前数据或配置已变化,请刷新后重新操作。';
|
||||
@@ -58,6 +70,10 @@ function toText(value: unknown): string {
|
||||
try { return JSON.stringify(value); } catch { return String(value); }
|
||||
}
|
||||
|
||||
function regressionStatus(value: unknown): string {
|
||||
return value === 'UNCONFIGURED' ? '未配置原表验收资料' : toText(value);
|
||||
}
|
||||
|
||||
function shownDepartment(value: string): string {
|
||||
return value === '质量管理部' ? '质量中心' : value;
|
||||
}
|
||||
@@ -67,7 +83,8 @@ function restoredAnalysisTurns(history: Record<string, unknown>, metadata: Colle
|
||||
return collectionItems(metadata).slice().reverse().map(turn => {
|
||||
const found = saved.find(item => item.id === turn.id);
|
||||
const answer = found && isObjectRecord(found.result) ? found.result : {};
|
||||
return { ...found, ...answer, ...turn, sessionId: history.id };
|
||||
const status=answer.visualRecovery&&answer.originalStatus===turn.status?answer.status||turn.status:turn.status;
|
||||
return { ...found, ...answer, ...turn, status, sessionId: history.id };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -91,11 +108,14 @@ function decodeAnalysisLinkContext(encoded: string | null): AnalysisLinkContext
|
||||
if (!Number.isInteger(year) || year < 2000 || year > 2100) throw new Error('分析条件链接中的年份无效');
|
||||
const month = rawQuery.month === undefined || rawQuery.month === null ? undefined : Number(rawQuery.month);
|
||||
const quarter = rawQuery.quarter === undefined || rawQuery.quarter === null ? undefined : Number(rawQuery.quarter);
|
||||
if ((month !== undefined && (!Number.isInteger(month) || month < 1 || month > 12)) || (quarter !== undefined && (!Number.isInteger(quarter) || quarter < 1 || quarter > 4)) || (month !== undefined && quarter !== undefined)) throw new Error('分析条件链接中的月/季度无效');
|
||||
const monthStart = rawQuery.monthStart === undefined || rawQuery.monthStart === null ? undefined : Number(rawQuery.monthStart);
|
||||
const monthEnd = rawQuery.monthEnd === undefined || rawQuery.monthEnd === null ? undefined : Number(rawQuery.monthEnd);
|
||||
if (!isValidAnalysisPeriodContext({ year, month, quarter, monthStart, monthEnd }, 2000, 2100)) throw new Error('分析条件链接中的统计期间无效');
|
||||
const views: ViewKind[] = ['overall', 'department', 'group', 'product', 'projectGroup'];
|
||||
if (!views.includes(rawQuery.view as ViewKind)) throw new Error('分析条件链接中的查询维度无效');
|
||||
const view = rawQuery.view as ViewKind;
|
||||
const query: QueryParams = { year, ...(month !== undefined ? { month } : {}), ...(quarter !== undefined ? { quarter } : {}), view };
|
||||
const query: QueryParams = { year, ...(month !== undefined ? { month } : {}), ...(quarter !== undefined ? { quarter } : {}),
|
||||
...(monthStart !== undefined ? { monthStart } : {}), ...(monthEnd !== undefined ? { monthEnd } : {}), view };
|
||||
for (const key of ['department', 'group', 'product', 'projectGroup'] as const) {
|
||||
const value = rawQuery[key];
|
||||
if (value === undefined || value === null || value === '') continue;
|
||||
@@ -186,15 +206,22 @@ function DynamicTable({ items, rowKey = 'id', paginate = true, indexOffset = 0 }
|
||||
}));
|
||||
return items.length
|
||||
? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={item => String(item[rowKey] ?? JSON.stringify(item))} pagination={paginate ? { pageSize: TABLE_PAGE_SIZE, showSizeChanger: false } : false} indexOffset={indexOffset} scroll={{ x: 'max-content' }} />
|
||||
<p className="table-caption">显示服务端返回的 {items.length} 条记录</p></div>
|
||||
: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前返回空列表" />;
|
||||
<p className="table-caption">共 {items.length} 条记录</p></div>
|
||||
: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无记录" />;
|
||||
}
|
||||
|
||||
export default function ManagementPages({ page, user, onUnauthorized, onNavigate }: {
|
||||
type ManagementPageProps = {
|
||||
page: PageKey; user: AuthUser; onUnauthorized: (error: unknown) => boolean;
|
||||
onNavigate: (page: PageKey) => void;
|
||||
}) {
|
||||
};
|
||||
export default function ManagementPages(props: ManagementPageProps) {
|
||||
return <CompactManagementTables.Provider value={['sources','imports','rules','mappings','masterData','tasks','access','basis'].includes(props.page)}>
|
||||
<ManagementPageContents {...props}/>
|
||||
</CompactManagementTables.Provider>;
|
||||
}
|
||||
function ManagementPageContents({ page, user, onUnauthorized, onNavigate }: ManagementPageProps) {
|
||||
if (page === 'sources' || page === 'imports') return <SourcesPage onUnauthorized={onUnauthorized} user={user} />;
|
||||
if (page === 'tasks') return <TasksMonitorPage user={user} onUnauthorized={onUnauthorized} />;
|
||||
if (page === 'analysis') return <AnalysisPage onUnauthorized={onUnauthorized} user={user} />;
|
||||
if (page === 'access') return <AccessPage user={user} onUnauthorized={onUnauthorized} />;
|
||||
if (page === 'basis') return <BasisPage onUnauthorized={onUnauthorized} />;
|
||||
@@ -291,7 +318,7 @@ function ImportIssuesDrawer({ runId, onClose, onUnauthorized }: { runId: string;
|
||||
</Drawer>;
|
||||
}
|
||||
|
||||
function ReadOnlyResourcePage({ endpoint, title, subtitle, user, onUnauthorized, onNavigate }: {
|
||||
function ReadOnlyResourcePage({ endpoint, title, subtitle, user, onUnauthorized }: {
|
||||
endpoint: 'imports' | 'tasks'; title: string; subtitle: string; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate?: () => void;
|
||||
}) {
|
||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||
@@ -317,11 +344,20 @@ function ReadOnlyResourcePage({ endpoint, title, subtitle, user, onUnauthorized,
|
||||
<section className="panel section-panel"><div className="resource-toolbar"><strong>{title}</strong><span>{metadata.total !== undefined ? `共 ${metadata.total} 条` : `服务端返回 ${items.length} 条`}</span></div>
|
||||
{loading ? <div className="loading-panel"><Spin />正在读取…</div> : <TaskTable items={items} importOnly={endpoint === 'imports'} user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
|
||||
</section>
|
||||
{endpoint === 'tasks' && <><OperationsMonitorPanel user={user} onUnauthorized={onUnauthorized} /><BackupOperationsPanel user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /></>}
|
||||
<Alert showIcon type="info" message="状态以服务端为准" description={endpoint === 'imports' ? '此处显示任务服务返回的导入状态、校验结果和错误;选择问题行可查看后端返回的逐行检查记录。' : '可查看真实任务进度、失败原因,并按权限对失败任务重试或取消排队任务。'} />
|
||||
</div>;
|
||||
}
|
||||
|
||||
function RuleContents({ value }: { value: unknown }) {
|
||||
const definition = value && typeof value === 'object' ? value as Record<string, unknown> : {};
|
||||
if (definition.version === 'pq-dax-v1' && !definition.rowRules && !definition.metricRules) return <p>此历史记录未保存可展开的公式明细。</p>;
|
||||
return <BusinessValue value={value} />;
|
||||
}
|
||||
|
||||
function ruleDisplayName(value: unknown): string {
|
||||
const name = String(value || '');
|
||||
return /power\s*query|power\s*pivot|\bdax\b|\bpq\b/i.test(name) ? '基础计算规则' : name;
|
||||
}
|
||||
|
||||
type PublishedConfigNames = Pick<OptionsResponse, 'departments' | 'groups' | 'products' | 'projectGroups'> & { groupDepartments?: Record<string, string | null> };
|
||||
|
||||
function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind: 'rules' | 'mappings' | 'masterData'; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate: (page: PageKey) => void }) {
|
||||
@@ -394,7 +430,8 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
const definition = isRules && testMode && String(active?.id ?? fallback?.id) === 'pq-dax-v1' && ruleSchema?.defaultDefinition
|
||||
? ruleSchema.defaultDefinition : storedDefinition;
|
||||
if (definition && typeof definition === 'object') setDraftDefinition(JSON.parse(JSON.stringify(definition)) as ConfigDefinition);
|
||||
form.setFieldsValue({ name: String(active?.name || fallback?.name || (isRules ? '测试计算规则' : '测试基础数据与对应关系')), description: String(active?.description || fallback?.description || '') });
|
||||
const metadata = items.find(row => String(row.id) === String(active?.id)) ?? fallback;
|
||||
form.setFieldsValue({ name: testMode ? currentConfigurationName(active?.name ?? metadata?.name, metadata?.createdAt) : isRules ? ruleDisplayName(active?.name || fallback?.name || '测试计算规则') : String(active?.name || fallback?.name || '测试基础数据与对应关系'), description: isRules ? readableRuleDescription(active?.description || fallback?.description) : String(active?.description || fallback?.description || '') });
|
||||
}, [workflowStatus, items, kind, isRules, testMode, ruleSchema]);
|
||||
|
||||
const openRegression = async (item: Record<string, unknown>, preferredRunId?: string) => {
|
||||
@@ -430,7 +467,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
setDraftDefinition(definition);
|
||||
form.setFieldsValue({
|
||||
name: String(item?.name || (source?.name ? `${String(source.name).slice(0, 112)}·草稿` : '')),
|
||||
description: String(source?.description || (source?.definition as ConfigDefinition | undefined)?.maintenanceNote || ''),
|
||||
description: isRules ? readableRuleDescription(source?.description) : String(source?.description || (source?.definition as ConfigDefinition | undefined)?.maintenanceNote || ''),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -447,7 +484,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
} else {
|
||||
if (isRules) await api.createRule(body); else await api.createMapping(body);
|
||||
}
|
||||
message.success('草稿已保存到服务端');
|
||||
message.success('草稿已保存');
|
||||
setDrafting(null); form.resetFields(); await load();
|
||||
} catch (value) {
|
||||
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
||||
@@ -467,7 +504,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
setValidation({ id, value: result });
|
||||
|
||||
}
|
||||
message.success(action === 'validate' ? '服务端校验已完成' : '配置已启用');
|
||||
message.success(action === 'validate' ? '校验已完成' : '配置已启用');
|
||||
if (action === 'activate') setDifferenceItem(null);
|
||||
await load();
|
||||
} catch (value) { if (!onUnauthorized(value)) message.error(apiMessage(value)); if (value instanceof ApiError && value.status === 409) await load(); }
|
||||
@@ -495,9 +532,9 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
];
|
||||
|
||||
const columns: ColumnsType<Record<string, unknown>> = [
|
||||
{ title: '名称', dataIndex: 'name', key: 'name', fixed: 'left', width: 230, render: value => <strong>{toText(value)}</strong> },
|
||||
{ title: '名称', dataIndex: 'name', key: 'name', fixed: 'left', width: 230, render: value => <strong>{toText(isRules ? ruleDisplayName(value) : value)}</strong> },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 125, align: 'center', render: value => <Tag color={String(value).toUpperCase().includes('ACTIVE') ? 'green' : 'blue'}>{({ ACTIVE: '已启用', VALIDATED: '已校验', DRAFT: '草稿', SUPERSEDED: '历史记录', ENGINE_BASELINE: '原始公式', ARCHIVED: '已归档' } as Record<string, string>)[String(value).toUpperCase()] || toText(value)}</Tag> },
|
||||
{ title: '说明', dataIndex: 'description', key: 'description', width: 260, ellipsis: true, render: (value, row) => readableValue(value || (row.definition as ConfigDefinition | undefined)?.maintenanceNote) },
|
||||
{ title: '说明', dataIndex: 'description', key: 'description', width: 260, ellipsis: true, render: (value, row) => readableValue(isRules ? readableRuleDescription(value) : value || (row.definition as ConfigDefinition | undefined)?.maintenanceNote) },
|
||||
{ title: '更新时间', dataIndex: 'createdAt', key: 'createdAt', width: 205 },
|
||||
{ title: '操作', key: 'actions', fixed: 'right', width: 330, align: 'center', render: (_, row) => <span className="task-actions">
|
||||
<Button type="link" onClick={() => setValidation({ id: String(row.id || ''), value: row.definition, purpose: 'definition' })}>{isRules ? '查看定义' : '查看内容'}</Button>
|
||||
@@ -512,19 +549,14 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
const simpleStageLabel: Record<string, string> = { QUEUED: '等待处理', VALIDATING: '检查配置与来源', VERSION_CREATED: '保存配置', REBUILDING: '重新计算报表', PUBLISHING: '更新当前报表', COMPLETED: '已完成', FAILED: '处理失败' };
|
||||
const applyCurrent = async () => {
|
||||
try {
|
||||
const values = await form.validateFields();
|
||||
await workflowOperation.start(() => api.applyDataWorkflow({ kind: isRules ? 'rule' : 'mapping', name: values.name.trim(), definition: draftDefinition, expectedCurrentReleaseId: workflowStatus?.currentReleaseId ?? null, ...(values.description?.trim() ? { description: values.description.trim() } : {}) }));
|
||||
await form.validateFields();
|
||||
const values = form.getFieldsValue(true);
|
||||
await workflowOperation.start(() => api.applyDataWorkflow({ kind: isRules ? 'rule' : 'mapping', name: configurationDateTime(new Date()), definition: draftDefinition, expectedCurrentReleaseId: workflowStatus?.currentReleaseId ?? null, ...(values.description?.trim() ? { description: values.description.trim() } : {}) }));
|
||||
} catch (value) {
|
||||
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
||||
if (!onUnauthorized(value)) message.error(apiMessage(value));
|
||||
}
|
||||
};
|
||||
const simpleHistoryColumns: ColumnsType<Record<string, unknown>> = [
|
||||
{ title: '配置名称', dataIndex: 'name', key: 'name', width: 250, render: name => <strong>{toText(name)}</strong> },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 120, render: status => <Tag color={String(status).toUpperCase() === 'ACTIVE' ? 'green' : 'default'}>{String(status).toUpperCase() === 'ACTIVE' ? '当前使用' : '历史记录'}</Tag> },
|
||||
{ title: '更新时间', dataIndex: 'createdAt', key: 'createdAt', width: 205 },
|
||||
{ title: '操作', key: 'actions', width: 120, render: (_, row) => <Button type="link" onClick={() => setValidation({ id: String(row.id || ''), value: row.definition, purpose: 'definition' })}>查看内容</Button> },
|
||||
];
|
||||
|
||||
if (!workflowStatusLoaded) return <div className="management-page"><div className="loading-panel"><Spin />正在读取当前维护模式…</div></div>;
|
||||
if (testMode) return <div className="management-page nc-simplified-config-page">
|
||||
@@ -535,10 +567,9 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
{workflowOperation.error && <Alert showIcon type="error" message={workflowOperation.operation?.status === 'FAILED' ? '保存或报表更新失败' : '进度读取失败'} description={workflowOperation.error} action={workflowOperation.operation?.operationId ? <Button size="small" onClick={workflowOperation.resume}>重试读取进度</Button> : undefined} />}
|
||||
{workflowOperation.operation && <section className="nc-operation-status panel"><div><strong>{workflowOperation.busy ? (simpleStageLabel[String(workflowOperation.operation.stage || workflowOperation.operation.status)] || '正在处理') : String(workflowOperation.operation.status).toUpperCase() === 'COMPLETED' ? '报表已更新' : '操作结束'}</strong></div><Progress percent={workflowOperation.busy ? undefined : String(workflowOperation.operation.status).toUpperCase() === 'COMPLETED' ? 100 : 0} status={String(workflowOperation.operation.status).toUpperCase() === 'FAILED' ? 'exception' : String(workflowOperation.operation.status).toUpperCase() === 'COMPLETED' ? 'success' : 'active'} /></section>}
|
||||
<section className="panel section-panel nc-simple-current-config">
|
||||
<div className="resource-toolbar"><strong>{isRules ? '当前计算规则' : '当前基础数据、对应关系与匹配规则'}</strong></div>
|
||||
<Form form={form} layout="vertical"><div className="structured-config-form-grid"><Form.Item name="name" label="配置名称" rules={[{ required: true, whitespace: true, message: '请填写名称' }]}><Input disabled={!canApplyWorkflow} maxLength={120} /></Form.Item><Form.Item name="description" label="说明(可选)"><Input disabled={!canApplyWorkflow} maxLength={1000} /></Form.Item></div></Form>
|
||||
{isRules ? canApplyWorkflow ? <RuleDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} schema={ruleSchema} schemaError={ruleSchemaError} /> : <pre className="json-result">{publicJson(draftDefinition)}</pre> : <>
|
||||
<div className="nc-simple-config-intro"><Alert showIcon type="info" message="Excel 与系统名称对应" description="Excel“事业部”映射为系统“产业部”;Excel“产业部”映射为系统“业务分组”。对应到的新目标会自动加入相应名录。" /></div>
|
||||
{isRules && <div className="resource-toolbar"><strong>当前计算规则</strong></div>}
|
||||
<Form form={form} component={isRules ? 'form' : false} layout="vertical">{isRules && <div className="structured-config-form-grid"><Form.Item name="name" label="配置名称"><Input readOnly placeholder="保存时自动生成" /></Form.Item><Form.Item name="description" label="说明(可选)"><Input disabled={!canApplyWorkflow} maxLength={1000} /></Form.Item></div>}</Form>
|
||||
{isRules ? canApplyWorkflow ? <RuleDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} schema={ruleSchema} schemaError={ruleSchemaError} /> : <RuleContents value={draftDefinition} /> : <>
|
||||
<Tabs className="nc-simple-config-tabs" activeKey={simpleTab} onChange={key => setSimpleTab(key as typeof simpleTab)} items={[
|
||||
{ key: 'catalog', label: '名录', children: <><div className="nc-simple-config-intro">{canApplyWorkflow && <MasterWorkbookUpload kind="masterData" base={workflowMappingBase} expectedCurrentReleaseId={workflowStatus?.currentReleaseId ?? null} onUnauthorized={onUnauthorized} onComplete={() => { void load(); void refreshWorkflowStatus(); }} simplified />}</div><MasterDataDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} publishedNames={publishedNames ?? undefined} simplified readOnly={!canApplyWorkflow} /></> },
|
||||
{ key: 'lookups', label: '基础对应', children: <><div className="nc-simple-config-intro">{canApplyWorkflow && <MasterWorkbookUpload kind="mappings" base={workflowMappingBase} expectedCurrentReleaseId={workflowStatus?.currentReleaseId ?? null} onUnauthorized={onUnauthorized} onComplete={() => { void load(); void refreshWorkflowStatus(); }} simplified />}</div><MappingDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} simplified readOnly={!canApplyWorkflow} /></> },
|
||||
@@ -548,8 +579,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
</>}
|
||||
{canApplyWorkflow && <div className="nc-simple-save-row"><span>保存会自动检查配置、保存配置、按当前来源重算并更新报表。</span><Button type="primary" size="large" disabled={workflowOperation.busy || (isRules && !ruleSchema)} loading={workflowOperation.busy} onClick={() => void applyCurrent()}>保存并更新报表</Button></div>}
|
||||
</section>
|
||||
<section className="panel section-panel nc-simple-history"><div className="resource-toolbar"><strong>历史配置记录</strong><span>{items.length} 条记录 · 仅供查看</span></div>{loading ? <div className="loading-panel"><Spin />正在读取…</div> : <Table size="small" bordered columns={simpleHistoryColumns} dataSource={items} rowKey={row => String(row.id)} pagination={{ pageSize: 8, showSizeChanger: false }} scroll={{ x: 760 }} locale={{ emptyText: '暂无历史配置记录' }} />}</section>
|
||||
{validation && <Drawer className="management-drawer" open title="历史记录内容" width={Math.min(980, window.innerWidth)} onClose={() => setValidation(null)}>{isRules ? <pre className="json-result">{publicJson(validation.value)}</pre> : <ReadableConfigDefinition kind="mappings" value={validation.value} />}</Drawer>}
|
||||
|
||||
</div>;
|
||||
|
||||
return <div className="management-page">
|
||||
@@ -571,7 +601,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
{kind === 'masterData' ? <MasterDataDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} publishedNames={publishedNames ?? undefined} /> : <MappingDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} />}
|
||||
{validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).length > 0 && <Alert showIcon type="warning" message="草稿存在需要处理的名录引用" description={<ul className="structured-config-error-list">{validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).slice(0, 20).map((issue, index) => <li key={`${issue}:${index}`}>{issue}</li>)}</ul>} />}
|
||||
</>}
|
||||
<TechnicalDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} />
|
||||
{!isRules && <TechnicalDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} />}
|
||||
</Modal>
|
||||
<Modal className="management-modal structured-config-modal" open={Boolean(differenceItem)} title="确认规则试算差异" width={920} okText="确认差异并启用" okButtonProps={{ disabled: !differenceConfirmed }} confirmLoading={Boolean(busyId)} onCancel={() => setDifferenceItem(null)} onOk={() => { if (differenceItem) void runAction(differenceItem, 'activate', true); }}>
|
||||
{differenceItem && (() => { const result = differenceItem.validation as Record<string, unknown>; return <>
|
||||
@@ -581,7 +611,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
<Checkbox checked={differenceConfirmed} onChange={event => setDifferenceConfirmed(event.target.checked)}>我已核对本次试算差异,并确认启用此规则</Checkbox>
|
||||
</>; })()}
|
||||
</Modal>
|
||||
{validation && !drafting && <Drawer className="management-drawer" open title={validation.purpose === 'definition' ? '配置定义' : '服务端校验结果'} width={Math.min(980, window.innerWidth)} onClose={() => setValidation(null)}>{validation.purpose === 'definition' ? isRules ? <pre className="json-result">{publicJson(validation.value)}</pre> : <ReadableConfigDefinition kind={kind === 'masterData' ? 'masterData' : 'mappings'} value={validation.value} /> : (() => {
|
||||
{validation && !drafting && <Drawer className="management-drawer" open title={validation.purpose === 'definition' ? '配置定义' : '服务端校验结果'} width={Math.min(980, window.innerWidth)} onClose={() => setValidation(null)}>{validation.purpose === 'definition' ? isRules ? <RuleContents value={validation.value} /> : <ReadableConfigDefinition kind={kind === 'masterData' ? 'masterData' : 'mappings'} value={validation.value} /> : (() => {
|
||||
const response = validation.value && typeof validation.value === 'object' ? validation.value as Record<string, unknown> : {};
|
||||
const result = response.validation && typeof response.validation === 'object' ? response.validation as Record<string, unknown> : response;
|
||||
const errors = Array.isArray(result.errors) ? result.errors : []; const warnings = Array.isArray(result.warnings) ? result.warnings : [];
|
||||
@@ -601,7 +631,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
const failures = Array.isArray(result.failedCases) ? result.failedCases.filter(item => item && typeof item === 'object') as Record<string, unknown>[] : [];
|
||||
const precision = result.precisionPolicy && typeof result.precisionPolicy === 'object' ? result.precisionPolicy as Record<string, unknown> : {};
|
||||
return <>
|
||||
<div className="governance-monitor-grid"><div><small>执行状态</small><strong>{toText(result.status)}</strong></div><div><small>隔离环境</small><strong>{result.isolated === true ? '是' : result.isolated === false ? '否' : '—'}</strong></div><div><small>回归案例</small><strong>{cases.length}</strong></div><div><small>失败案例</small><strong className={failures.length ? 'negative' : ''}>{failures.length}</strong></div></div>
|
||||
<div className="governance-monitor-grid"><div><small>执行状态</small><strong>{regressionStatus(result.status)}</strong></div><div><small>隔离环境</small><strong>{result.isolated === true ? '是' : result.isolated === false ? '否' : '—'}</strong></div><div><small>回归案例</small><strong>{cases.length}</strong></div><div><small>失败案例</small><strong className={failures.length ? 'negative' : ''}>{failures.length}</strong></div></div>
|
||||
<p className="completion-note">核验精度:重量 ±{toText(precision.weightAbsolute)},比率 ±{toText(precision.rateAbsolute)}</p>
|
||||
{Array.isArray(result.errors) && result.errors.length > 0 && <Alert showIcon type="error" message="回归错误" description={(result.errors as unknown[]).map(String).join(';')} />}
|
||||
<Table size="small" bordered rowKey={(row, index) => String(row.name || index)} dataSource={cases} pagination={false} scroll={{ x: 820 }} columns={[
|
||||
@@ -769,10 +799,8 @@ function MappingIssueResolutionPanel({ user, onUnauthorized }: { user: AuthUser;
|
||||
function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { message } = App.useApp();
|
||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||
const [migration, setMigration] = useState<Record<string, unknown> | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [dictionaryError, setDictionaryError] = useState('');
|
||||
const [migrationError, setMigrationError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [editing, setEditing] = useState<Record<string, unknown> | null>(null);
|
||||
const [inspecting, setInspecting] = useState<Record<string, unknown> | null>(null);
|
||||
@@ -781,12 +809,10 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
const [dictionaryResult, migrationResult] = await Promise.allSettled([api.metricDictionary(), api.metricDictionaryMigration()]);
|
||||
if (dictionaryResult.status === 'fulfilled') {
|
||||
setItems(collectionItems(dictionaryResult.value)); setDictionaryError('');
|
||||
} else if (!onUnauthorized(dictionaryResult.reason)) setDictionaryError(apiMessage(dictionaryResult.reason));
|
||||
if (migrationResult.status === 'fulfilled') { setMigration(migrationResult.value); setMigrationError(''); }
|
||||
else if (!onUnauthorized(migrationResult.reason)) setMigrationError(apiMessage(migrationResult.reason));
|
||||
try {
|
||||
const result = await api.metricDictionary();
|
||||
setItems(collectionItems(result)); setDictionaryError('');
|
||||
} catch (value) { if (!onUnauthorized(value)) setDictionaryError(apiMessage(value)); }
|
||||
setLoading(false);
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
@@ -796,7 +822,7 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
||||
form.setFieldsValue({
|
||||
name: String(item.name || ''),
|
||||
aliases: Array.isArray(item.aliases) ? item.aliases.map(String).join('\n') : '',
|
||||
description: String(item.description || ''), reason: '',
|
||||
description: readableRuleDescription(item.description), reason: '',
|
||||
});
|
||||
};
|
||||
const save = async () => {
|
||||
@@ -822,47 +848,19 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
||||
};
|
||||
|
||||
const columns: ColumnsType<Record<string, unknown>> = [
|
||||
{ title: '指标编码', dataIndex: 'code', key: 'code', fixed: 'left', width: 220 },
|
||||
{ title: '术语名称', dataIndex: 'name', key: 'name', width: 190 },
|
||||
{ title: '别名', dataIndex: 'aliases', key: 'aliases', width: 240, ellipsis: true, render: value => Array.isArray(value) ? value.map(String).join('、') || '—' : toText(value) },
|
||||
{ title: '说明', dataIndex: 'description', key: 'description', width: 260, ellipsis: true, render: readableValue },
|
||||
{ title: '单位', dataIndex: 'unit', key: 'unit', width: 100 },
|
||||
{ title: '维度', dataIndex: 'dimensions', key: 'dimensions', width: 190, ellipsis: true, render: value => Array.isArray(value) ? value.map(String).join('、') : readableValue(value) },
|
||||
{ title: '原始基线公式', dataIndex: 'formula', key: 'formula', width: 280, ellipsis: true, render: readableValue },
|
||||
{ title: '状态', dataIndex: 'enabled', key: 'enabled', width: 90, render: value => <Tag color={value === true ? 'green' : 'default'}>{value === true ? '启用' : value === false ? '停用' : '—'}</Tag> },
|
||||
{ title: '操作', key: 'actions', fixed: 'right', width: 150, render: (_, row) => <span className="task-actions"><Button type="link" onClick={() => setInspecting(row)}>查看</Button>{canManage && <Button type="link" onClick={() => openEditor(row)}>编辑术语</Button>}</span> },
|
||||
{ title: '术语名称', dataIndex: 'name', key: 'name', width: 160 },
|
||||
{ title: '说明', dataIndex: 'description', key: 'description', width: 200, render: value => readableValue(readableRuleDescription(value)) },
|
||||
{ title: '单位', dataIndex: 'unit', key: 'unit', width: 55, render: value => value === 'RATE' ? '%' : toText(value) },
|
||||
{ title: '适用范围', dataIndex: 'dimensions', key: 'dimensions', width: 130, render: value => <BusinessValue value={value} field="dimensions" /> },
|
||||
{ title: '当前生效公式', key: 'formula', width: 420, render: (_, row) => <div style={{ whiteSpace: 'normal', overflowWrap: 'anywhere', lineHeight: 1.7 }}>{currentMetricFormula(row)}</div> },
|
||||
{ title: '状态', dataIndex: 'enabled', key: 'enabled', width: 70, render: value => <Tag color={value === true ? 'green' : 'default'}>{value === true ? '启用' : value === false ? '停用' : '—'}</Tag> },
|
||||
{ title: '操作', key: 'actions', fixed: 'right', width: 100, render: (_, row) => <span className="task-actions"><Button type="link" onClick={() => setInspecting(row)}>查看</Button>{canManage && <Button type="link" onClick={() => openEditor(row)}>编辑术语</Button>}</span> },
|
||||
];
|
||||
const dictionary = Array.isArray(migration?.items)
|
||||
? migration.items.filter(item => item && typeof item === 'object') as Record<string, unknown>[]
|
||||
: [];
|
||||
const verification = migration?.verification;
|
||||
const verificationData = verification && typeof verification === 'object' ? verification as Record<string, unknown> : {};
|
||||
const migrationStatusLabel = (value: unknown) => ({
|
||||
MIGRATED_BASELINE: '已迁移基线',
|
||||
OBSERVED_MAPPING_BASELINE: '已观察映射基线',
|
||||
RECORDED_ORIGINAL_BASELINE: '已登记原度量基线',
|
||||
EXTRACTED_SOURCE_DEFINITION: '已提取定义,尚未开放执行',
|
||||
DECLARED_DEPENDENCY: '已登记依赖关系',
|
||||
FORMAL_RATE_BASELINE: '已建立正式比率基线',
|
||||
} as Record<string, string>)[String(value)] || String(value || '未标记');
|
||||
const migrationRows = dictionary.map(item => ({ ...item, sourceStatus: item.status, status: migrationStatusLabel(item.status) }));
|
||||
|
||||
return <section className="panel section-panel completion-tools">
|
||||
<div className="completion-panel-heading"><div><strong>指标术语字典</strong><span>维护展示名称与别名;计算公式在上方计算规则中维护</span></div><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新字典与迁移账本</Button></div>
|
||||
<Tabs items={[
|
||||
{ key: 'dictionary', label: `术语字典(${items.length})`, children: <>
|
||||
<div className="completion-panel-heading"><div><strong>指标术语字典</strong><span>维护展示名称与别名;计算公式在上方计算规则中维护</span></div><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新字典</Button></div>
|
||||
{dictionaryError && <Alert showIcon type="error" message="术语字典读取失败" description={dictionaryError} />}
|
||||
{loading ? <div className="loading-panel"><Spin />读取术语定义…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.code)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1580 }} /></div> : !dictionaryError && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端尚未登记指标术语" />}
|
||||
<Alert showIcon type="info" message="术语编辑不改变计算规则" description="此处显示原始基线公式。生效公式以当前生效的计算规则为准。" />
|
||||
</> },
|
||||
{ key: 'migration', label: `迁移与公式账本(${dictionary.length})`, children: <>
|
||||
{migrationError && <Alert showIcon type="error" message="迁移账本读取失败" description={migrationError} />}
|
||||
{loading ? <div className="loading-panel"><Spin />读取迁移与验证记录…</div> : <>
|
||||
{verification !== undefined && <><h3>迁移核验状态</h3><div className="governance-monitor-grid"><div><small>核验场景</small><strong>{toText(verificationData.scenarioCount)}</strong></div><div><small>失败场景</small><strong>{toText(verificationData.failedScenarios)}</strong></div><div><small>字段检查</small><strong>{toText(verificationData.fieldChecks)}</strong></div><div><small>查询 / 度量</small><strong>{toText(migration?.queryCount)} / {toText(migration?.measureCount)}</strong></div><div><small>成本核算</small><strong>{migration?.costCalculationEnabled === false ? '未启用' : toText(migration?.costCalculationEnabled)}</strong></div></div><p className="completion-note">产物:{toText(verificationData.artifact)} · {toText(verificationData.notice) || '状态由服务端迁移账本返回'}</p><details><summary>查看服务端核验明细</summary><pre className="json-result">{publicJson(verification)}</pre></details></>}
|
||||
<h3>迁移公式条目</h3>{migrationRows.length ? <><Alert showIcon type="info" message="迁移状态按服务端标记逐项呈现" description="已提取的源定义不等于已开放执行;正式公式、依赖、映射观察与迁移基线保持各自状态。" /><DynamicTable items={migrationRows} rowKey="id" /></> : !migrationError && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端尚未返回迁移条目" />}
|
||||
</>}
|
||||
</> },
|
||||
]} />
|
||||
{loading ? <div className="loading-panel"><Spin />读取术语定义…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.code)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1100 }} /></div> : !dictionaryError && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无指标术语" />}
|
||||
<Alert showIcon type="info" message="术语编辑不改变计算规则" description="公式来自当前查询数据所绑定的计算规则;编辑术语不会改变计算结果。" />
|
||||
<Modal className="management-modal" open={Boolean(editing)} title={`编辑术语 · ${String(editing?.code || '')}`} okText="保存术语" confirmLoading={saving} onCancel={() => { setEditing(null); form.resetFields(); }} onOk={() => void save()}>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="name" label="展示名称" rules={[{ required: true, whitespace: true, message: '请填写展示名称' }]}><Input maxLength={160} /></Form.Item>
|
||||
@@ -870,10 +868,10 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
||||
<Form.Item name="description" label="术语说明"><Input.TextArea rows={3} maxLength={1000} /></Form.Item>
|
||||
<Form.Item name="reason" label="修改原因" rules={[{ required: true, whitespace: true, message: '请填写修改原因' }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item>
|
||||
</Form>
|
||||
<Alert showIcon type="info" message="原始基线参考" description={`原始公式:${toText(editing?.formula)} · 单位:${toText(editing?.unit)} · 维度:${toText(editing?.dimensions)}`} />
|
||||
<Alert showIcon type="info" message="当前生效公式" description={editing ? currentMetricFormula(editing) : undefined} />
|
||||
</Modal>
|
||||
<Drawer className="management-drawer" open={Boolean(inspecting)} title={`指标术语 · ${String(inspecting?.code || '')}`} width={Math.min(760, window.innerWidth)} onClose={() => setInspecting(null)}>
|
||||
{inspecting && <dl className="completion-definition-list"><dt>名称</dt><dd>{toText(inspecting.name)}</dd><dt>别名</dt><dd>{Array.isArray(inspecting.aliases) ? inspecting.aliases.map(String).join('、') : toText(inspecting.aliases)}</dd><dt>说明</dt><dd>{toText(inspecting.description)}</dd><dt>单位</dt><dd>{toText(inspecting.unit)}</dd><dt>适用维度</dt><dd>{readableValue(inspecting.dimensions)}</dd><dt>原始基线公式</dt><dd>{readableValue(inspecting.formula)}</dd><dt>状态</dt><dd>{toText(inspecting.enabled)}</dd></dl>}
|
||||
<Drawer className="management-drawer" open={Boolean(inspecting)} title={`指标术语 · ${String(inspecting?.name || '')}`} width={Math.min(760, window.innerWidth)} onClose={() => setInspecting(null)}>
|
||||
{inspecting && <dl className="completion-definition-list"><dt>名称</dt><dd>{toText(inspecting.name)}</dd><dt>别名</dt><dd>{Array.isArray(inspecting.aliases) ? inspecting.aliases.map(String).join('、') : toText(inspecting.aliases)}</dd><dt>说明</dt><dd>{toText(readableRuleDescription(inspecting.description))}</dd><dt>单位</dt><dd>{inspecting.unit === 'RATE' ? '%' : toText(inspecting.unit)}</dd><dt>适用维度</dt><dd><BusinessValue value={inspecting.dimensions} field="dimensions" /></dd><dt>当前生效公式</dt><dd>{currentMetricFormula(inspecting)}</dd><dt>状态</dt><dd><BusinessValue value={inspecting.enabled} /></dd></dl>}
|
||||
</Drawer>
|
||||
</section>;
|
||||
}
|
||||
@@ -918,7 +916,7 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
||||
{ title: '任务类型', dataIndex: 'type', key: 'type', width: 130 },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 130, render: value => <Tag color={String(value).toUpperCase().includes('FAIL') || String(value).toUpperCase() === 'ERROR' ? 'red' : String(value).toUpperCase() === 'SUCCEEDED' || String(value).toUpperCase() === 'COMPLETED' ? 'green' : 'blue'}>{importOnly ? importState(value) : toText(value)}</Tag> },
|
||||
{ title: '处理阶段', dataIndex: 'stage', key: 'stage', width: 150 },
|
||||
{ title: importOnly ? '进度' : '进度(服务端)', dataIndex: 'progress', key: 'progress', width: 145, align: 'right', render: value => importOnly ? `${toText(value)}%` : toText(value) },
|
||||
{ title: importOnly ? '进度' : '进度', dataIndex: 'progress', key: 'progress', width: 145, align: 'right', render: value => importOnly ? `${toText(value)}%` : toText(value) },
|
||||
{ title: '已处理 / 总数', key: 'processed', width: 140, align: 'right', render: (_, row) => `${toText(row.processed)} / ${toText(row.total)}` },
|
||||
{ title: '错误码', dataIndex: 'errorCode', key: 'errorCode', width: 150, render: value => value ? <Tag color="red">{toText(value)}</Tag> : '—' },
|
||||
{ title: '错误信息', dataIndex: 'errorMessage', key: 'errorMessage', width: 300, ellipsis: true, render: value => value ? <span className="task-error">{toText(value)}</span> : '—' },
|
||||
@@ -932,7 +930,7 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
||||
];
|
||||
return <>
|
||||
{items.length ? <div className="resource-table"><Table size="small" bordered columns={importOnly ? columns.filter(column => ['createdAt', 'status', 'progress', 'processed', 'errorMessage', 'detail'].includes(String(column.key))) : columns} dataSource={items} rowKey={row => String(row.id ?? JSON.stringify(row))} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: importOnly ? 1000 : 1600 }} />
|
||||
{!importOnly && <p className="table-caption">错误信息、进度和结果均按任务服务实际返回展示。</p>}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有后台任务" />}
|
||||
</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无后台任务" />}
|
||||
<Drawer className="management-drawer" open={Boolean(selected)} title="任务详情" width={Math.min(760, window.innerWidth)} onClose={() => setSelected(null)}>
|
||||
{selected && <><div className="task-detail-summary"><strong>{importOnly ? importState(selected.status) : `${toText(selected.type)} · ${toText(selected.status)}`}</strong>{!importOnly && <span>{toText(selected.stage)} · {toText(selected.id)}</span>}{selected.errorMessage !== null && selected.errorMessage !== undefined && selected.errorMessage !== '' && <Alert showIcon type="error" message={toText(selected.errorCode || '任务错误')} description={toText(selected.errorMessage)} />}</div>{importOnly ? <dl className="nc-form-grid"><dt>处理状态</dt><dd>{importState(selected.status)}</dd><dt>处理行数</dt><dd>{toText(selected.processed)} / {toText(selected.total)}</dd><dt>创建时间</dt><dd>{toText(selected.createdAt)}</dd></dl> : <pre className="json-result">{publicJson(selected)}</pre>}</>}
|
||||
</Drawer>
|
||||
@@ -953,35 +951,102 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
const [initialLink] = useState(() => decodeAnalysisLinkContext(initialParams.get('context')));
|
||||
const [query, setQuery] = useState('');
|
||||
const [sessionId, setSessionId] = useState(initialSessionId);
|
||||
const [sessionReadOnly, setSessionReadOnly] = useState(false);
|
||||
const [sessionContext, setSessionContext] = useState<Record<string, unknown> | null>(null);
|
||||
const [sessions, setSessions] = useState<Record<string, unknown>[]>([]);
|
||||
const [turns, setTurns] = useState<Record<string, unknown>[]>([]);
|
||||
const [options, setOptions] = useState<OptionsResponse | null>(null);
|
||||
const [historyLoading, setHistoryLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [queuedFollowup, setQueuedFollowup] = useState('');
|
||||
const [stopping, setStopping] = useState(false);
|
||||
const cancellationRequest = useRef<{ generation: number } | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [retryQuestion, setRetryQuestion] = useState('');
|
||||
const [lastTurn, setLastTurn] = useState<Record<string, unknown> | null>(null);
|
||||
const [activeTurnId, setActiveTurnId] = useState('');
|
||||
const [streamProgress, setStreamProgress] = useState('');
|
||||
const streamController = useRef<AbortController | null>(null);
|
||||
const eventCursors = useRef<Record<string, string>>({});
|
||||
const mounted = useRef(true);
|
||||
const userSelectionMade = useRef(false);
|
||||
const navigationGeneration = useRef(0);
|
||||
const subscriptionGeneration = useRef(0);
|
||||
const submissionAttempt = useRef<AnalysisSubmission | null>(null);
|
||||
const [releaseId, setReleaseId] = useState<string>();
|
||||
const [sourceResultRef, setSourceResultRef] = useState<AnalysisResultRef>();
|
||||
const conversation = useRef<HTMLDivElement>(null);
|
||||
const followOutput = useRef(true);
|
||||
const explicitlyFollowing = useRef(false);
|
||||
const userScrollIntent = useRef<AnalysisScrollIntent>(null);
|
||||
const userScrollIntentTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const scrollbarPointerActive = useRef(false);
|
||||
const touchPosition = useRef<number | null>(null);
|
||||
const followRequest = useRef<string | null>(null);
|
||||
const seenConclusion = useRef<string | null>(null);
|
||||
const previousScrollTop = useRef(0);
|
||||
const readingPosition = useRef(0);
|
||||
const [hasNewContent, setHasNewContent] = useState(false);
|
||||
const clearUserScrollIntent = () => {
|
||||
userScrollIntent.current = null;
|
||||
if (userScrollIntentTimer.current !== null) {
|
||||
clearTimeout(userScrollIntentTimer.current);
|
||||
userScrollIntentTimer.current = null;
|
||||
}
|
||||
};
|
||||
const markUserScrollIntent = (intent: Exclude<AnalysisScrollIntent, null>) => {
|
||||
clearUserScrollIntent();
|
||||
userScrollIntent.current = intent;
|
||||
userScrollIntentTimer.current = setTimeout(clearUserScrollIntent, 100);
|
||||
};
|
||||
const handleUserScrollIntent = (element: HTMLDivElement, intent: Exclude<AnalysisScrollIntent, null>) => {
|
||||
if (intent === 'up') {
|
||||
if (element.scrollTop <= 0) return;
|
||||
clearUserScrollIntent();
|
||||
explicitlyFollowing.current = false;
|
||||
followOutput.current = analysisScrollFollows(
|
||||
element.scrollHeight - element.clientHeight - element.scrollTop, followOutput.current, intent);
|
||||
return;
|
||||
}
|
||||
const distanceFromBottom = element.scrollHeight - element.clientHeight - element.scrollTop;
|
||||
if (distanceFromBottom <= 24) {
|
||||
clearUserScrollIntent();
|
||||
explicitlyFollowing.current = true;
|
||||
followOutput.current = analysisScrollFollows(distanceFromBottom, followOutput.current, intent);
|
||||
setHasNewContent(false);
|
||||
} else markUserScrollIntent(intent);
|
||||
};
|
||||
const scrollToLatest = (element: HTMLDivElement) => {
|
||||
const latest = element.querySelector<HTMLElement>('.analysis-turn:last-child');
|
||||
const finished = latest && ANALYSIS_FINAL_STATUSES.has(latest.dataset.analysisStatus || '');
|
||||
const bounds = element.getBoundingClientRect();
|
||||
// DOM rectangles include the workspace zoom; scrollTop uses layout pixels.
|
||||
const renderedScale = element.offsetHeight ? bounds.height / element.offsetHeight : 1;
|
||||
const scale = renderedScale > 0 ? renderedScale : 1;
|
||||
const pauseAtConclusion = Boolean(finished && !explicitlyFollowing.current);
|
||||
element.scrollTop = pauseAtConclusion && latest
|
||||
? element.scrollTop + (latest.getBoundingClientRect().top - bounds.top) / scale - element.clientTop
|
||||
: element.scrollHeight;
|
||||
previousScrollTop.current = element.scrollTop;
|
||||
readingPosition.current = element.scrollTop;
|
||||
// Once the conclusion is visible, preserve the reader's place as charts load.
|
||||
if (finished) {
|
||||
seenConclusion.current = latest.dataset.analysisTurnId || null;
|
||||
setHasNewContent(false);
|
||||
if (pauseAtConclusion) followOutput.current = false;
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
if (!busy) { cancellationRequest.current = null; setStopping(false); }
|
||||
}, [busy]);
|
||||
useEffect(() => {
|
||||
const element = conversation.current;
|
||||
if (active && element) element.scrollTop = followOutput.current ? element.scrollHeight : readingPosition.current;
|
||||
if (active && element) { if (followOutput.current) scrollToLatest(element); else element.scrollTop = readingPosition.current; }
|
||||
}, [active]);
|
||||
useEffect(() => { followOutput.current = true; previousScrollTop.current = 0; setHasNewContent(false); }, [sessionId]);
|
||||
useEffect(() => {
|
||||
followOutput.current = true; explicitlyFollowing.current = false; clearUserScrollIntent();
|
||||
seenConclusion.current = null; previousScrollTop.current = 0; setHasNewContent(false);
|
||||
}, [sessionId]);
|
||||
useEffect(() => () => clearUserScrollIntent(), []);
|
||||
useEffect(() => {
|
||||
const element = conversation.current;
|
||||
if (!element || !active) return;
|
||||
@@ -991,9 +1056,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
frame = requestAnimationFrame(() => {
|
||||
if (!activePage.current) return;
|
||||
if (followOutput.current) {
|
||||
element.scrollTop = element.scrollHeight;
|
||||
previousScrollTop.current = element.scrollTop;
|
||||
readingPosition.current = element.scrollTop;
|
||||
scrollToLatest(element);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1004,12 +1067,18 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
return () => { cancelAnimationFrame(frame); resize.disconnect(); mutation.disconnect(); };
|
||||
}, [active, sessionId]);
|
||||
useEffect(() => {
|
||||
if (analysisFollowRequestReady(followRequest.current, lastTurn)) {
|
||||
followOutput.current = true; explicitlyFollowing.current = false; followRequest.current = null;
|
||||
seenConclusion.current = null; setHasNewContent(false);
|
||||
}
|
||||
const element = conversation.current;
|
||||
if (active && element && followOutput.current) {
|
||||
element.scrollTop = element.scrollHeight;
|
||||
previousScrollTop.current = element.scrollTop;
|
||||
scrollToLatest(element);
|
||||
setHasNewContent(false);
|
||||
} else if (active && element) setHasNewContent(true);
|
||||
} else if (active && element && seenConclusion.current && seenConclusion.current === String(lastTurn?.id || '')) {
|
||||
// Final detail/history refreshes are not unread output after we showed it.
|
||||
setHasNewContent(false);
|
||||
} else if (active && element && busy) setHasNewContent(true);
|
||||
}, [lastTurn, busy, turns, sessionId, active]);
|
||||
|
||||
const loadSessions = async () => {
|
||||
@@ -1055,6 +1124,8 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
...(linkedQuery.extraFilters ? { extraFilters: linkedQuery.extraFilters } : {}),
|
||||
...(linkedQuery.month !== undefined ? { month: linkedQuery.month } : {}),
|
||||
...(linkedQuery.quarter !== undefined ? { quarter: linkedQuery.quarter } : {}),
|
||||
...(linkedQuery.monthStart !== undefined ? { monthStart: linkedQuery.monthStart } : {}),
|
||||
...(linkedQuery.monthEnd !== undefined ? { monthEnd: linkedQuery.monthEnd } : {}),
|
||||
view: linkedQuery.view,
|
||||
...(linkedQuery.department ? { department: linkedQuery.department } : {}),
|
||||
...(linkedQuery.group ? { group: linkedQuery.group } : {}),
|
||||
@@ -1127,6 +1198,9 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
userSelectionMade.current = true;
|
||||
beginAnalysisSelection(user.id);
|
||||
const generation = ++navigationGeneration.current;
|
||||
setQueuedFollowup('');
|
||||
cancellationRequest.current = null; setStopping(false); followRequest.current = null;
|
||||
submissionAttempt.current = null;
|
||||
subscriptionGeneration.current += 1;
|
||||
streamController.current?.abort(); streamController.current = null;
|
||||
setBusy(false); setActiveTurnId(''); setHistoryLoading(true);
|
||||
@@ -1136,8 +1210,9 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
if (!current()) return false;
|
||||
const historyTurns = restoredAnalysisTurns(history, turnHistory);
|
||||
const active = activeAnalysisTurn(historyTurns);
|
||||
const selectedTurnId = focusTurnId || (active ? String(active.id || '') : '');
|
||||
const selectedTurnId = focusTurnId || (active ? String(active.id || '') : pendingClarificationTurnId(historyTurns));
|
||||
setSessionId(id);
|
||||
setSessionReadOnly(history.readOnly === true);
|
||||
setTurns(historyTurns.filter(turn => !selectedTurnId || String(turn.id || '') !== selectedTurnId));
|
||||
writeAnalysisLocation(id, selectedTurnId || undefined);
|
||||
setLastTurn(null); setError(''); setRetryQuestion('');
|
||||
@@ -1167,11 +1242,15 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
const newSession = () => {
|
||||
userSelectionMade.current = true;
|
||||
beginAnalysisSelection(user.id);
|
||||
setBusy(false); setActiveTurnId(''); setStreamProgress('');
|
||||
setQueuedFollowup('');
|
||||
setBusy(false); setActiveTurnId('');
|
||||
navigationGeneration.current += 1; subscriptionGeneration.current += 1;
|
||||
cancellationRequest.current = null; setStopping(false); followRequest.current = null;
|
||||
submissionAttempt.current = null;
|
||||
streamController.current?.abort(); streamController.current = null;
|
||||
rememberAnalysisSession(user.id, '');
|
||||
setHistoryLoading(false);
|
||||
setSessionReadOnly(false);
|
||||
setSessionId(''); setTurns([]); setLastTurn(null); setQuery(''); setError(''); setRetryQuestion('');
|
||||
setSessionContext(null);
|
||||
setReleaseId(undefined);
|
||||
@@ -1208,7 +1287,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
const current = () => mounted.current && generation === subscriptionGeneration.current;
|
||||
const linkedSessionId = sessionOverride || sessionId;
|
||||
if (linkedSessionId) writeAnalysisLocation(linkedSessionId, id);
|
||||
setActiveTurnId(id); setBusy(true); setStreamProgress('分析任务已排队,等待服务端步骤…');
|
||||
setActiveTurnId(id); setBusy(true);
|
||||
const controller = new AbortController(); streamController.current = controller;
|
||||
let streamedResult: Record<string, unknown> = {};
|
||||
let terminalEventStatus = '';
|
||||
@@ -1229,7 +1308,6 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
if (event.id) eventCursors.current[id] = event.id;
|
||||
const data = event.data && typeof event.data === 'object' ? event.data as Record<string, unknown> : {};
|
||||
const messageText = typeof data.message === 'string' ? data.message : event.event === 'answer' ? '正在整理分析结论…' : '正在分析…';
|
||||
setStreamProgress(messageText);
|
||||
const eventResult = isObjectRecord(data.result) ? data.result : undefined;
|
||||
if (eventResult) streamedResult = { ...streamedResult, ...eventResult };
|
||||
const eventName = event.event.toUpperCase().replaceAll('.', '_').replaceAll('-', '_');
|
||||
@@ -1253,7 +1331,8 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
...(Array.isArray(data.steps) ? { steps: data.steps } : {}),
|
||||
...(typeof data.startedAt === 'string' ? { startedAt: data.startedAt } : {}),
|
||||
...(typeof data.updatedAt === 'string' ? { updatedAt: data.updatedAt } : {}),
|
||||
progressMessage: messageText,
|
||||
progressMessage: typeof data.message === 'string' ? messageText : prior.progressMessage,
|
||||
...(data.thinkingDelta ? { modelThinking: mergeModelThinking(modelThinkingEntries(prior), data.thinkingDelta) } : {}),
|
||||
...(Array.isArray(data.timeline) ? { timeline: data.timeline } : {}),
|
||||
plan: data.plan || prior.plan,
|
||||
...(eventResult ? { result: { ...priorResult, ...eventResult } } : {}),
|
||||
@@ -1267,7 +1346,6 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
} catch (streamError) {
|
||||
if (!current() || (controller.signal.aborted && !terminalEventStatus)) return;
|
||||
if (streamError instanceof ApiError && [401, 403, 404].includes(streamError.status)) throw streamError;
|
||||
if (!terminalEventStatus) setStreamProgress('连接暂时中断,后台仍在分析,正在恢复…');
|
||||
}
|
||||
|
||||
if (!current() || (controller.signal.aborted && !terminalEventStatus)) return;
|
||||
@@ -1279,7 +1357,6 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
catch (readError) {
|
||||
if (!current()) return;
|
||||
if (readError instanceof ApiError && [401, 403, 404].includes(readError.status)) throw readError;
|
||||
setStreamProgress('连接暂时中断,后台仍在分析,正在恢复…');
|
||||
}
|
||||
if (!current()) return;
|
||||
if (ANALYSIS_FINAL_STATUSES.has(String(detail.status || '').toUpperCase())) break;
|
||||
@@ -1293,7 +1370,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
}
|
||||
if (!current()) return;
|
||||
const settledTurn = settledAnalysisTurn(id, question, detail, streamedResult, terminalEventStatus);
|
||||
setLastTurn(settledTurn);
|
||||
setLastTurn(previous => ({ ...settledTurn, ...(previous?.id === id && previous._uiFollowKey ? { _uiFollowKey: previous._uiFollowKey } : {}) }));
|
||||
if (ANALYSIS_FINAL_STATUSES.has(String(settledTurn.status || '').toUpperCase())) {
|
||||
setRetryQuestion('');
|
||||
const parentSessionId = sessionOverride || sessionId;
|
||||
@@ -1351,38 +1428,68 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
};
|
||||
}, []);
|
||||
|
||||
const cancelTurn = async () => {
|
||||
if (!activeTurnId) return;
|
||||
const generation = navigationGeneration.current;
|
||||
const id = activeTurnId;
|
||||
const cancelAcceptedTurn = async (id: string, generation: number, question?: string): Promise<boolean> => {
|
||||
const attempt = submissionAttempt.current;
|
||||
const subscription = subscriptionGeneration.current;
|
||||
const current = () => mounted.current && generation === navigationGeneration.current
|
||||
&& subscription === subscriptionGeneration.current && submissionAttempt.current === attempt;
|
||||
try {
|
||||
await api.cancelAnalysisTurn(id, '用户请求停止');
|
||||
if (!mounted.current || generation !== navigationGeneration.current) return;
|
||||
setStreamProgress('正在停止分析…');
|
||||
if (!current()) return false;
|
||||
const detail = await api.analysisTurn(id);
|
||||
if (mounted.current && generation === navigationGeneration.current) {
|
||||
setLastTurn(previous => ({ ...detail, id, question: previous?.question }));
|
||||
if (current()) {
|
||||
setLastTurn(previous => ({ ...detail, id, question: question ?? previous?.question, ...(previous?._uiFollowKey ? { _uiFollowKey: previous._uiFollowKey } : {}) }));
|
||||
if (ANALYSIS_FINAL_STATUSES.has(String(detail.status || '').toUpperCase())) {
|
||||
subscriptionGeneration.current += 1;
|
||||
streamController.current?.abort(); streamController.current = null;
|
||||
setBusy(false); setActiveTurnId(''); setStreamProgress('');
|
||||
await loadSessions();
|
||||
if (attempt) attempt.inFlight = false;
|
||||
submissionAttempt.current = null;
|
||||
setBusy(false); setActiveTurnId('');
|
||||
void loadSessions();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
} catch (value) {
|
||||
if (current()) { cancellationRequest.current = null; setStopping(false); if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const cancelTurn = async () => {
|
||||
const generation = navigationGeneration.current;
|
||||
if (cancellationRequest.current?.generation === generation) return;
|
||||
cancellationRequest.current = { generation };
|
||||
setStopping(true);
|
||||
if (queuedFollowup) { setQuery(restoredAnalysisDraft(query, queuedFollowup)); setQueuedFollowup(''); }
|
||||
const attempt = submissionAttempt.current;
|
||||
const pending = requestSubmissionCancellation(attempt, generation);
|
||||
if (pending) {
|
||||
// Creating/retrying a turn can still be in transit. Remember the intent
|
||||
// and cancel the accepted turn, rather than cancelling an old retry state.
|
||||
if (!attempt?.acceptedTurnId) return;
|
||||
}
|
||||
const id = pending ? attempt!.acceptedTurnId : activeTurnId;
|
||||
if (id) await cancelAcceptedTurn(id, generation, pending ? attempt?.question : undefined);
|
||||
else if (!pending) { cancellationRequest.current = null; setStopping(false); }
|
||||
};
|
||||
|
||||
const retryTurn = async (turn: Record<string, unknown>) => {
|
||||
if (busy || historyLoading) return;
|
||||
if (sessionReadOnly || busy || historyLoading || submissionAttempt.current?.inFlight) return;
|
||||
const id = String(turn.id || '');
|
||||
const status = String(turn.status || '').toUpperCase();
|
||||
if (!id || !['FAILED', 'CANCELLED', 'PARTIAL'].includes(status)) return;
|
||||
const selection = beginAnalysisSelection(user.id);
|
||||
const generation = navigationGeneration.current;
|
||||
const current = () => mounted.current && generation === navigationGeneration.current;
|
||||
const question = typeof turn.question === 'string' ? turn.question : '';
|
||||
const targetSessionId = String(turn.sessionId || sessionId || '');
|
||||
setError(''); setBusy(true); setActiveTurnId(id); setStreamProgress('正在按原冻结计划重新排队…');
|
||||
const attempt = beginAnalysisSubmission(null, { sessionId: targetSessionId, question, generation });
|
||||
submissionAttempt.current = attempt;
|
||||
followRequest.current = attempt.idempotencyKey;
|
||||
followOutput.current = true;
|
||||
explicitlyFollowing.current = false;
|
||||
setLastTurn({ ...turn, status: 'QUEUED', _uiFollowKey: attempt.idempotencyKey });
|
||||
const current = () => mounted.current && generation === navigationGeneration.current && submissionAttempt.current === attempt;
|
||||
setError(''); setBusy(true); setActiveTurnId(id);
|
||||
try {
|
||||
const response = await api.retryAnalysisTurn(id);
|
||||
const retried = response.turn;
|
||||
@@ -1390,13 +1497,17 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
const retryId = String(retried.id || id);
|
||||
const retrySessionId = String(retried.sessionId || targetSessionId);
|
||||
if (!retrySessionId) throw new Error('无法确定原分析会话,已停止重试。');
|
||||
attempt.acceptedTurnId = retryId;
|
||||
setActiveTurnId(retryId);
|
||||
setSessionId(retrySessionId);
|
||||
setTurns(previous => previous.filter(item => String(item.id || '') !== id));
|
||||
if (attempt.cancelRequested && await cancelAcceptedTurn(retryId, generation, question)) return;
|
||||
if (!current()) return;
|
||||
const retriedDetail = await api.analysisTurn(retryId);
|
||||
if (!current()) return;
|
||||
setLastTurn({ ...retriedDetail, ...retried, id: retryId, sessionId: retrySessionId, question });
|
||||
setLastTurn({ ...retriedDetail, ...retried, id: retryId, sessionId: retrySessionId, question, _uiFollowKey: attempt.idempotencyKey });
|
||||
writeAnalysisLocation(retrySessionId, retryId);
|
||||
await loadSessions();
|
||||
void loadSessions();
|
||||
if (!current()) return;
|
||||
setBusy(false);
|
||||
if (current()) await followTurn(retryId, question, retrySessionId);
|
||||
@@ -1408,29 +1519,36 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
if (!current()) return;
|
||||
setLastTurn({ ...turn, ...detail, id, question, sessionId: targetSessionId });
|
||||
} catch (refreshError) { if (!onUnauthorized(refreshError)) setError(apiMessage(refreshError)); }
|
||||
setBusy(false); setActiveTurnId(''); setStreamProgress('');
|
||||
setBusy(false); setActiveTurnId('');
|
||||
} finally {
|
||||
attempt.inFlight = false;
|
||||
if (submissionAttempt.current === attempt) submissionAttempt.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const submit = async (question = query) => {
|
||||
if (!question.trim()) return;
|
||||
if (busy || historyLoading) return;
|
||||
if (sessionReadOnly || busy || historyLoading || submissionAttempt.current?.inFlight) return;
|
||||
followOutput.current = true;
|
||||
explicitlyFollowing.current = false;
|
||||
const selection = beginAnalysisSelection(user.id);
|
||||
rememberAnalysisSession(user.id, '');
|
||||
const generation = navigationGeneration.current;
|
||||
const current = () => mounted.current && generation === navigationGeneration.current;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setRetryQuestion(question.trim());
|
||||
if (lastTurn) setTurns(previous => previous.some(item => item.id === lastTurn.id) ? previous : [...previous, lastTurn]);
|
||||
setLastTurn({ question: question.trim(), status: 'QUEUED' });
|
||||
setQuery('');
|
||||
const context = sessionContext
|
||||
? { ...sessionContext, ...(releaseId ? { releaseId } : {}), ...(sourceResultRef ? { resultRef: sourceResultRef } : {}) }
|
||||
: releaseId || sourceResultRef
|
||||
? { ...(releaseId ? { releaseId } : {}), ...(sourceResultRef ? { resultRef: sourceResultRef } : {}) }
|
||||
: undefined;
|
||||
const attempt = beginAnalysisSubmission(submissionAttempt.current, { sessionId, question: question.trim(), context, generation });
|
||||
submissionAttempt.current = attempt;
|
||||
followRequest.current = attempt.idempotencyKey;
|
||||
const current = () => mounted.current && generation === navigationGeneration.current && submissionAttempt.current === attempt;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setRetryQuestion(question.trim());
|
||||
if (typeof lastTurn?.id === 'string' && lastTurn.id) setTurns(previous => previous.some(item => item.id === lastTurn.id) ? previous : [...previous, lastTurn]);
|
||||
setLastTurn({ question: question.trim(), status: 'QUEUED', _uiFollowKey: attempt.idempotencyKey });
|
||||
setQuery('');
|
||||
try {
|
||||
let selectedSessionId = sessionId;
|
||||
if (!selectedSessionId) {
|
||||
@@ -1440,22 +1558,65 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
rememberPendingAnalysisSession(user.id, selectedSessionId, selection);
|
||||
if (current()) setSessionId(selectedSessionId);
|
||||
}
|
||||
const started = await api.startAnalysisTurn(selectedSessionId, { question: question.trim(), ...(context ? { context } : {}), idempotencyKey: crypto.randomUUID() });
|
||||
attempt.sessionId = selectedSessionId;
|
||||
if (!current()) return;
|
||||
if (attempt.cancelRequested && !attempt.turnRequestStarted) {
|
||||
setLastTurn({ question: question.trim(), status: 'CANCELLED', _uiFollowKey: attempt.idempotencyKey });
|
||||
setRetryQuestion(''); setBusy(false);
|
||||
void loadSessions();
|
||||
return;
|
||||
}
|
||||
attempt.turnRequestStarted = true;
|
||||
const started = await api.startAnalysisTurn(selectedSessionId, { question: question.trim(), ...(context ? { context } : {}), idempotencyKey: attempt.idempotencyKey });
|
||||
const turn = started.turn;
|
||||
const turnId = String(turn.id || '');
|
||||
if (!turnId) throw new Error('服务端未返回分析任务编号');
|
||||
rememberPendingAnalysisSession(user.id, selectedSessionId, selection);
|
||||
if (!current()) return;
|
||||
setLastTurn({ ...turn, id: turnId, question: question.trim(), sessionId: selectedSessionId });
|
||||
attempt.uncertain = false;
|
||||
attempt.acceptedTurnId = turnId;
|
||||
setActiveTurnId(turnId);
|
||||
setLastTurn({ ...turn, id: turnId, question: question.trim(), sessionId: selectedSessionId, _uiFollowKey: attempt.idempotencyKey });
|
||||
writeAnalysisLocation(selectedSessionId, turnId);
|
||||
await loadSessions();
|
||||
if (attempt.cancelRequested && await cancelAcceptedTurn(turnId, generation, question.trim())) return;
|
||||
void loadSessions();
|
||||
if (!current()) return;
|
||||
setBusy(false);
|
||||
await followTurn(turnId, question.trim(), selectedSessionId);
|
||||
}
|
||||
catch (value) { if (current()) { if (!onUnauthorized(value)) { setError(apiMessage(value)); message.error(apiMessage(value)); } setBusy(false); } }
|
||||
catch (value) {
|
||||
attempt.uncertain = attempt.turnRequestStarted && !attempt.acceptedTurnId && submissionOutcomeUnknown(value);
|
||||
if (current()) {
|
||||
if (!onUnauthorized(value)) { setError(apiMessage(value)); message.error(apiMessage(value)); }
|
||||
if (!attempt.acceptedTurnId) setLastTurn({ question: question.trim(), _uiFollowKey: attempt.idempotencyKey, submissionNotice: attempt.uncertain
|
||||
? '提交结果暂未确认,请重试上一问恢复原任务。'
|
||||
: '本次提交未成功,请检查错误提示后重试。' });
|
||||
setBusy(false);
|
||||
}
|
||||
} finally {
|
||||
attempt.inFlight = false;
|
||||
if (submissionAttempt.current === attempt && !attempt.uncertain) submissionAttempt.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const queueFollowup = () => {
|
||||
if (sessionReadOnly || !busy || historyLoading || queuedFollowup || cancellationRequest.current || !query.trim()) return;
|
||||
setQueuedFollowup(query.trim());
|
||||
setQuery('');
|
||||
message.info('当前分析结束后发送追问');
|
||||
};
|
||||
|
||||
const sendQueuedFollowup = () => {
|
||||
if (!queuedFollowup || busy || historyLoading ||
|
||||
!ANALYSIS_FINAL_STATUSES.has(String(lastTurn?.status || '').toUpperCase())) return;
|
||||
const question = queuedFollowup;
|
||||
setQueuedFollowup('');
|
||||
return submit(question);
|
||||
};
|
||||
useEffect(() => { void sendQueuedFollowup(); }, [busy, historyLoading, lastTurn?.status, queuedFollowup]);
|
||||
|
||||
const composer = analysisComposerState(busy, stopping, historyLoading, query, queuedFollowup);
|
||||
|
||||
return <div className="management-page analysis-simple-page">
|
||||
<PageHeader title="智能分析" />
|
||||
{error && <Alert type="error" showIcon message="智能分析状态" description={error} action={retryQuestion && <Button size="small" onClick={() => void submit(retryQuestion)}>重试上一问</Button>} />}
|
||||
@@ -1472,30 +1633,59 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
</aside>
|
||||
<section className="panel analysis-chat-panel">
|
||||
<div className="analysis-conversation" ref={conversation} aria-live="polite" onWheel={event => {
|
||||
if (event.deltaY < 0 && event.currentTarget.scrollTop > 0) followOutput.current = false;
|
||||
const direction = event.deltaY < 0 ? 'up' : event.deltaY > 0 ? 'down' : null;
|
||||
if (direction) handleUserScrollIntent(event.currentTarget, direction);
|
||||
}} onPointerDown={event => {
|
||||
const element = event.currentTarget;
|
||||
const bounds = element.getBoundingClientRect();
|
||||
const scale = element.offsetWidth ? bounds.width / element.offsetWidth : 1;
|
||||
const scrollbarZone = Math.max(12, element.offsetWidth - element.clientWidth) * scale;
|
||||
scrollbarPointerActive.current = event.clientX >= bounds.right - scrollbarZone;
|
||||
}} onPointerUp={() => { scrollbarPointerActive.current = false; }} onPointerCancel={() => { scrollbarPointerActive.current = false; }} onTouchStart={event => {
|
||||
touchPosition.current = event.touches[0]?.clientY ?? null;
|
||||
}} onTouchMove={event => {
|
||||
const currentY = event.touches[0]?.clientY;
|
||||
if (currentY === undefined || touchPosition.current === null) return;
|
||||
const delta = currentY - touchPosition.current;
|
||||
touchPosition.current = currentY;
|
||||
if (Math.abs(delta) > 2) handleUserScrollIntent(event.currentTarget, delta > 0 ? 'up' : 'down');
|
||||
}} onTouchEnd={() => { touchPosition.current = null; }} onTouchCancel={() => { touchPosition.current = null; }} onKeyDown={event => {
|
||||
if (event.target !== event.currentTarget) return;
|
||||
const direction = ['ArrowUp', 'PageUp', 'Home'].includes(event.key) ? 'up'
|
||||
: ['ArrowDown', 'PageDown', 'End'].includes(event.key) ? 'down' : null;
|
||||
if (direction) handleUserScrollIntent(event.currentTarget, direction);
|
||||
}} onScroll={event => {
|
||||
if (!activePage.current) return;
|
||||
const element = event.currentTarget;
|
||||
followOutput.current = analysisScrollFollows(previousScrollTop.current, element.scrollTop,
|
||||
element.scrollHeight - element.clientHeight - element.scrollTop, followOutput.current);
|
||||
const distanceFromBottom = element.scrollHeight - element.clientHeight - element.scrollTop;
|
||||
const pointerIntent = scrollbarPointerActive.current && element.scrollTop !== previousScrollTop.current
|
||||
? element.scrollTop < previousScrollTop.current ? 'up' : 'down' : null;
|
||||
const intent = userScrollIntent.current || pointerIntent;
|
||||
clearUserScrollIntent();
|
||||
followOutput.current = analysisScrollFollows(distanceFromBottom, followOutput.current, intent);
|
||||
if (intent === 'up') explicitlyFollowing.current = false;
|
||||
else if (intent === 'down' && followOutput.current) explicitlyFollowing.current = true;
|
||||
previousScrollTop.current = element.scrollTop;
|
||||
readingPosition.current = element.scrollTop;
|
||||
if (followOutput.current) setHasNewContent(false);
|
||||
}}>
|
||||
{turns.map((turn, index) => <AnalysisTurn key={String(turn.id || index)} turn={turn} onRetry={(id) => void retryTurn(turns.find(item => String(item.id || '') === id) || turn)} onResume={id => { if (!historyLoading) void followTurn(id, String(turn.question || '')); }} retryDisabled={busy || historyLoading} />)}
|
||||
{lastTurn && <AnalysisTurn turn={lastTurn} onRetry={() => void retryTurn(lastTurn)} onResume={id => { if (!historyLoading) void followTurn(id, String(lastTurn.question || '')); }} retryDisabled={busy || historyLoading} />}
|
||||
{busy && <div className="analysis-progress"><span>{streamProgress || '正在分析…'}</span><Button size="small" danger onClick={() => void cancelTurn()}>停止分析</Button></div>}
|
||||
{turns.map((turn, index) => <AnalysisTurn key={String(turn.id || index)} turn={turn} onRetry={sessionReadOnly ? undefined : (id) => void retryTurn(turns.find(item => String(item.id || '') === id) || turn)} onResume={id => { if (!historyLoading) void followTurn(id, String(turn.question || '')); }} onUnauthorized={onUnauthorized} retryDisabled={sessionReadOnly || busy || historyLoading} />)}
|
||||
{lastTurn && <AnalysisTurn turn={lastTurn} onClarify={sessionReadOnly ? undefined : question => submit(question)} onRetry={sessionReadOnly ? undefined : () => void retryTurn(lastTurn)} onResume={id => { if (!historyLoading) void followTurn(id, String(lastTurn.question || '')); }} onUnauthorized={onUnauthorized} retryDisabled={sessionReadOnly || busy || historyLoading} />}
|
||||
{!turns.length && !lastTurn && !busy && <div className="analysis-empty"><RobotOutlined /><strong>想了解哪些质量情况?</strong><span>例如:9月汽车交通的合格率为什么下降?</span></div>}
|
||||
</div>
|
||||
{hasNewContent && <Button size="small" type="text" className="analysis-new-content" onClick={() => {
|
||||
const element = conversation.current;
|
||||
followOutput.current = true; setHasNewContent(false);
|
||||
followOutput.current = true; explicitlyFollowing.current = true; clearUserScrollIntent(); setHasNewContent(false);
|
||||
if (element) { element.scrollTop = element.scrollHeight; previousScrollTop.current = element.scrollTop; readingPosition.current = element.scrollTop; }
|
||||
}}>回到最新内容 ↓</Button>}
|
||||
<div className="analysis-composer">
|
||||
<Input.TextArea id="analysis-query" disabled={historyLoading} value={query} onChange={event => setQuery(event.target.value)} autoSize={{ minRows: 2, maxRows: 5 }} maxLength={1600} aria-label="质量问题" placeholder="直接描述问题,或继续追问…" onPressEnter={event => { if (!event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); void submit(); } }} />
|
||||
<div className="ai-actions"><span>Enter 发送 · Shift + Enter 换行</span><div className="analysis-composer-buttons">{user.roles.includes('SYSTEM_ADMIN') && <AnalysisApiSettings onUnauthorized={onUnauthorized} />}<Button type="primary" aria-label="发送" loading={busy} disabled={!query.trim() || busy || historyLoading} onClick={() => void submit()}>发送</Button></div></div>
|
||||
</div>
|
||||
{sessionReadOnly ? <div className="analysis-composer">
|
||||
<Alert type="info" message="此会话保留用于查看历史结果。" action={<Button type="primary" disabled={busy || historyLoading} onClick={() => { const fixedRelease=releaseId; newSession(); setReleaseId(fixedRelease); }}>新建会话继续分析</Button>} />
|
||||
{composer.showStop && <Button danger loading={stopping} disabled={composer.stopDisabled} onClick={() => void cancelTurn()}>停止分析</Button>}
|
||||
</div> : <div className="analysis-composer">
|
||||
<Input.TextArea id="analysis-query" disabled={historyLoading} value={query} onChange={event => setQuery(event.target.value)} autoSize={{ minRows: 2, maxRows: 5 }} maxLength={1600} aria-label="质量问题" placeholder="直接描述问题,或继续追问…" onPressEnter={event => { if (!event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); if (busy) queueFollowup(); else void submit(); } }} />
|
||||
{queuedFollowup && <div className="analysis-queued-followup" role="status"><span title={queuedFollowup}>待发送:{queuedFollowup}</span><Button type="text" size="small" onClick={() => { setQuery(restoredAnalysisDraft(query, queuedFollowup)); setQueuedFollowup(''); }}>取回编辑</Button></div>}
|
||||
<div className="ai-actions"><span>Enter {busy ? '排队发送' : '发送'} · Shift + Enter 换行</span><div className="analysis-composer-buttons">{user.roles.includes('SYSTEM_ADMIN') && <AnalysisApiSettings onUnauthorized={onUnauthorized} />}{composer.showStop && <Button danger aria-label="停止分析" loading={stopping} disabled={composer.stopDisabled} onClick={() => void cancelTurn()}>{stopping ? '正在停止' : '停止分析'}</Button>}<Button type="primary" aria-label={composer.sendLabel} disabled={composer.sendDisabled} onClick={() => { if (busy) queueFollowup(); else void submit(); }}>{composer.sendLabel}</Button></div></div>
|
||||
</div>}
|
||||
</section>
|
||||
</div>
|
||||
<Modal title="重命名会话" open={Boolean(renameTarget)} confirmLoading={renaming} okText="保存" cancelText="取消" okButtonProps={{ disabled: !renameTitle.trim() }} onCancel={() => { if (!renaming) setRenameTarget(null); }} onOk={() => void renameSession()}>
|
||||
@@ -1504,9 +1694,16 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
</div>;
|
||||
}
|
||||
|
||||
function AnalysisTurn({ turn, onResume, onRetry, retryDisabled = false }: { turn: Record<string, unknown>; onResume?: (turnId: string) => void; onRetry?: (turnId: string) => void; retryDisabled?: boolean }) {
|
||||
function AnalysisTurn({ turn: sourceTurn, onResume, onRetry, onClarify, onUnauthorized, retryDisabled = false }: { turn: Record<string, unknown>; onClarify?: (question: string) => void | Promise<void>; onResume?: (turnId: string) => void; onRetry?: (turnId: string) => void; onUnauthorized: (error: unknown) => boolean; retryDisabled?: boolean }) {
|
||||
const recovery=useAnalysisVisualRecovery(sourceTurn,onUnauthorized),turn=recovery.turn;
|
||||
const question = typeof turn.question === 'string' ? turn.question : '';
|
||||
if (!turn.id && typeof turn.submissionNotice === 'string') return <article className="analysis-turn">
|
||||
{question && <div className="analysis-question"><p>{question}</p></div>}
|
||||
<p className="analysis-chat-notice" role="status">{turn.submissionNotice}</p>
|
||||
</article>;
|
||||
const result = isObjectRecord(turn.result) ? turn.result : turn;
|
||||
const memberList = result.memberList ?? turn.memberList;
|
||||
const recordList = result.recordList ?? turn.recordList;
|
||||
const answer = partialAnswerIsOnlyProgress(turn) ? '' : typeof result.answer === 'string' ? result.answer : typeof turn.answer === 'string' ? turn.answer : '';
|
||||
const status = String(turn.status || result.status || '').toUpperCase();
|
||||
const visuals = result.visualSchemaVersion === 1 ? result.visuals : undefined;
|
||||
@@ -1519,27 +1716,32 @@ function AnalysisTurn({ turn, onResume, onRetry, retryDisabled = false }: { turn
|
||||
: status === 'PARTIAL' ? '本轮已保存查询过程,尚未形成最终答复。'
|
||||
: status === 'COMPLETED' ? '分析任务已完成,但未返回回答内容。'
|
||||
: failure;
|
||||
return <article className="analysis-turn">
|
||||
const scope = analysisScopeText(turn);
|
||||
return <article className="analysis-turn" data-analysis-turn-id={String(turn.id || '')} data-analysis-status={status}>
|
||||
{question && <div className="analysis-question"><p>{question}</p></div>}
|
||||
<AnalysisTurnMetadata turn={turn} status={status} />
|
||||
<AnalysisProcess turn={turn} />
|
||||
{scope && <p className="analysis-turn-scope" aria-label="本轮分析范围">{scope}</p>}
|
||||
<AnalysisProcess turn={turn} metadata={<AnalysisTurnMetadata turn={turn} status={status} compact />} />
|
||||
{(!resumable || !Array.isArray(turn.timeline || (isObjectRecord(turn.plan) ? turn.plan.timeline : undefined))) && (answer || !resumable || !retryDisabled) && <div className="analysis-answer">
|
||||
{answer ? <>
|
||||
{status === 'NEEDS_CLARIFICATION' && onClarify ? <AnalysisClarification turn={turn} disabled={retryDisabled} onContinue={onClarify} /> : answer ? <>
|
||||
{resumable ? <AiMarkdown content={answer} className="ai-answer" />
|
||||
: <AnalysisNarrative answer={answer} visuals={visuals} visualState={result.visualState} question={question} turnId={String(turn.id || '')} beforeExport={() => authorizeAnalysisSnapshot(turn)} />}
|
||||
: <AnalysisNarrative answer={answer} visuals={visuals} visualState={result.visualState} question={question} turnId={String(turn.id || '')} beforeExport={() => authorizeAnalysisSnapshot(turn)} turn={turn} />}
|
||||
</> : <p className={resumable ? 'analysis-chat-notice' : undefined}>{resumable ? '分析任务仍在运行,尚未返回完整回答。' : emptyStatus}</p>}
|
||||
{status === 'PARTIAL' && answer && <p className="analysis-chat-notice">{partialAnalysisNotice(result.stopReason || turn.stopReason || (isObjectRecord(turn.plan) ? turn.plan.stopReason : ''))}</p>}
|
||||
<div className="analysis-message-actions">
|
||||
{(reportMarkdown.trim() || reportHtml?.trim()) && <NativeAnalysisReport turn={turn} reportMarkdown={reportMarkdown} reportHtml={reportHtml} />}
|
||||
{!reportMarkdown.trim() && !reportHtml?.trim() && answer && ['COMPLETED', 'PARTIAL'].includes(status) && <AnalysisReportExport turn={turn} />}
|
||||
{['FAILED', 'CANCELLED', 'PARTIAL'].includes(status) && typeof turn.id === 'string' && onRetry && <Button size="small" type="text" disabled={retryDisabled} onClick={() => onRetry(String(turn.id))}>重新分析</Button>}
|
||||
{recovery.available&&<Button size="small" type="text" loading={recovery.recovering} disabled={retryDisabled} onClick={()=>void recovery.recover()}>重试图表</Button>}
|
||||
{['FAILED', 'CANCELLED', 'PARTIAL'].includes(status) && typeof turn.id === 'string' && onRetry && <Button size="small" type="text" disabled={retryDisabled||recovery.recovering} onClick={() => onRetry(String(turn.id))}>重新分析</Button>}
|
||||
{resumable && !retryDisabled && typeof turn.id === 'string' && onResume && <Button size="small" type="text" onClick={() => onResume(String(turn.id))}>继续分析</Button>}
|
||||
</div>
|
||||
{recovery.error&&<p className="analysis-chat-notice" role="alert">{recovery.error}</p>}
|
||||
</div>}
|
||||
{memberList !== undefined && memberList !== null && <AnalysisMemberListPanel turn={turn} value={memberList} onUnauthorized={onUnauthorized} />}
|
||||
{recordList !== undefined && recordList !== null && <AnalysisRecordListPanel turn={turn} value={recordList} onUnauthorized={onUnauthorized} />}
|
||||
</article>;
|
||||
}
|
||||
|
||||
function AnalysisTurnMetadata({ turn, status }: { turn: Record<string, unknown>; status: string }) {
|
||||
function AnalysisTurnMetadata({ turn, status, compact = false }: { turn: Record<string, unknown>; status: string; compact?: boolean }) {
|
||||
const [now, setNow] = useState(Date.now());
|
||||
const running = analysisIsRunning(status);
|
||||
useEffect(() => { if (!running) return; setNow(Date.now()); const timer = window.setInterval(() => setNow(Date.now()), 1000); return () => window.clearInterval(timer); }, [running]);
|
||||
@@ -1553,13 +1755,13 @@ function AnalysisTurnMetadata({ turn, status }: { turn: Record<string, unknown>;
|
||||
const stamp = (value: number) => new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }).format(value);
|
||||
const steps = Array.isArray(turn.steps) ? turn.steps : Array.isArray(plan.steps) ? plan.steps : [];
|
||||
const labels: Record<string, string> = { QUEUED: '排队中', RUNNING: '运行中', COMPLETED: '已完成', PARTIAL: '部分完成', FAILED: '未完成', CANCELLED: '已停止', NEEDS_CLARIFICATION: '待补充信息' };
|
||||
return <div className="analysis-turn-metadata" aria-label="分析运行信息">
|
||||
return <span className="analysis-turn-metadata" aria-label="分析运行信息">
|
||||
<span>{labels[status] || (running ? '运行中' : '分析记录')}</span>
|
||||
{durationText && <span>{running ? '已运行' : '运行时长'} {durationText}</span>}
|
||||
{start !== undefined && <span>开始 {stamp(start)}</span>}
|
||||
{!running && finish !== undefined && <span>{status === 'COMPLETED' ? '完成时间' : '结束时间'} {stamp(finish)}</span>}
|
||||
{steps.length > 0 && <span>工具调用 {steps.length} 次</span>}
|
||||
</div>;
|
||||
{!compact && start !== undefined && <span>开始 {stamp(start)}</span>}
|
||||
{!compact && !running && finish !== undefined && <span>{status === 'COMPLETED' ? '完成时间' : '结束时间'} {stamp(finish)}</span>}
|
||||
{!compact && steps.length > 0 && <span>工具调用 {steps.length} 次</span>}
|
||||
</span>;
|
||||
}
|
||||
|
||||
function isObjectRecord(value: unknown): value is Record<string, unknown> {
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { RightOutlined } from '@ant-design/icons';
|
||||
import { thinkingTextFrame, type ModelThinking } from './analysisModelThinking';
|
||||
|
||||
export function AnalysisThinkingBlock({ entry, running }: { entry: ModelThinking; running: boolean }) {
|
||||
const active = running && entry.status === 'running';
|
||||
const [open, setOpen] = useState(false);
|
||||
const priorId = useRef(entry.id);
|
||||
const [text, setText] = useState(entry.text);
|
||||
const shown = useRef(entry.text);
|
||||
useEffect(() => {
|
||||
if (priorId.current !== entry.id) { priorId.current = entry.id; setOpen(false); }
|
||||
else if (!active) setOpen(false);
|
||||
// A late adjacent call must not reopen a disclosure that already closed.
|
||||
}, [active, entry.id]);
|
||||
useEffect(() => {
|
||||
const target = entry.text;
|
||||
if (!active || !open || window.matchMedia('(prefers-reduced-motion: reduce)').matches || !target.startsWith(shown.current)) {
|
||||
shown.current = target; setText(target); return;
|
||||
}
|
||||
const from = shown.current, start = performance.now();
|
||||
let frame = 0;
|
||||
const update = (now: number) => {
|
||||
const next = thinkingTextFrame(from, target, now - start);
|
||||
shown.current = next; setText(next);
|
||||
if (next !== target) frame = requestAnimationFrame(update);
|
||||
};
|
||||
frame = requestAnimationFrame(update);
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [entry.id, entry.text, active, open]);
|
||||
if (!entry.text) return null;
|
||||
return <details className="analysis-thinking-block" aria-live="off" open={open} onToggle={event => setOpen(event.currentTarget.open)} data-process-id={entry.id}>
|
||||
<summary>深度思考<RightOutlined aria-hidden="true" /></summary>
|
||||
<div className="analysis-thinking-text"><pre>{active && open ? text : entry.text}</pre></div>
|
||||
</details>;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { configurationDateTime } from './configurationName';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Checkbox, Empty, Form, Input, InputNumber, Modal, Progress, Select, Spin, Steps, Tag } from 'antd';
|
||||
import { QualityTable as Table } from './QualityTable';
|
||||
@@ -531,7 +532,7 @@ export function MasterWorkbookUpload({ kind, base, onUnauthorized, onComplete, s
|
||||
const format = suggestion?.keyFormat || inferFormat(first?.headers || [], nextKind);
|
||||
setSelectedKind(nextKind); setSheetName(first?.name || ''); setKeyFormat(format);
|
||||
setColumns(nextKind === 'standardBundle' ? {} : autoMatch(first?.headers || [], nextKind, format, response.suggestedTables || [], first?.name || ''));
|
||||
setName(`${nextKind === 'standardBundle' ? '整本基础数据' : kindLabel(nextKind)}·${file.name.replace(/\.xlsx$/i, '')}`.slice(0, 120));
|
||||
setName(simplified ? configurationDateTime(new Date()) : `${nextKind === 'standardBundle' ? '整本基础数据' : kindLabel(nextKind)}·${file.name.replace(/\.xlsx$/i, '')}`.slice(0, 120));
|
||||
setResult(null); setConfirmed(false);
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(failure(value)); }
|
||||
finally { setBusy(false); if (fileInput.current) fileInput.current.value = ''; }
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Alert, Button, Drawer, Empty, Segmented, Spin } from 'antd';
|
||||
import { api } from './api';
|
||||
import { AnalysisVisuals } from './AnalysisVisuals';
|
||||
import { QualityTable } from './QualityTable';
|
||||
import { authorizeAnalysisSnapshot, reportSnapshotIdentity } from './analysisSnapshot';
|
||||
import { productDrilldownQuery, productTrendVisual, resolveProductDrilldown, type ProductDrilldownBinding, type ProductDrilldownView } from './analysisProductDrilldown';
|
||||
import { publicJson } from './publicDataDisplay';
|
||||
import type { AnalysisVisual } from './analysisVisualsModel';
|
||||
import type { FocusProductRow } from './analysisReportModel';
|
||||
import type { FineDefectTopResponse, RecordsResponse, Stage } from './types';
|
||||
import './analysis-product-drilldown.css';
|
||||
|
||||
export interface ProductDrilldownSelection {
|
||||
binding: ProductDrilldownBinding;
|
||||
row: FocusProductRow;
|
||||
view: ProductDrilldownView;
|
||||
trigger: HTMLElement;
|
||||
}
|
||||
type Loaded = { kind: 'defects'; data: FineDefectTopResponse } | { kind: 'trend'; visuals: AnalysisVisual[] } | { kind: 'records'; data: RecordsResponse };
|
||||
const titles = { defects: '看缺陷', trend: '看趋势', records: '看来源明细' };
|
||||
const numberText = (value: number | null) => value === null ? '—' : value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
|
||||
/** Keeps the report mounted and its scroll position intact while querying the
|
||||
* clicked row's immutable filters through the existing read-only APIs. */
|
||||
export function AnalysisProductDrilldown({ turn, selection, onClose }: { turn: Record<string, unknown>; selection: ProductDrilldownSelection; onClose: () => void }) {
|
||||
const { binding } = selection;
|
||||
const [open, setOpen] = useState(true);
|
||||
const [view, setView] = useState(selection.view);
|
||||
const [stage, setStage] = useState<Stage>(binding.stages[0]);
|
||||
const [periodIndex, setPeriodIndex] = useState(0);
|
||||
const [page, setPage] = useState(1);
|
||||
const [revision, setRevision] = useState(0);
|
||||
const [loaded, setLoaded] = useState<Loaded | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const controller = new AbortController();
|
||||
setLoading(true); setLoaded(null); setError('');
|
||||
const load = async (): Promise<Loaded> => {
|
||||
// Permission and stored-answer changes are checked before every request,
|
||||
// including retries and paging; the backend also enforces current access.
|
||||
const snapshot = await api.analysisTurnSnapshot(binding.turnId);
|
||||
if (!['COMPLETED', 'PARTIAL', 'CANCELLED'].includes(String(snapshot.status || '').toUpperCase()) || reportSnapshotIdentity(snapshot) !== reportSnapshotIdentity(turn)) throw new Error('分析结果或访问权限已变化,请重新打开本轮分析。');
|
||||
if (controller.signal.aborted) throw new DOMException('Aborted', 'AbortError');
|
||||
const current = resolveProductDrilldown(snapshot, selection.row);
|
||||
if (!current.binding || JSON.stringify(current.binding) !== JSON.stringify(binding)) throw new Error('本条查询范围已变化,请关闭后重新打开。');
|
||||
const query = productDrilldownQuery(binding, binding.periods[periodIndex].period);
|
||||
if (view === 'records') return { kind: 'records', data: await api.records({ ...query, stage, page, pageSize: 25 }, controller.signal) };
|
||||
if (view === 'defects') {
|
||||
const { view: _view, trendGranularity: _granularity, ...filters } = query;
|
||||
const data = await api.fineDefectTop({ ...filters, stage, mode: 'top', dimension: 'defect', limit: 100 }, controller.signal);
|
||||
if (data.releaseId !== binding.query.releaseId) throw new Error('查询返回的数据版本已变化,请重新打开本轮分析。');
|
||||
return { kind: 'defects', data };
|
||||
}
|
||||
const snapshots = await Promise.all(binding.periods.map(period => api.metrics(productDrilldownQuery(binding, period.period), controller.signal)));
|
||||
return { kind: 'trend', visuals: productTrendVisual(binding, snapshots) };
|
||||
};
|
||||
load().then(value => { if (!controller.signal.aborted) setLoaded(value); })
|
||||
.catch(value => { if (!controller.signal.aborted) setError(value instanceof Error ? value.message : '读取失败,请重试。'); })
|
||||
.finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||||
return () => controller.abort();
|
||||
}, [open, view, stage, periodIndex, page, revision, binding, turn, selection.row]);
|
||||
|
||||
const restoreFocus = (visible: boolean) => {
|
||||
if (visible) return;
|
||||
if (selection.trigger.isConnected) selection.trigger.focus({ preventScroll: true });
|
||||
onClose();
|
||||
};
|
||||
const sourceColumns = [
|
||||
{ title: '来源文件', dataIndex: 'sourceFile', width: 220 },
|
||||
{ title: '工作表', dataIndex: 'sheet', width: 130 },
|
||||
{ title: '原始行号', dataIndex: 'rowNumber', width: 90, align: 'center' as const },
|
||||
{ title: '产业部', dataIndex: 'department', width: 150 },
|
||||
{ title: '业务分组', dataIndex: 'group', width: 170 },
|
||||
{ title: '原始字段', key: 'raw', width: 220, render: (_: unknown, row: RecordsResponse['rows'][number]) => <details className="analysis-product-source-row"><summary>查看原始字段</summary><dl>{Object.entries(JSON.parse(publicJson(row.raw || {}) || '{}') as Record<string, unknown>).map(([name, value]) => <div key={name}><dt>{name}</dt><dd>{value === null ? '—' : typeof value === 'object' ? JSON.stringify(value) : String(value)}</dd></div>)}</dl></details> },
|
||||
];
|
||||
return <Drawer className="analysis-product-drawer" title={binding.product} open={open} onClose={() => setOpen(false)} afterOpenChange={restoreFocus} width="min(1080px, 100vw)" destroyOnHidden>
|
||||
<div className="analysis-product-controls">
|
||||
<Segmented aria-label="产品下钻内容" value={view} options={(Object.keys(titles) as ProductDrilldownView[]).map(value => ({ label: titles[value], value }))} onChange={value => { setView(value as ProductDrilldownView); setPage(1); }} />
|
||||
{view !== 'trend' && binding.stages.length > 1 && <Segmented aria-label="下钻阶段" value={stage} options={binding.stages.map(value => ({ label: value === 'black' ? '黑片' : '亮片', value }))} onChange={value => { setStage(value as Stage); setPage(1); }} />}
|
||||
{view !== 'trend' && binding.periods.length > 1 && <Segmented aria-label="下钻期间" value={periodIndex} options={binding.periods.map((period, index) => ({ label: period.label, value: index }))} onChange={value => { setPeriodIndex(Number(value)); setPage(1); }} />}
|
||||
</div>
|
||||
{(view === 'trend' || binding.periods.length === 1 || binding.stages.length === 1) && <p className="analysis-product-context">{view === 'trend' ? [...binding.periods].reverse().map(period => period.label).join(' → ') : binding.periods.length === 1 ? binding.periods[0].label : ''}{binding.stages.length === 1 ? `${binding.periods.length === 1 || view === 'trend' ? ' · ' : ''}${binding.stages[0] === 'black' ? '黑片' : '亮片'}` : ''}</p>}
|
||||
{error ? <Alert type="error" showIcon message="下钻加载失败" description={error} action={<Button size="small" onClick={() => setRevision(value => value + 1)}>重试</Button>} />
|
||||
: loading ? <div className="analysis-product-loading" role="status"><Spin />正在读取{titles[view].slice(1)}…</div>
|
||||
: loaded?.kind === 'trend' ? loaded.visuals.length ? <AnalysisVisuals visuals={loaded.visuals} embedded visualState="ready" beforeExport={() => authorizeAnalysisSnapshot(turn)} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="原分析期间内没有可用趋势数据" />
|
||||
: loaded?.kind === 'defects' ? <>
|
||||
<p className="analysis-product-context">来源细分重量(kg),用于缺陷核查。</p>
|
||||
{loaded.data.sourceRows > 0 && loaded.data.coverage?.available !== false && loaded.data.rows.length ? <QualityTable rowKey="key" dataSource={loaded.data.rows} pagination={false} columns={[
|
||||
{ title: '具体缺陷', dataIndex: 'label' }, { title: '报废类别', dataIndex: 'category', width: 150 },
|
||||
{ title: '来源重量(kg)', dataIndex: 'weight', align: 'right', width: 170, render: numberText },
|
||||
]} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="原分析范围内没有可用的细分缺陷数据" />}
|
||||
{loaded.data.coverage?.categories?.some(category => category.reconciliationStatus !== 'RECONCILED') && <p className="analysis-product-context">部分来源细分尚不能与正式报废重量核对一致,不能据此计算总体贡献。</p>}
|
||||
</> : loaded?.kind === 'records' ? <QualityTable rowKey="id" dataSource={loaded.data.rows} columns={sourceColumns} scroll={{ x: 1050 }} locale={{ emptyText: '原分析范围内没有来源记录' }} pagination={{ current: page, pageSize: 25, total: loaded.data.total, showSizeChanger: false, showTotal: total => `共 ${total} 条`, onChange: next => setPage(next) }} /> : null}
|
||||
</Drawer>;
|
||||
}
|
||||
@@ -1,5 +1,26 @@
|
||||
import { Table as AntdTable } from 'antd';
|
||||
import type { ColumnType, TableProps } from 'antd/es/table';
|
||||
import type { ColumnsType, ColumnType, TableProps } from 'antd/es/table';
|
||||
import { createContext, isValidElement, useContext, useState } from 'react';
|
||||
import { CompactTableCell } from './CompactTableCell';
|
||||
|
||||
export const CompactManagementTables = createContext(false);
|
||||
|
||||
function compactColumns<T extends object>(columns: ColumnsType<T>): ColumnsType<T> {
|
||||
return columns.map(column => {
|
||||
const title = typeof column.title === 'function' ? column.title : <CompactTableCell>{column.title}</CompactTableCell>;
|
||||
if ('children' in column) return { ...column, title, children: compactColumns(column.children) };
|
||||
return {
|
||||
...column, title, ellipsis: { showTitle: false },
|
||||
render: (value, record, index) => {
|
||||
const content = column.render ? column.render(value, record, index) : value;
|
||||
if (content && typeof content === 'object' && !isValidElement(content) && !Array.isArray(content) && 'children' in content) {
|
||||
return { ...content, children: <CompactTableCell>{content.children}</CompactTableCell> };
|
||||
}
|
||||
return <CompactTableCell>{content}</CompactTableCell>;
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
type QualityTableProps<T extends object> = TableProps<T> & {
|
||||
/** Offset for tables whose page is controlled outside Ant Design. */
|
||||
@@ -13,12 +34,20 @@ export function QualityTable<T extends object>({
|
||||
indexOffset = 0,
|
||||
className,
|
||||
size = 'small',
|
||||
onChange,
|
||||
...props
|
||||
}: QualityTableProps<T>) {
|
||||
const compact = useContext(CompactManagementTables);
|
||||
const pageConfig = typeof pagination === 'object' && pagination !== null ? pagination : undefined;
|
||||
const page = pageConfig?.current ?? 1;
|
||||
const pageSize = pageConfig?.pageSize ?? (pagination === undefined ? 10 : dataSource?.length ?? 0);
|
||||
const pageOffset = indexOffset + Math.max(0, page - 1) * pageSize;
|
||||
const [innerPage, setInnerPage] = useState(() => ({ current: pageConfig?.defaultCurrent ?? 1, pageSize: pageConfig?.defaultPageSize ?? 10 }));
|
||||
const pageSize = pageConfig?.pageSize ?? innerPage.pageSize;
|
||||
const total = pageConfig?.total ?? dataSource?.length ?? 0;
|
||||
const page = Math.min(pageConfig?.current ?? innerPage.current, Math.max(1, Math.ceil(total / pageSize)));
|
||||
const pageOffset = indexOffset + (pagination === false ? 0 : Math.max(0, page - 1) * pageSize);
|
||||
const handleChange: TableProps<T>['onChange'] = (next, filters, sorter, extra) => {
|
||||
setInnerPage({ current: next.current ?? 1, pageSize: next.pageSize ?? pageSize });
|
||||
onChange?.(next, filters, sorter, extra);
|
||||
};
|
||||
const indexColumn: ColumnType<T> = {
|
||||
title: '序号',
|
||||
key: '__quality-row-number__',
|
||||
@@ -30,13 +59,15 @@ export function QualityTable<T extends object>({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="quality-table-frame">
|
||||
<div className={`quality-table-frame${compact ? ' quality-table-compact' : ''}`}>
|
||||
<AntdTable<T>
|
||||
{...props}
|
||||
className={['quality-table', className].filter(Boolean).join(' ')}
|
||||
columns={[indexColumn, ...(columns ?? [])]}
|
||||
tableLayout={props.tableLayout ?? (compact ? 'fixed' : undefined)}
|
||||
columns={[indexColumn, ...(compact ? compactColumns(columns ?? []) : columns ?? [])]}
|
||||
dataSource={dataSource}
|
||||
pagination={pagination}
|
||||
onChange={handleChange}
|
||||
size={size}
|
||||
bordered
|
||||
/>
|
||||
|
||||
@@ -22,6 +22,8 @@ import {
|
||||
LineChartOutlined,
|
||||
LoadingOutlined,
|
||||
LogoutOutlined,
|
||||
MenuFoldOutlined,
|
||||
MenuUnfoldOutlined,
|
||||
RobotOutlined,
|
||||
SettingOutlined,
|
||||
TeamOutlined,
|
||||
@@ -36,10 +38,10 @@ import PersonalAccount, { type AccountTab } from './PersonalAccount';
|
||||
|
||||
import { CachedWorkspacePages, type WorkspaceNavigation } from './CachedWorkspacePages';
|
||||
|
||||
export type PageKey = 'overall' | 'department' | 'group' | 'product' | 'basis' | 'analysis' | 'sources' | 'imports' | 'rules' | 'mappings' | 'masterData' | 'tasks' | 'access';
|
||||
export type PageKey = 'overall' | 'department' | 'group' | 'product' | 'blackProduct' | 'brightProduct' | 'basis' | 'analysis' | 'sources' | 'imports' | 'rules' | 'mappings' | 'masterData' | 'tasks' | 'access';
|
||||
|
||||
const pageNames: Record<PageKey, string> = {
|
||||
overall: '总体汇总', department: '产业部汇总', group: '产业部-业务分组', product: '产品汇总',
|
||||
overall: '总体汇总', department: '产业部汇总', group: '产业部-业务分组', product: '产品汇总', blackProduct: '黑片汇总', brightProduct: '亮片汇总',
|
||||
basis: '数据与计算依据', analysis: '智能分析', sources: '数据接入', imports: '导入与校验',
|
||||
rules: '计算规则', mappings: '对应关系', masterData: '基础数据', tasks: '任务与监控', access: '权限与审计',
|
||||
};
|
||||
@@ -68,6 +70,8 @@ const navGroups = [
|
||||
['department', '产业部汇总', ApartmentOutlined],
|
||||
['group', '产业部-业务分组', DeploymentUnitOutlined],
|
||||
['product', '产品汇总', DatabaseOutlined],
|
||||
['blackProduct', '黑片汇总', DatabaseOutlined],
|
||||
['brightProduct', '亮片汇总', DatabaseOutlined],
|
||||
] as const,
|
||||
},
|
||||
{
|
||||
@@ -110,8 +114,15 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
|
||||
const [sessionLoading, setSessionLoading] = useState(true);
|
||||
const [sessionError, setSessionError] = useState('');
|
||||
const [accountTab, setAccountTab] = useState<AccountTab | null>(null);
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(() => {
|
||||
try { return localStorage.getItem('quality-sidebar-collapsed') === 'true'; } catch { return false; }
|
||||
});
|
||||
const workspaceNavigation = useRef<WorkspaceNavigation>(null);
|
||||
|
||||
useEffect(() => {
|
||||
try { localStorage.setItem('quality-sidebar-collapsed', String(sidebarCollapsed)); } catch { /* Local appearance preferences are optional. */ }
|
||||
}, [sidebarCollapsed]);
|
||||
|
||||
useEffect(() => {
|
||||
const syncFromLocation = () => {
|
||||
const url = new URL(window.location.href);
|
||||
@@ -183,11 +194,11 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
|
||||
if (!user) return <LoginPage onSuccess={setUser} />;
|
||||
|
||||
return (
|
||||
<div className="app-shell">
|
||||
<aside className="sidebar">
|
||||
<div className={`app-shell${sidebarCollapsed ? ' sidebar-collapsed' : ''}`}>
|
||||
<aside className="sidebar" id="workspace-sidebar">
|
||||
<button className="brand" onClick={() => navigate('overall')} aria-label="回到总体汇总">
|
||||
<span className="brand-mark" aria-hidden="true"><i /><i /><i /></span>
|
||||
<span>质量数据分析平台</span>
|
||||
<span className="brand-copy">质量数据分析平台</span>
|
||||
</button>
|
||||
<div className="workspace-caption">分析工作台</div>
|
||||
<nav className="side-navigation" aria-label="主导航">
|
||||
@@ -195,15 +206,17 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
|
||||
<div className="nav-group" key={group.label}>
|
||||
<div className="nav-group-label">{group.label}</div>
|
||||
{group.items.map(([key, label, Icon]) => (
|
||||
<Tooltip key={key} title={sidebarCollapsed ? label : undefined} placement="right">
|
||||
<button
|
||||
key={key}
|
||||
className={`nav-item ${page === key ? 'active' : ''}`}
|
||||
aria-current={page === key ? 'page' : undefined}
|
||||
aria-label={label}
|
||||
onClick={() => navigate(key)}
|
||||
>
|
||||
<Icon aria-hidden="true" />
|
||||
<span>{label}</span>
|
||||
<span className="nav-item-label">{label}</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
@@ -219,7 +232,11 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
|
||||
|
||||
<main className="main-column">
|
||||
<header className="topbar">
|
||||
<div className="breadcrumb"><span>质量分析</span><span className="breadcrumb-slash">/</span><strong>{pageNames[page]}</strong></div>
|
||||
<div className="workspace-heading">
|
||||
<Tooltip title={sidebarCollapsed ? '展开侧边栏' : '收起侧边栏'}><Button className="sidebar-toggle" type="text" icon={sidebarCollapsed ? <MenuUnfoldOutlined/> : <MenuFoldOutlined/>}
|
||||
aria-label={sidebarCollapsed ? '展开侧边栏' : '收起侧边栏'} aria-expanded={!sidebarCollapsed} aria-controls="workspace-sidebar" onClick={() => setSidebarCollapsed(value => !value)}/></Tooltip>
|
||||
<div className="breadcrumb"><span>质量分析</span><span className="breadcrumb-slash">/</span><strong>{pageNames[page]}</strong></div>
|
||||
</div>
|
||||
<div className="topbar-actions">
|
||||
<Dropdown
|
||||
trigger={['click']}
|
||||
|
||||
+160
-102
@@ -1,5 +1,6 @@
|
||||
import { BusinessValue } from './BusinessValue';
|
||||
import { usePageCache } from './pageCache';
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import * as echarts from 'echarts/core';
|
||||
import { BarChart, LineChart } from 'echarts/charts';
|
||||
import { GraphicComponent, GridComponent, LegendComponent, MarkLineComponent, TooltipComponent } from 'echarts/components';
|
||||
@@ -21,7 +22,7 @@ import {
|
||||
Tooltip,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { DownloadOutlined, InfoCircleOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
|
||||
import { DownloadOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
|
||||
import { ApiError, api, decodeQueryValueList, encodeQueryValueList } from './api';
|
||||
import type {
|
||||
DefectMetric,
|
||||
@@ -45,10 +46,13 @@ import { previousCompleteMonth, previousCompleteQuarter } from './periodDefaults
|
||||
import { defectWeightRate } from './trendMetrics';
|
||||
import './query-motion.css';
|
||||
import { ExtraQueryFilters } from './ExtraQueryFilters';
|
||||
import { freezeSourceRecordsQuery } from './sourceRecordsContext';
|
||||
import { downloadMetricWorkbook } from './metricWorkbook';
|
||||
|
||||
echarts.use([BarChart, LineChart, GraphicComponent, GridComponent, LegendComponent, MarkLineComponent, TooltipComponent, SVGRenderer]);
|
||||
|
||||
const MONTHS = Array.from({ length: 12 }, (_, index) => `${String(index + 1).padStart(2, '0')}月`);
|
||||
const CHART_FONT_SIZE = 12;
|
||||
const TABLE_PAGE_SIZE = 20;
|
||||
const SUMMARY_PAGE_SIZE = 15;
|
||||
const SUMMARY_PAGE_SIZE_OPTIONS = ['10', '15', '20', '50', '100'];
|
||||
@@ -69,6 +73,10 @@ function rateText(value: number | null | undefined): string {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? `${(value * 100).toFixed(2)}%` : '—';
|
||||
}
|
||||
|
||||
function defectRateLabel(label: string): string {
|
||||
return `${label.replace(/(?:总重量|重量)(?:合计)?$/, '').replace(/率$/, '')}率`;
|
||||
}
|
||||
|
||||
function rateNumber(value: number | null | undefined): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value * 100 : null;
|
||||
}
|
||||
@@ -203,7 +211,7 @@ function escapeTooltipText(value: string): string {
|
||||
return value.replace(/[&<>"']/g, character => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character]!);
|
||||
}
|
||||
|
||||
function queryFromLocation(search = window.location.search): Partial<QueryParams> {
|
||||
export function queryFromLocation(search = window.location.search): Partial<QueryParams> {
|
||||
const context = new URLSearchParams(search).get('context');
|
||||
if (!context) return {};
|
||||
try {
|
||||
@@ -294,6 +302,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
const [search, setSearch] = useState(initialQuery.productSearch || '');
|
||||
const [appliedSearch, setAppliedSearch] = useState(initialQuery.productSearch || '');
|
||||
const [fullFields, setFullFields] = useState(false);
|
||||
const [defectDisplay, setDefectDisplay] = useState<'weight' | 'rate'>('weight');
|
||||
const [data, setData] = useState<MetricsResponse | null>(null);
|
||||
const [dataKey, setDataKey] = useState('');
|
||||
const [trendData, setTrendData] = useState<TrendMetricRow[]>([]);
|
||||
@@ -317,9 +326,12 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
const [recordsOpen, setRecordsOpen] = useState(false);
|
||||
const [recordStage, setRecordStage] = useState<Stage>('black');
|
||||
const [recordMonth, setRecordMonth] = useState<number>();
|
||||
const [recordQuerySnapshot, setRecordQuerySnapshot] = useState<QueryParams | null>(null);
|
||||
const [basisOpen, setBasisOpen] = useState(false);
|
||||
const trendAnchorTop = useRef<number | null>(null);
|
||||
const tableContent = useRef<HTMLDivElement>(null);
|
||||
const summaryExport = useRef<{ exportExcel: () => Promise<void> }>(null);
|
||||
const [summaryExporting, setSummaryExporting] = useState(false);
|
||||
const trendSection = useRef<HTMLElement>(null);
|
||||
const refreshSeen = useRef(refreshKey);
|
||||
useEffect(() => {
|
||||
@@ -540,12 +552,6 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
return orderedRows.filter(row => [row.label, row.department, row.group, row.product, row.projectGroup].filter(Boolean).join(' ').toLocaleLowerCase().includes(term));
|
||||
}, [page, period, currentMetricsData, appliedSearch, year, view, department, allowedGroupSet]);
|
||||
|
||||
const openRecords = useCallback((row: MetricRow | null, stage: Stage, selectedMonth?: number) => {
|
||||
setSelectedRecord(row);
|
||||
setRecordStage(stage);
|
||||
setRecordMonth(selectedMonth);
|
||||
setRecordsOpen(true);
|
||||
}, []);
|
||||
const captureTrendAnchor = useCallback(() => {
|
||||
trendAnchorTop.current = trendSection.current?.getBoundingClientRect().top ?? null;
|
||||
}, []);
|
||||
@@ -622,6 +628,12 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
: currentMetricsData;
|
||||
// 产品月度下钻复用当前对象的服务端指标,汇总表仍保留父层结果供返回。
|
||||
const summaryMetricsData = drilledProduct ? activeDefectData : currentMetricsData;
|
||||
const openRecords = useCallback((row: MetricRow | null, stage: Stage, selectedMonth?: number, sourceQuery?: QueryParams, sourceData?: MetricsResponse | null) => {
|
||||
const source = sourceData === undefined ? summaryMetricsData : sourceData;
|
||||
if (!source?.release?.id) { message.info('指标数据尚未就绪,请重新查询后打开来源明细。'); return; }
|
||||
setRecordQuerySnapshot(freezeSourceRecordsQuery(sourceQuery || (drilledProduct ? defectQueryParams : queryParams), source.release.id, view, row, selectedMonth));
|
||||
setSelectedRecord(row); setRecordStage(stage); setRecordMonth(selectedMonth); setRecordsOpen(true);
|
||||
}, [summaryMetricsData, drilledProduct, defectQueryParams, queryParams, view, message]);
|
||||
const summaryMetricsError = drilledProduct ? trendObjectMetricsError : currentMetricsError;
|
||||
const summaryBusy = drilledProduct ? trendObjectMetricsLoading || !summaryMetricsData && !summaryMetricsError : queryBusy;
|
||||
const rowForSummary = summaryMetricsData?.summary;
|
||||
@@ -727,7 +739,8 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
|
||||
<div className="query-quality-summary" aria-label="数据覆盖摘要">
|
||||
<span>{drilledProduct && <>{drilledProduct} · </>}{summaryMetricsData ? <>来源覆盖 {summaryMetricsData.coverage.sourceMonths.filter(item => item.blackRows > 0 || item.brightRows > 0).length} 个月 · 参与计算 {summaryMetricsData.coverage.includedRows.toLocaleString('zh-CN')} / 原始 {summaryMetricsData.coverage.rawRows.toLocaleString('zh-CN')} 行 · 未分类 {summaryMetricsData.coverage.excludedBlankRows.toLocaleString('zh-CN')} 行({includeUnassigned ? '已包含' : '本次排除'})</> : summaryBusy ? '正在更新来源覆盖…' : '来源覆盖暂不可用'}</span>
|
||||
<Button type="link" size="small" disabled={!summaryMetricsData} onClick={() => setBasisOpen(true)}>质量范围说明</Button>
|
||||
<Button type="link" size="small" disabled={!summaryMetricsData} onClick={() => setBasisOpen(true)}>计算口径</Button>
|
||||
|
||||
</div>
|
||||
|
||||
{['department', 'group', 'product'].includes(page) && <>
|
||||
@@ -742,15 +755,23 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
<Input allowClear={!drilledProduct} disabled={Boolean(drilledProduct)} maxLength={view === 'product' ? 256 : undefined} prefix={<SearchOutlined />} placeholder={view === 'product' ? '输入关键词或完整产品名称' : `搜索${view === 'group' ? '业务分组' : '汇总对象'}`} value={drilledProduct || search} onChange={event => setSearch(event.target.value)} aria-label={view === 'product' ? '搜索产品名称并同步筛选指标和趋势' : '搜索汇总对象'} />
|
||||
<Button type="primary" disabled={Boolean(drilledProduct)} onClick={() => applySearch()} aria-label="开始搜索">搜索</Button>
|
||||
<Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整字段', value: 'full' }]} onChange={value => setFullFields(value === 'full')} aria-label="字段显示" />
|
||||
<Tooltip title="点击综合合格率可查看计算依据"><Button type="text" icon={<InfoCircleOutlined />} aria-label="查看计算依据" onClick={() => setBasisOpen(true)} /></Tooltip>
|
||||
<Segmented value={defectDisplay} options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={value=>setDefectDisplay(value as typeof defectDisplay)} aria-label="不良显示方式" />
|
||||
{!drilledProduct && (view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else { setGroup([]); setDepartment([]); setViewOverride('department'); } }}>{view === 'product' ? '返回业务分组' : '返回产业部'}</Button>}
|
||||
{drilledProduct && <Button onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回产品汇总</Button>}
|
||||
<Tooltip title="导出 Excel"><Button type="text" icon={<DownloadOutlined />} aria-label="导出 Excel" loading={summaryExporting} disabled={queryBusy || summaryBusy || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length} onClick={async () => {
|
||||
setSummaryExporting(true);
|
||||
try { await summaryExport.current?.exportExcel(); }
|
||||
catch (error) { message.error(`导出失败:${chooseError(error)}`); }
|
||||
finally { setSummaryExporting(false); }
|
||||
}} /></Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mobile-scroll-hint">横向滑动查看完整指标</div>
|
||||
<Spin spinning={queryBusy}><div ref={tableContent} className="query-table-content" style={{ minHeight: queryBusy ? tableHeight.current : undefined }} aria-busy={queryBusy} inert={!currentMetricsData}>
|
||||
{drilledProduct ? (
|
||||
<MetricTable
|
||||
ref={summaryExport}
|
||||
exportFilename={`${drilledProduct || scopeName}质量汇总-${year}${drilledProduct || period === 'year' ? '' : period === 'month' ? `-${String(month).padStart(2, '0')}` : `-Q${quarter}`}-${fullFields ? '完整字段' : '关键指标'}`}
|
||||
rows={drilledTrendData}
|
||||
view="overall"
|
||||
layoutView="product"
|
||||
@@ -759,6 +780,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
month={month}
|
||||
quarter={quarter}
|
||||
fullFields={fullFields}
|
||||
defectDisplay={defectDisplay}
|
||||
rateBasis={rateBasis}
|
||||
onDetail={openRecords}
|
||||
onBasis={() => setBasisOpen(true)}
|
||||
@@ -766,12 +788,15 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
/>
|
||||
) : (
|
||||
<MetricTable
|
||||
ref={summaryExport}
|
||||
exportFilename={`${drilledProduct || scopeName}质量汇总-${year}${drilledProduct || period === 'year' ? '' : period === 'month' ? `-${String(month).padStart(2, '0')}` : `-Q${quarter}`}-${fullFields ? '完整字段' : '关键指标'}`}
|
||||
rows={visibleRows}
|
||||
view={view}
|
||||
period={period}
|
||||
month={month}
|
||||
quarter={quarter}
|
||||
fullFields={fullFields}
|
||||
defectDisplay={defectDisplay}
|
||||
rateBasis={rateBasis}
|
||||
onDetail={openRecords}
|
||||
onBasis={() => setBasisOpen(true)}
|
||||
@@ -802,6 +827,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
<Segmented value={trendMode} options={[{ label: '合格率与产量', value: 'production' }, { label: '不良率', value: 'defects' }, { label: `${trendGranularity === 'quarter' ? '季度' : trendGranularity === 'year' ? '年度' : '月度'}数据`, value: 'data' }]} onChange={value => setTrendMode(value as typeof trendMode)} aria-label="趋势视图" />
|
||||
</div>
|
||||
<div className="trend-controls">
|
||||
{trendMode==='data'&&<Segmented value={defectDisplay} options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={value=>setDefectDisplay(value as typeof defectDisplay)} aria-label="趋势不良显示方式"/>}
|
||||
<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={trendGranularity} options={[{ label: '按月', value: 'month' }, { label: '按季度', value: 'quarter' }, { label: '按年度', value: 'year' }]} onChange={value => setTrendGranularity(value)} aria-label="趋势粒度" /></label>
|
||||
<label className="query-field trend-object"><span>趋势对象</span><Select {...readableSelectPopup} allowClear placeholder={`当前${scopeName}筛选`} value={trendObject || undefined} options={trendOptions} onChange={setSynchronizedTrendObject} aria-label="趋势对象" />
|
||||
</label>
|
||||
@@ -809,7 +835,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
</div>
|
||||
<div className="trend-chart-shell" aria-busy={trendLoading}>
|
||||
{trendMode === 'data'
|
||||
? <TrendTable rows={visibleTrendData} rateBasis={rateBasis} onMonth={selectTrendPeriod} />
|
||||
? <TrendTable rows={visibleTrendData} defectDisplay={defectDisplay} rateBasis={rateBasis} onMonth={selectTrendPeriod} />
|
||||
: <TrendChart rows={visibleTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={currentTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
|
||||
{(trendLoading || (useSummaryTrend && queryBusy)) && <span className="trend-refresh-indicator"><Spin size="small" />正在更新趋势</span>}
|
||||
</div>
|
||||
@@ -818,7 +844,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
|
||||
<section className="panel section-panel defects-panel">
|
||||
<div className="section-heading-row">
|
||||
<SectionHeading title="不良具体构成" subtitle={`${year}年${period === 'month' ? MONTHS[month - 1] : period === 'quarter' ? `第${quarter}季度` : '全年'}${trendObject ? ` · ${trendObject}` : ''} · 占比为分类报废内占比;废率为该类重量 ÷ 同阶段适用总重量`} />
|
||||
<SectionHeading title="不良具体构成" subtitle={`${year}年${period === 'month' ? MONTHS[month - 1] : period === 'quarter' ? `第${quarter}季度` : '全年'}${trendObject ? ` · ${trendObject}` : ''} · 占比为分类报废内占比;废率为该类重量 ÷ 同阶段总重量`} />
|
||||
</div>
|
||||
{trendObjectMetricsLoading && <div className="defect-pareto-status"><Spin size="small" />正在更新当前趋势对象的不良数据</div>}
|
||||
{trendObjectMetricsError && <Alert showIcon type="warning" message="当前趋势对象的不良数据读取失败" description={trendObjectMetricsError} />}
|
||||
@@ -830,7 +856,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
{trendObjectMetricsLoading || trendObjectMetricsError
|
||||
? null
|
||||
: items.length
|
||||
? <DefectBreakdown items={items} stage={stage} totalWeight={activeDefectData?.summary?.[stage]?.totalWeight} maximum={Math.max(0, ...items.map(item => item.weight ?? 0))} onDetail={() => openRecords(null, stage)} />
|
||||
? <DefectBreakdown items={items} stage={stage} totalWeight={activeDefectData?.summary?.[stage]?.totalWeight} maximum={Math.max(0, ...items.map(item => item.weight ?? 0))} onDetail={() => openRecords(null, stage, undefined, defectQueryParams, activeDefectData)} />
|
||||
: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前条件下暂无不良分类数据" />}
|
||||
</section>;
|
||||
})}
|
||||
@@ -840,41 +866,41 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
</div>
|
||||
</>
|
||||
|
||||
<div className="query-footer"><span>查询数据由服务端按当前数据返回</span><Button type="link" disabled={!currentMetricsData} onClick={() => setBasisOpen(true)}>计算口径</Button></div>
|
||||
|
||||
<Modal open={basisOpen} title={`${rateBasis === 'original' ? '综合合格率' : '综合调整率'}计算依据`} onCancel={() => setBasisOpen(false)} footer={<Button onClick={() => setBasisOpen(false)}>关闭</Button>} width={680}>
|
||||
<div className="basis-card"><span>当前服务返回的{rateBasis === 'original' ? '综合合格率' : '综合调整率'}</span><strong>{rateText(visibleCompositeRate(rowForSummary, rateBasis))}</strong><span>黑片 {rateText(visibleStageRate(rowForSummary, 'black'))} · {rateBasis === 'original' ? '亮片' : '亮片调整率'} {rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))}</span></div>
|
||||
<p className="basis-copy">正式指标按当前数据绑定的规则与筛选条件计算。综合合格率是黑片合格率与亮片合格率相乘的业务指标。以下公式及空值处理说明来自指标服务;缺少阶段来源时不展示对应率。</p>
|
||||
|
||||
<Modal open={basisOpen} title={`${rateBasis === 'original' ? '综合合格率' : '综合调整率'}计算口径`} onCancel={() => setBasisOpen(false)} footer={<Button onClick={() => setBasisOpen(false)}>关闭</Button>} width={680}>
|
||||
<div className="basis-card"><span>当前{rateBasis === 'original' ? '综合合格率' : '综合调整率'}</span><strong>{rateText(visibleCompositeRate(rowForSummary, rateBasis))}</strong><span>黑片 {rateText(visibleStageRate(rowForSummary, 'black'))} · {rateBasis === 'original' ? '亮片' : '亮片调整率'} {rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))}</span></div>
|
||||
<p className="basis-copy">以下为当前查询实际使用的公式、适用条件与空值处理规则。月、季、年先汇总计算分量,再按生效公式计算。</p>
|
||||
<dl className="basis-details">
|
||||
<dt>综合公式</dt><dd>{formulaText(compositeFormula)}</dd>
|
||||
<dt>黑片公式</dt><dd>{formulaText(formulaDescriptions.blackRate)}</dd>
|
||||
<dt>{rateBasis === 'original' ? '亮片公式' : '亮片调整公式'}</dt><dd>{formulaText(brightFormula)}</dd>
|
||||
<dt>统计范围</dt><dd>{year}年{period === 'month' ? ` ${MONTHS[month - 1]}` : period === 'quarter' ? ` 第${quarter}季度` : '度'} · {drilledProduct || scopeName}</dd>
|
||||
<dt>适用总重量</dt><dd>黑片 {numberText(rowForSummary?.black?.totalWeight)} kg · 亮片 {numberText(rowForSummary?.bright?.totalWeight)} kg</dd>
|
||||
<dt>总重量</dt><dd>黑片 {numberText(rowForSummary?.black?.totalWeight)} kg · 亮片 {numberText(rowForSummary?.bright?.totalWeight)} kg</dd>
|
||||
<dt>覆盖行数</dt><dd>黑片 {rowForSummary?.coverage.blackRows ?? '—'} · 亮片 {rowForSummary?.coverage.brightRows ?? '—'}</dd>
|
||||
<dt>来源行覆盖</dt><dd>原始 {summaryMetricsData?.coverage.rawRows ?? '—'} · 参与 {summaryMetricsData?.coverage.includedRows ?? '—'} · 未分类行 {includeUnassigned ? '(已选择包含)' : '(本次排除)'} {summaryMetricsData?.coverage.excludedBlankRows ?? '—'}</dd>
|
||||
<dt>业务分类映射</dt><dd>未映射 {summaryMetricsData?.coverage.unmappedRows ?? '—'} 行</dd>
|
||||
<dt>项目组维度</dt><dd>{summaryMetricsData?.coverage.projectGroupUnconfiguredRows ?? '—'} 行未配置项目组归属。该计数不等于排除行数;是否参与指标由当前筛选及规则决定。</dd>
|
||||
</dl>
|
||||
<details><summary>查看服务返回的公式原文</summary><pre>{JSON.stringify(formulaDescriptions, null, 2)}</pre></details>
|
||||
|
||||
</Modal>
|
||||
|
||||
<RecordsDrawer
|
||||
{recordsOpen && recordQuerySnapshot && <RecordsDrawer
|
||||
key={JSON.stringify({ query: recordQuerySnapshot, stage: recordStage })}
|
||||
open={recordsOpen}
|
||||
row={selectedRecord}
|
||||
stage={recordStage}
|
||||
onStage={setRecordStage}
|
||||
onClose={() => { setSelectedRecord(null); setRecordMonth(undefined); setRecordsOpen(false); }}
|
||||
query={drilledProduct ? defectQueryParams : queryParams}
|
||||
view={view}
|
||||
query={recordQuerySnapshot}
|
||||
month={recordMonth}
|
||||
onUnauthorized={onUnauthorized}
|
||||
/>
|
||||
/>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricCard({ primary, label, value, note, stage, onClick }: { primary?: boolean; label: string; value: string; note?: string; stage?: Stage; onClick: () => void }) {
|
||||
export function MetricCard({ primary, label, value, note, stage, onClick }: { primary?: boolean; label: string; value: string; note?: string; stage?: Stage; onClick: () => void }) {
|
||||
const parts = value.match(/^(.*?)(%| kg)$/);
|
||||
return <button className={`metric-card ${primary ? 'primary' : ''} ${stage || ''}`} onClick={onClick}>
|
||||
<span className="metric-label">{stage && <i className={`stage-dot ${stage}`} />}{label}</span>
|
||||
@@ -883,7 +909,7 @@ function MetricCard({ primary, label, value, note, stage, onClick }: { primary?:
|
||||
</button>;
|
||||
}
|
||||
|
||||
function DefectBreakdown({ items, stage, totalWeight, maximum, onDetail }: { items: DefectMetric[]; stage: Stage; totalWeight?: number | null; maximum: number; onDetail: () => void }) {
|
||||
export function DefectBreakdown({ items, stage, totalWeight, maximum, onDetail }: { items: DefectMetric[]; stage: Stage; totalWeight?: number | null; maximum: number; onDetail: () => void }) {
|
||||
return <div className="defect-list">
|
||||
<div className="defect-header"><span>不良分类</span><span aria-hidden="true" /><span>重量 / kg</span><span>占比</span><span>废率</span></div>
|
||||
{items.map(item => <button className="defect-row" key={item.name} onClick={onDetail}>
|
||||
@@ -898,8 +924,8 @@ function DefectBreakdown({ items, stage, totalWeight, maximum, onDetail }: { ite
|
||||
|
||||
const FINE_DEFECT_FIELD_COUNT = 33;
|
||||
|
||||
function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthorized }: {
|
||||
releaseId?: string; query: QueryParams; externalScrapWeight?: number | null; onUnauthorized: (error: unknown) => boolean;
|
||||
export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthorized, onlyStage }: {
|
||||
releaseId?: string; query: QueryParams; externalScrapWeight?: number | null; onUnauthorized: (error: unknown) => boolean; onlyStage?: Stage;
|
||||
}) {
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
|
||||
@@ -911,6 +937,7 @@ function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthoriz
|
||||
year: query.year,
|
||||
...(query.productSearch ? { productSearch: query.productSearch } : {}),
|
||||
...(query.extraFilters ? { extraFilters: query.extraFilters } : {}),
|
||||
...(query.columnFilters?.length ? { columnFilters: query.columnFilters } : {}),
|
||||
...(query.month != null ? { month: query.month } : {}),
|
||||
...(query.quarter != null ? { quarter: query.quarter } : {}),
|
||||
...(query.department ? { department: query.department } : {}),
|
||||
@@ -918,7 +945,7 @@ function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthoriz
|
||||
...(query.product ? { product: query.product } : {}),
|
||||
...(query.projectGroup ? { projectGroup: query.projectGroup } : {}),
|
||||
...(query.includeUnassigned ? { includeUnassigned: true } : {}),
|
||||
}), [query.year, query.month, query.quarter, query.department, query.group, query.product, query.productSearch, query.projectGroup, query.extraFilters, query.includeUnassigned]);
|
||||
}), [query.year, query.month, query.quarter, query.department, query.group, query.product, query.productSearch, query.projectGroup, query.extraFilters, query.columnFilters, query.includeUnassigned]);
|
||||
const fineQueryKey = JSON.stringify(fineQuery);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -929,9 +956,9 @@ function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthoriz
|
||||
setLoading(true);
|
||||
setError('');
|
||||
Promise.all([
|
||||
api.fineDefectTop({ ...base, stage: 'black' }, controller.signal),
|
||||
api.fineDefectTop({ ...base, stage: 'bright' }, controller.signal),
|
||||
]).then(([black, bright]) => setResponses({ black, bright }))
|
||||
onlyStage === 'bright' ? Promise.resolve({kind:'fine_defect_top' as const,releaseId,sourceRows:0,rows:[]}) : api.fineDefectTop({ ...base, stage: 'black' }, controller.signal),
|
||||
onlyStage === 'black' ? Promise.resolve({kind:'fine_defect_top' as const,releaseId,sourceRows:0,rows:[]}) : api.fineDefectTop({ ...base, stage: 'bright' }, controller.signal),
|
||||
]).then(([black, bright]) => { if (!controller.signal.aborted) setResponses({ black, bright }); })
|
||||
.catch(value => {
|
||||
if (controller.signal.aborted) return;
|
||||
if (onUnauthorized(value)) return;
|
||||
@@ -939,7 +966,7 @@ function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthoriz
|
||||
})
|
||||
.finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||||
return () => controller.abort();
|
||||
}, [releaseId, fineQueryKey, onUnauthorized]);
|
||||
}, [releaseId, fineQueryKey, onUnauthorized, onlyStage]);
|
||||
|
||||
useEffect(() => {
|
||||
const observer = new MutationObserver(() => setThemeRevision(value => value + 1));
|
||||
@@ -966,12 +993,12 @@ function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthoriz
|
||||
weight: row.weight,
|
||||
kind: 'source' as const,
|
||||
})));
|
||||
if (typeof externalScrapWeight === 'number' && Number.isFinite(externalScrapWeight) && externalScrapWeight > 0) {
|
||||
if (onlyStage !== 'bright' && typeof externalScrapWeight === 'number' && Number.isFinite(externalScrapWeight) && externalScrapWeight > 0) {
|
||||
raw.push({ key: 'black:externalScrap', label: '黑片·外废(仅大类重量)', category: '外废', weight: externalScrapWeight, kind: 'category' });
|
||||
}
|
||||
return raw.filter(item => typeof item.weight === 'number' && Number.isFinite(item.weight) && item.weight > 0)
|
||||
.sort((left, right) => right.weight! - left.weight! || left.label.localeCompare(right.label, 'zh-CN'));
|
||||
}, [responses, externalScrapWeight]);
|
||||
}, [responses, externalScrapWeight, onlyStage]);
|
||||
const totalWeight = items.reduce((total, item) => total + (item.weight || 0), 0);
|
||||
const visibleFieldCount = responses ? (responses.black.sourceFields?.length || 0) + (responses.bright.sourceFields?.length || 0) : 0;
|
||||
|
||||
@@ -994,7 +1021,7 @@ function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthoriz
|
||||
animationDuration: 420,
|
||||
animationDurationUpdate: 520,
|
||||
grid: { left: 68, right: 72, top: 48, bottom: items.length > 12 ? 92 : 62, containLabel: true },
|
||||
legend: { top: 8, data: ['报废重量', '累计占比'], textStyle: { color: ink, fontSize: 11 } },
|
||||
legend: { top: 8, data: ['报废重量', '累计占比'], textStyle: { color: ink, fontSize: CHART_FONT_SIZE } },
|
||||
tooltip: {
|
||||
trigger: 'axis',
|
||||
axisPointer: { type: 'shadow' },
|
||||
@@ -1013,13 +1040,13 @@ function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthoriz
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: items.map(item => item.label),
|
||||
axisLabel: { color: ink, rotate: 35, interval: 0, hideOverlap: true, fontSize: 10 },
|
||||
axisLabel: { color: ink, rotate: 35, interval: 0, hideOverlap: true, fontSize: CHART_FONT_SIZE },
|
||||
axisLine: { lineStyle: { color: line } },
|
||||
axisTick: { alignWithLabel: true, lineStyle: { color: line } },
|
||||
},
|
||||
yAxis: [
|
||||
{ type: 'value', name: '报废重量 / kg', nameTextStyle: { color: ink, fontSize: 10 }, axisLabel: { color: ink, fontSize: 10 }, splitLine: { lineStyle: { color: line, type: 'dashed' } } },
|
||||
{ type: 'value', name: '累计占比', min: 0, max: 100, nameTextStyle: { color: ink, fontSize: 10 }, axisLabel: { color: ink, fontSize: 10, formatter: '{value}%' }, splitLine: { show: false } },
|
||||
{ type: 'value', name: '报废重量 / kg', nameTextStyle: { color: ink, fontSize: CHART_FONT_SIZE }, axisLabel: { color: ink, fontSize: CHART_FONT_SIZE }, splitLine: { lineStyle: { color: line, type: 'dashed' } } },
|
||||
{ type: 'value', name: '累计占比', min: 0, max: 100, nameTextStyle: { color: ink, fontSize: CHART_FONT_SIZE }, axisLabel: { color: ink, fontSize: CHART_FONT_SIZE, formatter: '{value}%' }, splitLine: { show: false } },
|
||||
],
|
||||
series: [
|
||||
{ name: '报废重量', type: 'bar', z: 1, barMaxWidth: 36, data: items.map(item => ({ value: item.weight, itemStyle: { color: item.kind === 'category' ? '#9aa4b2' : item.key.startsWith('black:') ? blue : teal } })) },
|
||||
@@ -1034,8 +1061,8 @@ function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthoriz
|
||||
.filter(item => item.reconciliationStatus !== 'RECONCILED' && item.reconciliationStatus !== 'UNAVAILABLE').length
|
||||
: 0;
|
||||
|
||||
return <section className="defect-pareto-section" aria-label="综合报废重量柏拉图">
|
||||
<div className="defect-pareto-heading"><strong>黑片与亮片综合报废重量柏拉图</strong><span>{responses ? `细分源字段 ${visibleFieldCount} / ${FINE_DEFECT_FIELD_COUNT} 项${incompleteCategories ? ` · ${incompleteCategories} 类细分数据未与正式大类完全核对` : ''}` : '按当前筛选范围汇总全部可见细分报废重量'}</span></div>
|
||||
return <section className="defect-pareto-section" aria-label={onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '综合报废重量柏拉图'}>
|
||||
<div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong><span>{responses ? `细分源字段 ${visibleFieldCount}${onlyStage ? '' : ` / ${FINE_DEFECT_FIELD_COUNT}`} 项${incompleteCategories ? ` · ${incompleteCategories} 类细分数据未与正式大类完全核对` : ''}` : '按当前筛选范围汇总全部可见细分报废重量'}</span></div>
|
||||
{loading && <div className="defect-pareto-status"><Spin size="small" />正在汇总细分报废重量</div>}
|
||||
{error && <Alert showIcon type="warning" message="细分报废重量读取失败" description={error} />}
|
||||
{!loading && !releaseId && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有已发布数据版本" />}
|
||||
@@ -1044,7 +1071,7 @@ function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthoriz
|
||||
</section>;
|
||||
}
|
||||
|
||||
function SectionHeading({ title, subtitle }: { title: string; subtitle?: string }) {
|
||||
export function SectionHeading({ title, subtitle }: { title: string; subtitle?: string }) {
|
||||
return <div className="section-heading"><h2>{title}</h2>{subtitle && <span>{subtitle}</span>}</div>;
|
||||
}
|
||||
|
||||
@@ -1059,13 +1086,14 @@ function useCompactTable() {
|
||||
return compact;
|
||||
}
|
||||
|
||||
function MetricTable({
|
||||
rows, view, layoutView = view, pageSizeOverride, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, emptyText = '当前条件下暂无数据',
|
||||
export function MetricTable({
|
||||
ref, exportFilename, rows, view, layoutView = view, pageSizeOverride, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, onlyStage, defectDisplay = 'weight', emptyText = '当前条件下暂无数据',
|
||||
}: {
|
||||
ref?: React.Ref<{ exportExcel: () => Promise<void> }>; exportFilename: string;
|
||||
rows: MetricRow[]; view: ViewKind; layoutView?: ViewKind; pageSizeOverride?: number; period: PeriodKind; month: number; quarter: number; fullFields: boolean;
|
||||
rateBasis: 'original' | 'withoutHeadquartersScrap';
|
||||
onDetail: (row: MetricRow | null, stage: Stage, month?: number) => void; onBasis: () => void; onDrilldown: (row: MetricRow) => void;
|
||||
emptyText?: string;
|
||||
emptyText?: string; onlyStage?: Stage; defectDisplay?: 'weight'|'rate';
|
||||
}) {
|
||||
const compact = useCompactTable();
|
||||
const blackDefects = fullFields ? defectsFor(rows, 'black') : [];
|
||||
@@ -1080,30 +1108,47 @@ function MetricTable({
|
||||
onDetail(row, stage, isOverall && period === 'year' ? monthNumber((row as TrendMetricRow).month) || undefined : isOverall && period === 'month' ? month : undefined);
|
||||
};
|
||||
const numeric = (label: string, stage: Stage, field: 'qualifiedWeight' | 'scrapWeight' | 'totalWeight' | 'rate' | 'headquartersScrapWeight', className = '') => ({
|
||||
title: compact ? `${stage === 'black' ? '黑片' : '亮片'}${label}` : label,
|
||||
title: `${compact ? stage === 'black' ? '黑片' : '亮片' : ''}${defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? defectRateLabel(label) : label}`,
|
||||
exportRate: defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight'),
|
||||
key: `${stage}-${field}`,
|
||||
align: 'center' as const,
|
||||
width: field === 'rate' ? 116 : 145,
|
||||
className: `${field === 'rate' ? `rate-cell ${stage}` : 'weight-cell'} ${className}`,
|
||||
render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" onClick={() => openRow(row, stage)}>{field === 'rate' ? rateText(visibleStageRate(row, stage)) : numberText(stageValue(row, stage, field))}</Button>,
|
||||
render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{field === 'rate' ? rateText(visibleStageRate(row, stage)) : defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? rateText(defectWeightRate(stageValue(row, stage, field),stageValue(row, stage, 'totalWeight'))) : numberText(stageValue(row, stage, field))}</Button>,
|
||||
});
|
||||
const defectColumns = (stage: Stage, names: string[]) => names.map(name => ({
|
||||
title: compact ? `${stage === 'black' ? '黑片' : '亮片'}${name}` : name,
|
||||
title: `${compact ? stage === 'black' ? '黑片' : '亮片' : ''}${defectDisplay === 'rate' ? defectRateLabel(name) : name}`,
|
||||
exportRate: defectDisplay === 'rate',
|
||||
key: `${stage}-defect-${name}`,
|
||||
align: 'center' as const,
|
||||
width: 130,
|
||||
render: (_: unknown, row: MetricRow) => {
|
||||
const value = defectList(row, stage).find(item => item.name === name);
|
||||
return <Button type="link" className="table-value" onClick={() => openRow(row, stage)}>{numberText(value?.weight ?? null)}</Button>;
|
||||
return <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{defectDisplay === 'rate' ? rateText(defectWeightRate(value?.weight,stageValue(row,stage,'totalWeight'))) : numberText(value?.weight ?? null)}</Button>;
|
||||
},
|
||||
}));
|
||||
const columns: ColumnsType<MetricRow> = [
|
||||
{ title: isOverall ? period === 'year' ? '月份' : '统计期间' : view === 'group' ? '产业部 / 业务分组' : view === 'product' ? '产品规格' : view === 'projectGroup' ? '项目组' : view === 'department' ? '产业部' : '对象', key: 'object', dataIndex: 'label', fixed: 'left', width: compact ? isOverall ? 100 : 180 : layoutView === 'product' ? 300 : layoutView === 'group' ? 260 : 220, render: (_: unknown, row) => <span className="object-cell">{view === 'department' || view === 'group' || view === 'product' ? <Button type="link" className="object-drilldown" onClick={() => onDrilldown(row)}>{title(row)} <span>›</span></Button> : <strong>{title(row)}</strong>}{view === 'group' && row.department && <small>{row.department}</small>}{view === 'product' && row.group && <small>{row.group}</small>}</span> },
|
||||
{ title: <button className="header-link" onClick={onBasis}>{rateBasis === 'original' ? '综合合格率' : '综合调整率'}</button>, key: 'compositeRate', dataIndex: 'compositeRate', align: 'center', fixed: compact ? undefined : 'left', width: 140, className: 'combined-column', render: (_: number | null, row: MetricRow) => <button className="combined-value" onClick={onBasis}>{rateText(visibleCompositeRate(row, rateBasis))}</button> },
|
||||
{ title: <span className="stage-heading black"><i />黑片</span>, children: [numeric('合格重量', 'black', 'qualifiedWeight'), ...(fullFields ? [numeric('适用总重量', 'black', 'totalWeight')] : []), numeric('报废重量', 'black', 'scrapWeight'), ...defectColumns('black', blackDefects), numeric('合格率', 'black', 'rate')] },
|
||||
{ title: <span className="stage-heading bright"><i />亮片</span>, children: [numeric('合格重量', 'bright', 'qualifiedWeight'), ...(fullFields ? [numeric('适用总重量', 'bright', 'totalWeight')] : []), numeric('报废重量', 'bright', 'scrapWeight'), ...(fullFields ? [numeric('本部报废重量', 'bright', 'headquartersScrapWeight')] : []), ...defectColumns('bright', brightDefects), { ...numeric(rateBasis === 'original' ? '合格率' : '不含本部报废调整率', 'bright', 'rate'), render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" onClick={() => openRow(row, 'bright')}>{rateText(visibleStageRate(row, 'bright', rateBasis))}</Button> }] },
|
||||
{ title: '操作', key: 'actions', fixed: compact ? undefined : 'right', width: 100, align: 'center', render: (_: unknown, row) => (row as TrendMetricRow).noData ? <span>—</span> : <Button type="link" onClick={() => openRow(row, 'black')}>来源明细</Button> },
|
||||
const allColumns: ColumnsType<MetricRow> = [
|
||||
{ title: isOverall ? period === 'year' ? '月份' : '统计期间' : view === 'group' ? '产业部 / 业务分组' : view === 'product' ? '产品规格' : view === 'projectGroup' ? '项目组' : view === 'department' ? '产业部' : '对象', key: 'object', dataIndex: 'label', fixed: 'left', width: compact ? isOverall ? 100 : 180 : layoutView === 'product' ? 300 : layoutView === 'group' ? 260 : 220, render: (_: unknown, row) => <span className="object-cell">{view === 'department' || view === 'group' || view === 'product' ? <Button type="link" className="object-drilldown" style={{ userSelect: 'text', WebkitUserSelect: 'text' }} onClick={() => { if (window.getSelection()?.isCollapsed !== false) onDrilldown(row); }}>{title(row)} <span>›</span></Button> : <strong>{title(row)}</strong>}{view === 'group' && row.department && <small>{row.department}</small>}</span> },
|
||||
{ title: <button className="header-link" onClick={onBasis}>{rateBasis === 'original' ? '综合合格率' : '综合调整率'}</button>, key: 'compositeRate', dataIndex: 'compositeRate', align: 'center', fixed: compact ? undefined : 'left', width: 140, className: 'combined-column', render: (_: number | null, row: MetricRow) => <button className="combined-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{rateText(visibleCompositeRate(row, rateBasis))}</button> },
|
||||
{ key: 'stage-black', title: <span className="stage-heading black"><i />黑片</span>, children: [numeric('合格重量', 'black', 'qualifiedWeight'), ...(fullFields ? [numeric('总重量', 'black', 'totalWeight')] : []), numeric('报废重量', 'black', 'scrapWeight'), ...defectColumns('black', blackDefects), numeric('合格率', 'black', 'rate')] },
|
||||
{ key: 'stage-bright', title: <span className="stage-heading bright"><i />亮片</span>, children: [numeric('合格重量', 'bright', 'qualifiedWeight'), ...(fullFields ? [numeric('总重量', 'bright', 'totalWeight')] : []), numeric('报废重量', 'bright', 'scrapWeight'), ...(fullFields ? [numeric('本部报废重量', 'bright', 'headquartersScrapWeight')] : []), ...defectColumns('bright', brightDefects), { ...numeric(rateBasis === 'original' ? '合格率' : '不含本部报废调整率', 'bright', 'rate'), render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{rateText(visibleStageRate(row, 'bright', rateBasis))}</Button> }] },
|
||||
{ title: '操作', key: 'actions', fixed: compact ? undefined : 'right', width: 100, align: 'center', render: (_: unknown, row) => (row as TrendMetricRow).noData ? <span>—</span> : <Button type="link" onClick={() => openRow(row, onlyStage || 'black')}>来源明细</Button> },
|
||||
];
|
||||
const columns = onlyStage ? allColumns.filter(column => !['compositeRate', `stage-${onlyStage === 'black' ? 'bright' : 'black'}`].includes(String(column.key))) : allColumns;
|
||||
useImperativeHandle(ref, () => ({
|
||||
exportExcel: () => downloadMetricWorkbook(exportFilename, columns, rows, (key, row) => {
|
||||
if (key === 'object') return [title(row), view === 'group' ? row.department : null].filter(Boolean).join(' / ');
|
||||
if (key === 'compositeRate') return visibleCompositeRate(row, rateBasis);
|
||||
const stage: Stage = key.startsWith('black-') ? 'black' : 'bright';
|
||||
if (key.startsWith(`${stage}-defect-`)) {
|
||||
const weight=defectList(row, stage).find(item => item.name === key.slice(`${stage}-defect-`.length))?.weight ?? null;
|
||||
return defectDisplay === 'rate' ? defectWeightRate(weight,stageValue(row,stage,'totalWeight')) : weight;
|
||||
}
|
||||
const field = key.slice(stage.length + 1) as 'qualifiedWeight' | 'scrapWeight' | 'totalWeight' | 'headquartersScrapWeight' | 'rate';
|
||||
if (defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight')) return defectWeightRate(stageValue(row,stage,field),stageValue(row,stage,'totalWeight'));
|
||||
return field === 'rate' ? visibleStageRate(row, stage, stage === 'bright' ? rateBasis : 'original') : stageValue(row, stage, field);
|
||||
}),
|
||||
}));
|
||||
const dataSource = rows.map((row, index) => ({ ...row, key: row.key || `${title(row)}-${index}` }));
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(SUMMARY_PAGE_SIZE);
|
||||
@@ -1136,7 +1181,7 @@ function trendBarWidth(chartWidth: number, count: number): number {
|
||||
return Math.max(12, Math.min(64, Math.floor(((chartWidth - 132) / Math.max(count, 1)) * 0.8)));
|
||||
}
|
||||
|
||||
function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod, onMonth }: { rows: TrendMetricRow[]; mode: 'production' | 'defects'; stage: Stage; rateBasis: 'original' | 'withoutHeadquartersScrap'; targetRate: number | null; selectedPeriod?: string; onMonth: (value: number | string) => void }) {
|
||||
export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod, onMonth, onlyStage }: { rows: TrendMetricRow[]; mode: 'production' | 'defects'; stage: Stage; rateBasis: 'original' | 'withoutHeadquartersScrap'; targetRate: number | null; selectedPeriod?: string; onMonth: (value: number | string) => void; onlyStage?: Stage }) {
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
|
||||
const onMonthRef = useRef(onMonth);
|
||||
@@ -1238,10 +1283,10 @@ function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod,
|
||||
};
|
||||
const base: echarts.EChartsCoreOption = {
|
||||
animation: false,
|
||||
textStyle: { fontFamily: '-apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif', color: ink, fontSize: 12 },
|
||||
textStyle: { fontFamily: '-apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif', color: ink, fontSize: CHART_FONT_SIZE },
|
||||
grid: { left: 65, right: mode === 'production' ? 67 : 32, top: 70, bottom: 38 },
|
||||
legend: { type: 'scroll', top: 0, left: 9, right: 9, itemWidth: 14, itemHeight: 7, itemGap: 20, textStyle: { color: ink, fontSize: 12 } },
|
||||
tooltip: { trigger: 'axis', backgroundColor: surface, borderColor: line, borderWidth: 1, padding: [10, 13], textStyle: { color: ink, fontSize: 12 }, transitionDuration: 0, axisPointer: { type: 'line', lineStyle: { color: blue, width: 1, type: 'dashed' } }, formatter: (params: unknown) => formatTooltip(params, mode === 'defects') },
|
||||
legend: { type: 'scroll', top: 0, left: 9, right: 9, itemWidth: 14, itemHeight: 7, itemGap: 20, textStyle: { color: ink, fontSize: CHART_FONT_SIZE } },
|
||||
tooltip: { trigger: 'axis', backgroundColor: surface, borderColor: line, borderWidth: 1, padding: [10, 13], textStyle: { color: ink, fontSize: CHART_FONT_SIZE }, transitionDuration: 0, axisPointer: { type: 'line', lineStyle: { color: blue, width: 1, type: 'dashed' } }, formatter: (params: unknown) => formatTooltip(params, mode === 'defects') },
|
||||
xAxis: { type: 'category', data: labels, triggerEvent: true, axisLine: { lineStyle: { color: line } }, axisLabel: { color: ink, margin: 12 }, axisTick: { show: false } },
|
||||
};
|
||||
let option: echarts.EChartsCoreOption;
|
||||
@@ -1256,14 +1301,14 @@ function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod,
|
||||
silent: true,
|
||||
symbol: 'none',
|
||||
lineStyle: { color: '#c47a47', width: 1.5, type: 'dashed' as const },
|
||||
label: { show: true, formatter: `综合率目标 ${targetRate.toFixed(2)}%`, position: 'insideEndTop' as const, color: '#a55d30', fontSize: 11 },
|
||||
label: { show: true, formatter: `综合率目标 ${targetRate.toFixed(2)}%`, position: 'insideEndTop' as const, color: '#a55d30', fontSize: CHART_FONT_SIZE },
|
||||
data: [{ yAxis: targetRate }],
|
||||
} };
|
||||
option = {
|
||||
...base,
|
||||
yAxis: [
|
||||
{ type: 'value', name: '重量 / kg', nameGap: 18, nameTextStyle: { color: ink, align: 'left', fontSize: 11 }, axisLabel: { color: ink, fontSize: 11 }, axisLine: { show: false }, axisTick: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' } } },
|
||||
{ type: 'value', name: '合格率 / %', nameGap: 18, min: minRate, max: maxRate, nameTextStyle: { color: ink, align: 'right', fontSize: 11 }, axisLabel: { color: ink, formatter: '{value}%', fontSize: 11 }, axisLine: { show: false }, axisTick: { show: false }, splitLine: { show: false } },
|
||||
{ type: 'value', name: '重量 / kg', nameGap: 18, nameTextStyle: { color: ink, align: 'left', fontSize: CHART_FONT_SIZE }, axisLabel: { color: ink, fontSize: CHART_FONT_SIZE }, axisLine: { show: false }, axisTick: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' } } },
|
||||
{ type: 'value', name: '合格率 / %', nameGap: 18, min: minRate, max: maxRate, nameTextStyle: { color: ink, align: 'right', fontSize: CHART_FONT_SIZE }, axisLabel: { color: ink, formatter: '{value}%', fontSize: CHART_FONT_SIZE }, axisLine: { show: false }, axisTick: { show: false }, splitLine: { show: false } },
|
||||
],
|
||||
series: [
|
||||
{ id: 'qualified-weight', name: `${stageName}合格重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: barColor }, emphasis: { itemStyle: { color: blue } }, data: barData('qualifiedWeight') },
|
||||
@@ -1278,13 +1323,17 @@ function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod,
|
||||
const palette = [blue, teal, '#bf7d58', '#9278bf', '#598eae'];
|
||||
option = {
|
||||
...base,
|
||||
yAxis: [{ type: 'value', name: '不良率 / %', nameGap: 18, nameTextStyle: { color: ink, align: 'left', fontSize: 11 }, axisLabel: { color: ink, formatter: '{value}%', fontSize: 11 }, axisLine: { show: false }, axisTick: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' } } }],
|
||||
yAxis: [{ type: 'value', name: '不良率 / %', nameGap: 18, nameTextStyle: { color: ink, align: 'left', fontSize: CHART_FONT_SIZE }, axisLabel: { color: ink, formatter: '{value}%', fontSize: CHART_FONT_SIZE }, axisLine: { show: false }, axisTick: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' } } }],
|
||||
series: names.map((name, index) => ({ id: `defect-${stage}-${name}`, name, type: 'line' as const, ...pointStyle, lineStyle: { width: 2, color: palette[index % palette.length] }, itemStyle: { color: palette[index % palette.length] }, data: rows.map(row => { const defect = row[stage].defects.find(item => item.name === name); return rateNumber(defectWeightRate(defect?.weight, row[stage].totalWeight)); }) })),
|
||||
};
|
||||
}
|
||||
if(onlyStage && mode === 'production') {
|
||||
const stageOption=option as {series?:Array<{id?:string}>;legend?:unknown};
|
||||
stageOption.series=stageOption.series?.filter(item=>item.id==='qualified-weight'||item.id==='scrap-weight'||item.id===`${onlyStage}-rate`);
|
||||
}
|
||||
instance.setOption(option, { replaceMerge: ['series', 'yAxis'], lazyUpdate: false });
|
||||
refreshBarMasks();
|
||||
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks]);
|
||||
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage]);
|
||||
|
||||
const dimmedPeriod = selectedPeriod === lineSelectedPeriod ? undefined : selectedPeriod;
|
||||
|
||||
@@ -1328,7 +1377,7 @@ function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod,
|
||||
</div>;
|
||||
}
|
||||
|
||||
function TrendTable({ rows, rateBasis, onMonth, showMonthLinks = true }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; showMonthLinks?: boolean }) {
|
||||
function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight', showMonthLinks = true }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; defectDisplay?: 'weight'|'rate'; showMonthLinks?: boolean }) {
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(SUMMARY_PAGE_SIZE);
|
||||
useEffect(() => setCurrentPage(1), [rows]);
|
||||
@@ -1336,10 +1385,10 @@ function TrendTable({ rows, rateBasis, onMonth, showMonthLinks = true }: { rows:
|
||||
{ title: '统计期间', dataIndex: 'month', key: 'month', align: 'center', fixed: 'left', width: 130, render: (_: unknown, row) => <Button type="link" onClick={() => onMonth(row.month)}>{row.periodLabel || String(row.month)}</Button> },
|
||||
{ title: rateBasis === 'original' ? '综合合格率' : '综合调整率', dataIndex: 'compositeRate', key: 'compositeRate', align: 'center', width: 130, className: 'combined-column', render: (_: number | null, row: MetricRow) => rateText(visibleCompositeRate(row, rateBasis)) },
|
||||
{ title: '黑片合格重量 / kg', dataIndex: ['black', 'qualifiedWeight'], key: 'blackQualified', align: 'center', width: 160, render: value => numberText(value) },
|
||||
{ title: '黑片报废重量 / kg', dataIndex: ['black', 'scrapWeight'], key: 'blackScrap', align: 'center', width: 160, render: value => numberText(value) },
|
||||
{ title: defectDisplay === 'rate' ? '黑片报废率' : '黑片报废重量 / kg', dataIndex: ['black', 'scrapWeight'], key: 'blackScrap', align: 'center', width: 160, render: (_: unknown, row: TrendMetricRow) => defectDisplay === 'rate' ? rateText(defectWeightRate(row.black.scrapWeight,row.black.totalWeight)) : numberText(row.black.scrapWeight) },
|
||||
{ title: '黑片合格率', dataIndex: ['black', 'rate'], key: 'blackRate', align: 'center', width: 130, render: (_: number | null, row: TrendMetricRow) => rateText(visibleStageRate(row, 'black')) },
|
||||
{ title: '亮片合格重量 / kg', dataIndex: ['bright', 'qualifiedWeight'], key: 'brightQualified', align: 'center', width: 160, render: value => numberText(value) },
|
||||
{ title: '亮片报废重量 / kg', dataIndex: ['bright', 'scrapWeight'], key: 'brightScrap', align: 'center', width: 160, render: value => numberText(value) },
|
||||
{ title: defectDisplay === 'rate' ? '亮片报废率' : '亮片报废重量 / kg', dataIndex: ['bright', 'scrapWeight'], key: 'brightScrap', align: 'center', width: 160, render: (_: unknown, row: TrendMetricRow) => defectDisplay === 'rate' ? rateText(defectWeightRate(row.bright.scrapWeight,row.bright.totalWeight)) : numberText(row.bright.scrapWeight) },
|
||||
{ title: rateBasis === 'original' ? '亮片合格率' : '亮片不含本部报废调整率', dataIndex: ['bright', 'rate'], key: 'brightRate', align: 'center', width: 180, render: (_: number | null, row: TrendMetricRow) => rateText(visibleStageRate(row, 'bright', rateBasis)) },
|
||||
];
|
||||
return rows.length ? <div className="metric-table-scroll trend-data-table"><Table size="small" bordered columns={columns} dataSource={rows} rowKey={row => String(row.month)} pagination={{ current: currentPage, pageSize, showSizeChanger: rows.length > SUMMARY_PAGE_SIZE, pageSizeOptions: SUMMARY_PAGE_SIZE_OPTIONS, showTotal: (total, range) => `显示 ${range[0]}–${range[1]} 行,共 ${total} 个月`, onChange: (nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); } }} scroll={{ x: 1130 }} />
|
||||
@@ -1347,17 +1396,17 @@ function TrendTable({ rows, rateBasis, onMonth, showMonthLinks = true }: { rows:
|
||||
</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前数据未返回趋势" />;
|
||||
}
|
||||
|
||||
function RecordsDrawer({
|
||||
open, row, stage, onStage, onClose, query, view, month, onUnauthorized,
|
||||
export function RecordsDrawer({
|
||||
open, row, stage, onStage, onClose, query, month, onUnauthorized, lockedStage,
|
||||
}: {
|
||||
open: boolean; row: MetricRow | null; stage: Stage; onStage: (stage: Stage) => void; onClose: () => void;
|
||||
query: QueryParams; view: ViewKind; month?: number; onUnauthorized: (error: unknown) => boolean;
|
||||
query: QueryParams; month?: number; onUnauthorized: (error: unknown) => boolean; lockedStage?: boolean;
|
||||
}) {
|
||||
const { message } = App.useApp();
|
||||
const [page, setPage] = useState(1);
|
||||
const [result, setResult] = useState<RecordsResponse | null>(null);
|
||||
const [response, setResponse] = useState<{ key: string; data: RecordsResponse } | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [failure, setFailure] = useState<{ key: string; message: string } | null>(null);
|
||||
const [field, setField] = useState<string>();
|
||||
const [fieldSearch, setFieldSearch] = useState('');
|
||||
const [sort, setSort] = useState<string>();
|
||||
@@ -1365,46 +1414,50 @@ function RecordsDrawer({
|
||||
const [selectedColumns, setSelectedColumns] = useState<string[]>();
|
||||
const [rawFields, setRawFields] = useState<string[]>([]);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
|
||||
const recordQuery = useMemo(() => {
|
||||
const params: QueryParams = { ...query };
|
||||
if (month) { params.month = month; delete params.quarter; }
|
||||
if (row) {
|
||||
if (view === 'department') params.department = row.key === '__UNASSIGNED__' ? '__UNASSIGNED__' : (row.department || row.key);
|
||||
if (view === 'group') params.group = row.key === '__UNASSIGNED__' ? '__UNASSIGNED__' : (row.group || row.key);
|
||||
if (view === 'product') params.product = row.key === '__UNASSIGNED__' ? '__UNASSIGNED__' : (row.product || row.key);
|
||||
if (view === 'projectGroup') params.projectGroup = row.key === '__UNASSIGNED__' ? '__UNASSIGNED__' : (row.projectGroup || row.key);
|
||||
}
|
||||
return params;
|
||||
}, [query, row, view, month]);
|
||||
const [revision, setRevision] = useState(0);
|
||||
const exportController = useRef<AbortController | null>(null);
|
||||
useEffect(() => () => exportController.current?.abort(), []);
|
||||
const recordQuery = query;
|
||||
const requestParams = useMemo(() => ({ ...recordQuery, stage, page, pageSize: TABLE_PAGE_SIZE,
|
||||
...(field ? { field } : {}), ...(field && fieldSearch.trim() ? { search: fieldSearch.trim() } : {}),
|
||||
...(sort ? { sort, direction } : {}),
|
||||
}), [recordQuery, stage, page, field, fieldSearch, sort, direction]);
|
||||
const requestKey = JSON.stringify(requestParams);
|
||||
const result = response?.key === requestKey ? response.data : null;
|
||||
const error = failure?.key === requestKey ? failure.message : '';
|
||||
const fetching = loading || !result && !error;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError('');
|
||||
api.records({ ...recordQuery, stage, page, pageSize: TABLE_PAGE_SIZE,
|
||||
...(field ? { field } : {}), ...(field && fieldSearch.trim() ? { search: fieldSearch.trim() } : {}),
|
||||
...(sort ? { sort, direction } : {}),
|
||||
}, controller.signal).then(value => {
|
||||
setResult(value);
|
||||
setResponse(null); setFailure(null);
|
||||
api.records(requestParams, controller.signal).then(value => {
|
||||
if (controller.signal.aborted) return;
|
||||
const lastPage = Math.max(1, Math.ceil(value.total / value.pageSize));
|
||||
if (page > lastPage) { setPage(lastPage); return; }
|
||||
setResponse({ key: requestKey, data: value });
|
||||
const pageFields = value.rows.flatMap(record => Object.keys(record.raw || {}).filter(key => !isSystemVersionField(key)));
|
||||
if (pageFields.length) setRawFields(existing => [...new Set([...existing, ...pageFields])]);
|
||||
})
|
||||
.catch(errorValue => {
|
||||
if (controller.signal.aborted) return;
|
||||
if (!onUnauthorized(errorValue)) setError(chooseError(errorValue));
|
||||
if (!onUnauthorized(errorValue)) setFailure({ key: requestKey, message: chooseError(errorValue) });
|
||||
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||||
return () => controller.abort();
|
||||
}, [open, recordQuery, stage, page, field, fieldSearch, sort, direction, onUnauthorized]);
|
||||
}, [open, requestKey, revision, onUnauthorized]);
|
||||
|
||||
const visibleRawFields = selectedColumns ?? rawFields.slice(0, 8);
|
||||
const exportRecords = async () => {
|
||||
const params: RecordExportParams = {
|
||||
year: recordQuery.year,
|
||||
...(recordQuery.extraFilters ? { extraFilters: recordQuery.extraFilters } : {}),
|
||||
...(recordQuery.columnFilters ? { columnFilters: recordQuery.columnFilters } : {}),
|
||||
...(lockedStage ? { stage } : {}),
|
||||
...(recordQuery.month !== undefined ? { month: recordQuery.month } : {}),
|
||||
...(recordQuery.quarter !== undefined ? { quarter: recordQuery.quarter } : {}),
|
||||
...(recordQuery.monthStart !== undefined ? { monthStart: recordQuery.monthStart } : {}),
|
||||
...(recordQuery.monthEnd !== undefined ? { monthEnd: recordQuery.monthEnd } : {}),
|
||||
...(recordQuery.department !== undefined ? { department: recordQuery.department } : {}),
|
||||
...(recordQuery.group !== undefined ? { group: recordQuery.group } : {}),
|
||||
...(recordQuery.product !== undefined ? { product: recordQuery.product } : {}),
|
||||
@@ -1413,9 +1466,12 @@ function RecordsDrawer({
|
||||
...(recordQuery.includeUnassigned !== undefined ? { includeUnassigned: recordQuery.includeUnassigned } : {}),
|
||||
...(recordQuery.releaseId !== undefined ? { releaseId: recordQuery.releaseId } : {}),
|
||||
};
|
||||
const controller = new AbortController();
|
||||
exportController.current?.abort(); exportController.current = controller;
|
||||
setExporting(true);
|
||||
try {
|
||||
const { blob, filename } = await api.exportRecords(params);
|
||||
const { blob, filename } = await api.exportRecords(params, controller.signal);
|
||||
if (controller.signal.aborted) return;
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
@@ -1424,11 +1480,11 @@ function RecordsDrawer({
|
||||
link.click();
|
||||
link.remove();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
message.success('明细 Excel 已开始下载,含黑片和亮片两个工作表');
|
||||
message.success(lockedStage ? '当前阶段明细 Excel 已开始下载' : '明细 Excel 已开始下载,含黑片和亮片两个工作表');
|
||||
} catch (errorValue) {
|
||||
message.error(chooseError(errorValue));
|
||||
if (!controller.signal.aborted && !onUnauthorized(errorValue)) message.error(chooseError(errorValue));
|
||||
} finally {
|
||||
setExporting(false);
|
||||
if (!controller.signal.aborted) setExporting(false);
|
||||
}
|
||||
};
|
||||
const fixedColumns: ColumnsType<RecordRow> = [
|
||||
@@ -1439,7 +1495,7 @@ function RecordsDrawer({
|
||||
return <details className="source-fields source-raw-fields">
|
||||
<summary>查看全部原始字段({fieldCount})</summary>
|
||||
<p>以下为该来源行导入时保存的字段值,按当前字段授权筛选。</p>
|
||||
<pre className="json-cell">{JSON.stringify(raw, null, 2)}</pre>
|
||||
<BusinessValue value={raw} />
|
||||
</details>;
|
||||
} },
|
||||
{ title: '工作表', dataIndex: 'sheet', key: 'sheet', width: 120 },
|
||||
@@ -1452,12 +1508,12 @@ function RecordsDrawer({
|
||||
{ title: '业务分组', dataIndex: 'group', key: 'group', width: 190 },
|
||||
{ title: '产品', dataIndex: 'product', key: 'product', width: 190 },
|
||||
...visibleRawFields.map(name => ({ title: name, key: `raw:${name}`, width: 180, ellipsis: true, render: (_: unknown, record: RecordRow) => String(record.raw?.[name] ?? '—') })),
|
||||
{ title: '规范化值与转换说明', key: 'transform', width: 260, render: (_: unknown, record: RecordRow) => <details className="source-fields"><summary>查看本行转换</summary><strong>规范化值</strong><pre className="json-cell">{JSON.stringify(withoutSystemVersionFields(record.normalized || {}), null, 2)}</pre><strong>转换说明</strong><ul>{(record.transformNotes || []).map((note, index) => <li key={index}>{typeof note === 'string' ? note : JSON.stringify(withoutSystemVersionFields(note))}</li>)}</ul></details> },
|
||||
{ title: '计算分量', dataIndex: 'components', key: 'components', width: 270, render: value => <details className="source-fields"><summary>查看计算分量</summary><pre className="json-cell">{JSON.stringify(withoutSystemVersionFields(value), null, 2)}</pre></details> },
|
||||
{ title: '规范化值与转换说明', key: 'transform', width: 260, render: (_: unknown, record: RecordRow) => <details className="source-fields"><summary>查看本行转换</summary><strong>规范化值</strong><BusinessValue value={withoutSystemVersionFields(record.normalized || {})} /><strong>转换说明</strong><ul>{(record.transformNotes || []).map((note, index) => <li key={index}>{typeof note === 'string' ? note : <BusinessValue value={withoutSystemVersionFields(note)} />}</li>)}</ul></details> },
|
||||
{ title: '计算分量', dataIndex: 'components', key: 'components', width: 270, render: value => <details className="source-fields"><summary>查看计算分量</summary><BusinessValue value={withoutSystemVersionFields(value)} /></details> },
|
||||
];
|
||||
|
||||
return <Drawer className="source-records-drawer" open={open} onClose={onClose} width={Math.min(1120, window.innerWidth)} title={<div className="drawer-title">来源明细 <small>{row?.label || (month ? MONTHS[month - 1] : '当前筛选条件')}</small></div>} destroyOnClose>
|
||||
<div className="drawer-controls"><Segmented value={stage} options={[{ label: '黑片', value: 'black' }, { label: '亮片', value: 'bright' }]} onChange={value => { onStage(value as Stage); setPage(1); setRawFields([]); setField(undefined); setFieldSearch(''); setSelectedColumns(undefined); setSort(undefined); }} aria-label="明细阶段" /><span>{result ? `共 ${result.total} 条来源记录 · 已载入 ${rawFields.length} 个原始字段` : '按当前查询条件获取原始来源行'}</span><Button size="small" icon={<DownloadOutlined />} loading={exporting} onClick={exportRecords} title="导出当前查询范围全部来源明细,含黑片和亮片两个工作表">导出明细 Excel</Button></div>
|
||||
<div className="drawer-controls"><Segmented disabled={lockedStage} value={stage} options={[{ label: '黑片', value: 'black' }, { label: '亮片', value: 'bright' }]} onChange={value => { onStage(value as Stage); setPage(1); setRawFields([]); setField(undefined); setFieldSearch(''); setSelectedColumns(undefined); setSort(undefined); }} aria-label="明细阶段" /><span>{result ? `共 ${result.total} 条来源记录 · 已载入 ${rawFields.length} 个原始字段` : '按当前查询条件获取原始来源行'}</span><Button size="small" icon={<DownloadOutlined />} loading={exporting} onClick={exportRecords} title={lockedStage ? '导出当前阶段和筛选范围的全部来源明细' : '导出当前查询范围全部来源明细,含黑片和亮片两个工作表'}>导出明细 Excel</Button></div>
|
||||
<div className="record-query-tools">
|
||||
<label><span>字段检索</span><Select {...readableSelectPopup} allowClear showSearch optionFilterProp="label" placeholder="选择原始字段" value={field} options={rawFields.map(name => ({ label: name, value: name }))} onChange={value => { setField(value); setPage(1); }} /></label>
|
||||
<Input allowClear disabled={!field} prefix={<SearchOutlined />} placeholder={field ? `搜索字段:${field}` : '先选择检索字段'} value={fieldSearch} onChange={event => { setFieldSearch(event.target.value); setPage(1); }} />
|
||||
@@ -1469,8 +1525,10 @@ function RecordsDrawer({
|
||||
]} onChange={value => { setSort(value); setPage(1); }} /></label>
|
||||
<Segmented value={direction} options={[{ label: '升序', value: 'asc' }, { label: '降序', value: 'desc' }]} onChange={value => { setDirection(value as 'asc' | 'desc'); setPage(1); }} aria-label="排序方向" />
|
||||
</div>
|
||||
{error && <Alert type="error" showIcon message="来源明细加载失败" description={error} />}
|
||||
{loading && !result ? <div className="loading-panel"><Spin />正在读取来源行…</div> : result?.rows.length ? <Table size="small" bordered columns={fixedColumns} dataSource={result.rows} rowKey="id" pagination={false} scroll={{ x: 1800 + visibleRawFields.length * 180 }} /> : !loading && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={error ? '来源记录加载失败' : '当前条件没有来源记录'} />}
|
||||
{error && <Alert type="error" showIcon message="来源明细加载失败" description={error} action={<Button size="small" onClick={() => setRevision(value => value + 1)}>重试</Button>} />}
|
||||
{fetching ? <div className="loading-panel"><Spin />正在读取来源行…</div> : result?.rows.length ? <Table size="small" bordered columns={fixedColumns} dataSource={result.rows} rowKey="id" pagination={false} scroll={{ x: 1800 + visibleRawFields.length * 180 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={error ? '来源记录加载失败' : '当前条件没有来源记录'} />}
|
||||
{result && result.total > result.pageSize && <Pagination className="records-pagination" current={page} pageSize={result.pageSize} total={result.total} showTotal={total => `共 ${total} 条`} onChange={next => setPage(next)} />}
|
||||
</Drawer>;
|
||||
}
|
||||
|
||||
export { fullYearTrend };
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Checkbox, Empty, Input, Modal, Segmented, Select, Spin } from 'antd';
|
||||
import { DownloadOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
|
||||
import { api, decodeQueryValueList, encodeQueryValueList } from './api';
|
||||
import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHeading, RecordsDrawer, TrendChart, fullYearTrend, queryFromLocation } from './QueryPage';
|
||||
import { StageSourceFilters } from './StageSourceFilters';
|
||||
import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery';
|
||||
import { usePageCache } from './pageCache';
|
||||
import { previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import { readableMetricFormula } from './publicDataDisplay';
|
||||
import type { MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage } from './types';
|
||||
import './stage-product.css';
|
||||
|
||||
const weight=(v:number|null|undefined)=>typeof v==='number'?v.toLocaleString('zh-CN',{maximumFractionDigits:2}):'—';
|
||||
const rate=(v:number|null|undefined)=>typeof v==='number'?`${(v*100).toFixed(2)}%`:'—';
|
||||
export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onUnauthorized:(error:unknown)=>boolean}) {
|
||||
const {message}=App.useApp();const {active,initialSearch,refreshKey,onLocationChange}=usePageCache();
|
||||
const [initial]=useState(()=>queryFromLocation(initialSearch));const defaults=previousCompleteMonth();
|
||||
const [period,setPeriod]=useState<PeriodKind>(initial.quarter?'quarter':initial.month?'month':initial.year?'year':'month');
|
||||
const [year,setYear]=useState(initial.year||defaults.year);const [month,setMonth]=useState(initial.month||defaults.month);const [quarter,setQuarter]=useState(initial.quarter||previousCompleteQuarter().quarter);
|
||||
const [department,setDepartment]=useState(()=>decodeQueryValueList(initial.department));const [group,setGroup]=useState(()=>decodeQueryValueList(initial.group));const [product,setProduct]=useState(()=>decodeQueryValueList(initial.product));const [projectGroup,setProjectGroup]=useState(()=>decodeQueryValueList(initial.projectGroup));
|
||||
const [sourceFilters,setSourceFilters]=useState<SourceColumnFilter[]>(initial.columnFilters||[]);const [search,setSearch]=useState(initial.productSearch||'');const [includeUnassigned,setIncludeUnassigned]=useState(!!initial.includeUnassigned);
|
||||
const [options,setOptions]=useState<OptionsResponse|null>(null);const [catalog,setCatalog]=useState<{releaseId:string;sourceFields:SourceColumnField[]}|null>(null);const [supportError,setSupportError]=useState('');const [supportLoading,setSupportLoading]=useState(true);
|
||||
const [applied,setApplied]=useState<QueryParams|null>(null);const [revision,setRevision]=useState(0);const [response,setResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [loading,setLoading]=useState(false);const [failure,setFailure]=useState<{key:string;message:string}|null>(null);
|
||||
const [defectDisplay,setDefectDisplay]=useState<'weight'|'rate'>('weight');
|
||||
const [fullFields,setFullFields]=useState(true);const [rateBasis,setRateBasis]=useState<'original'|'withoutHeadquartersScrap'>('original');const [basisOpen,setBasisOpen]=useState(false);const [trendMode,setTrendMode]=useState<'production'|'defects'|'data'>('production');
|
||||
const [trendGranularity,setTrendGranularity]=useState<'month'|'quarter'|'year'>('month');
|
||||
const [trendResponse,setTrendResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [trendError,setTrendError]=useState('');const [trendLoading,setTrendLoading]=useState(false);
|
||||
const [records,setRecords]=useState<{row:MetricRow|null;query:QueryParams}|null>(null);const exporter=useRef<{exportExcel:()=>Promise<void>}>(null);const [exporting,setExporting]=useState(false);
|
||||
const label=stage==='black'?'黑片':'亮片';
|
||||
const loadSupport=useCallback(async()=>{
|
||||
setSupportLoading(true);setSupportError('');
|
||||
try{const [choices,source]=await Promise.all([api.options(),api.sourceColumnCatalog()]);setOptions(choices);setCatalog(source);}
|
||||
catch(error){if(!onUnauthorized(error))setSupportError(error instanceof Error?error.message:'查询条件读取失败');}
|
||||
finally{setSupportLoading(false);}
|
||||
},[onUnauthorized]);
|
||||
useEffect(()=>{if(active)void loadSupport();},[active,refreshKey,loadSupport]);
|
||||
const fields=useMemo(()=>catalog?.sourceFields.filter(field=>field.type==='source_value'&&field.stages.includes(stage))||[],[catalog,stage]);
|
||||
const draft=useMemo(()=>stageProductQuery({year,...(period==='month'?{month}:period==='quarter'?{quarter}:{}),department:encodeQueryValueList(department),group:encodeQueryValueList(group),product:encodeQueryValueList(product),projectGroup:encodeQueryValueList(projectGroup),productSearch:search.trim()||undefined,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,sourceFilters),[year,period,month,quarter,department,group,product,projectGroup,search,includeUnassigned,catalog,stage,sourceFilters]);
|
||||
// A new release resets the data binding; hidden cached pages never issue queries.
|
||||
useEffect(()=>{if(catalog)setApplied(draft);},[catalog]);
|
||||
const queryKey=JSON.stringify({query:applied,revision});const current=response?.key===queryKey?response.value:null;const error=failure?.key===queryKey?failure.message:'';
|
||||
useEffect(()=>{
|
||||
if(!active||!applied||supportError)return;const controller=new AbortController();setLoading(true);setFailure(null);
|
||||
void api.metrics(applied,controller.signal).then(value=>{if(!controller.signal.aborted)setResponse({key:queryKey,value});}).catch(e=>{if(!controller.signal.aborted&&!onUnauthorized(e))setFailure({key:queryKey,message:e instanceof Error?e.message:'查询失败'});}).finally(()=>{if(!controller.signal.aborted)setLoading(false);});
|
||||
return()=>controller.abort();
|
||||
},[active,queryKey,onUnauthorized,supportError]);
|
||||
useEffect(()=>{if(!active||!applied)return;const bytes=new TextEncoder().encode(JSON.stringify({query:applied}));const encoded=btoa(Array.from(bytes,b=>String.fromCharCode(b)).join('')).replace(/=/g,'').replace(/\+/g,'-').replace(/\//g,'_');const url=`?page=${stage==='black'?'blackProduct':'brightProduct'}&context=${encoded}`;window.history.replaceState({},'',`${location.pathname}${url}`);onLocationChange(url);},[active,applied,stage]);
|
||||
const trendQuery=useMemo(()=>applied?{...applied,month:undefined,quarter:undefined,...(trendGranularity==='year'?{year:undefined}:{}),trendGranularity}:null,[applied,trendGranularity]);
|
||||
const trendKey=JSON.stringify({query:trendQuery,revision});
|
||||
useEffect(()=>{if(!active||!current||!trendQuery)return;const controller=new AbortController();setTrendLoading(true);setTrendError('');void api.metrics(trendQuery,controller.signal).then(value=>{if(!controller.signal.aborted)setTrendResponse({key:trendKey,value});}).catch(error=>{if(!controller.signal.aborted&&!onUnauthorized(error))setTrendError(error instanceof Error?error.message:'趋势读取失败');}).finally(()=>{if(!controller.signal.aborted)setTrendLoading(false);});return()=>controller.abort();},[active,trendKey,!!current,onUnauthorized]);
|
||||
const visibleTrend=useMemo(()=>fullYearTrend(trendResponse?.key===trendKey?trendResponse.value.trend:[],applied?.year||year,trendGranularity),[trendResponse,trendKey,applied?.year,year,trendGranularity]);
|
||||
const selectTrendPeriod=(value:number|string)=>{if(!applied)return;const text=String(value);if(trendGranularity==='year'){const selectedYear=Number(text);if(Number.isFinite(selectedYear)){setYear(selectedYear);setPeriod('year');setApplied({...applied,year:selectedYear,month:undefined,quarter:undefined});}}else if(trendGranularity==='quarter'){const selectedQuarter=Number(text.replace(/^.*Q/,''));if(selectedQuarter>=1&&selectedQuarter<=4){setQuarter(selectedQuarter);setPeriod('quarter');setApplied({...applied,quarter:selectedQuarter,month:undefined});}}else{const selectedMonth=Number(text.slice(-2));if(selectedMonth>=1&&selectedMonth<=12){setMonth(selectedMonth);setPeriod('month');setApplied({...applied,month:selectedMonth,quarter:undefined});}}setRevision(v=>v+1);};
|
||||
const dirty=!!applied&&JSON.stringify(draft)!==JSON.stringify(applied);const submit=()=>{setApplied(draft);setRevision(v=>v+1);};
|
||||
const groups=(options?.groups||[]).filter(name=>!department.length||department.includes(options?.groupDepartments?.[name]||''));
|
||||
const paths=options?.organizationPaths||[];const products=department.length||group.length?[...new Set(paths.filter(path=>(!department.length||department.includes(path.department||''))&&(!group.length||group.includes(path.group||''))).map(path=>path.product).filter((v):v is string=>!!v))]:options?.products||[];
|
||||
const select=(name:string,value:string[],choices:string[],change:(v:string[])=>void)=><label className="query-field query-primary-field"><span>{name}</span><Select {...readableSelectPopup} mode="multiple" allowClear showSearch optionFilterProp="label" aria-label={name} placeholder="全部" maxTagCount="responsive" value={value} options={[...new Set([...choices,...value])].map(v=>({label:v==='__UNASSIGNED__'?'未分类':v,value:v}))} onChange={change}/></label>;
|
||||
const sortedRows=useMemo(()=>sortStageRowsByTotalWeight(current?.rows||[],stage),[current,stage]);
|
||||
const summary=current?.summary[stage];const stageRate=stage==='bright'&&rateBasis==='withoutHeadquartersScrap'?summary?.rateWithoutHeadquartersScrap:summary?.rate;
|
||||
const openDetail=(row:MetricRow|null,_stage:Stage,selectedMonth?:number)=>{if(!applied||!current?.release)return;setRecords({row,query:{...applied,releaseId:current.release.id,...(row&&selectedMonth==null?{product:row.product||'__UNASSIGNED__'}:{}),...(selectedMonth?{month:selectedMonth,quarter:undefined}: {})}});};
|
||||
const runExport=async()=>{setExporting(true);try{await exporter.current?.exportExcel();}catch(e){message.error(e instanceof Error?e.message:'导出失败');}finally{setExporting(false);}};
|
||||
const formulaKey=stage==='black'?'blackRate':rateBasis==='original'?'brightRate':'brightRateWithoutHeadquartersScrap';
|
||||
return <div className="query-page stage-product-page">
|
||||
{supportError&&<Alert showIcon type="error" message="查询条件读取失败" description={supportError} action={<Button onClick={()=>void loadSupport()}>重试</Button>}/>}
|
||||
<section className="query-toolbar panel" aria-label={`${label}汇总条件`}>
|
||||
<Segmented aria-label="统计周期" value={period} options={[{label:'年度',value:'year'},{label:'季度',value:'quarter'},{label:'月度',value:'month'}]} onChange={v=>setPeriod(v as PeriodKind)}/>
|
||||
<label className="query-field query-period-field"><span>年份</span><Select aria-label="年份" value={year} onChange={setYear} options={(options?.years?.length?options.years:[year]).map(v=>({label:`${v}年`,value:v}))}/></label>
|
||||
{period==='month'&&<label className="query-field query-period-field"><span>月份</span><Select aria-label="月份" value={month} onChange={setMonth} options={Array.from({length:12},(_,i)=>({label:`${i+1}月`,value:i+1}))}/></label>}
|
||||
{period==='quarter'&&<label className="query-field query-period-field"><span>季度</span><Select aria-label="季度" value={quarter} onChange={setQuarter} options={[1,2,3,4].map(v=>({label:`第${v}季度`,value:v}))}/></label>}
|
||||
{select('产业部',department,options?.departments||[],values=>{setDepartment(values);setGroup([]);setProduct([]);})}
|
||||
{select('业务分组',group,groups,values=>{setGroup(values);setProduct([]);})}
|
||||
{select('产品',product,products,setProduct)}
|
||||
{options?.projectGroupStatus==='READY'&&select('项目组',projectGroup,options.projectGroups||[],setProjectGroup)}
|
||||
{catalog&&<StageSourceFilters part="picker" stage={stage} fields={fields} query={draft} value={sourceFilters} onChange={setSourceFilters} onUnauthorized={onUnauthorized}/>}
|
||||
<Checkbox checked={includeUnassigned} onChange={e=>setIncludeUnassigned(e.target.checked)}>包含未分类行</Checkbox>
|
||||
<div className="query-toolbar-tail"><Button type="text" icon={<ReloadOutlined/>} loading={supportLoading} onClick={()=>void loadSupport()}>刷新</Button><Button type="primary" icon={<SearchOutlined/>} disabled={supportLoading||!!supportError||!catalog} loading={loading} onClick={submit}>查询</Button></div>
|
||||
{catalog&&<StageSourceFilters part="rows" stage={stage} fields={fields} query={draft} value={sourceFilters} onChange={setSourceFilters} onUnauthorized={onUnauthorized}/>}
|
||||
{dirty&&<div className="stage-query-pending">筛选条件已修改,点击“查询”更新统计结果</div>}
|
||||
</section>
|
||||
{error&&<Alert showIcon type="error" message="查询失败" description={error} action={<Button onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>}
|
||||
<section className="metric-strip stage-metric-strip" aria-label="质量指标" aria-busy={loading} inert={!current}>
|
||||
{stage==='bright'&&<div className="rate-basis-control"><span>亮片本部报废调整</span><Segmented size="small" aria-label="合格率口径" value={rateBasis} options={[{label:'原口径',value:'original'},{label:'去本部报废',value:'withoutHeadquartersScrap'}]} onChange={v=>setRateBasis(v as typeof rateBasis)}/></div>}
|
||||
<MetricCard primary stage={stage} label={`${label}${rateBasis==='original'?'合格率':'调整率'}`} value={rate(stageRate)} onClick={()=>setBasisOpen(true)}/>
|
||||
<MetricCard label="合格重量" value={`${weight(summary?.qualifiedWeight)} kg`} onClick={()=>openDetail(null,stage)}/>
|
||||
<MetricCard label="报废重量" value={`${weight(summary?.scrapWeight)} kg`} onClick={()=>openDetail(null,stage)}/>
|
||||
<MetricCard label="总重量" value={`${weight(summary?.totalWeight)} kg`} onClick={()=>openDetail(null,stage)}/>
|
||||
</section>
|
||||
<div className="query-quality-summary"><span>{current?`来源覆盖 ${current.coverage.sourceMonths.filter(m=>(stage==='black'?m.blackRows:m.brightRows)>0).length} 个月 · 参与计算 ${current.coverage.includedRows.toLocaleString()} 行`:loading?'正在查询…':'暂无统计结果'}</span><Button type="link" disabled={!current} onClick={()=>setBasisOpen(true)}>计算口径</Button></div>
|
||||
<section className="panel section-panel table-panel"><div className="section-heading-row"><SectionHeading title={`${label}汇总`} subtitle="重量 / kg 合格率 / %"/><div className="table-tools"><Input aria-label="搜索产品名称" placeholder="输入产品名称关键词" allowClear value={search} onChange={e=>setSearch(e.target.value)} onPressEnter={submit}/><Button onClick={submit} disabled={!catalog||!!supportError}>搜索</Button><Segmented value={fullFields?'full':'key'} aria-label="字段显示" options={[{label:'关键指标',value:'key'},{label:'完整字段',value:'full'}]} onChange={v=>setFullFields(v==='full')}/><Segmented value={defectDisplay} aria-label="不良显示方式" options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={v=>setDefectDisplay(v as typeof defectDisplay)}/><Button icon={<DownloadOutlined/>} aria-label="导出产品汇总" loading={exporting} disabled={!current||loading} onClick={()=>void runExport()}/></div></div>
|
||||
<Spin spinning={loading}><MetricTable ref={exporter} exportFilename={`${label}产品汇总-${year}`} rows={sortedRows} view="product" period={period} month={month} quarter={quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={row=>{setProduct([row.product||'__UNASSIGNED__']);setSearch('');setApplied({...applied!,product:row.product||'__UNASSIGNED__',productSearch:undefined});setRevision(v=>v+1);}}/></Spin>
|
||||
</section>
|
||||
<div className="analysis-stack"><section className="panel section-panel trend-panel"><div className="section-heading-row trend-heading-row"><SectionHeading title={`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}变化趋势`} subtitle={`${year} 年 · 当前${label}筛选`}/><Segmented value={trendMode} aria-label="趋势视图" options={[{label:'合格率与产量',value:'production'},{label:'不良率',value:'defects'},{label:`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}数据`,value:'data'}]} onChange={v=>setTrendMode(v as typeof trendMode)}/></div><div className="trend-controls">{trendMode==='data'&&<Segmented value={defectDisplay} aria-label="趋势不良显示方式" options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={v=>setDefectDisplay(v as typeof defectDisplay)}/>}<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={trendGranularity} options={[{label:'按月',value:'month'},{label:'按季度',value:'quarter'},{label:'按年度',value:'year'}]} onChange={setTrendGranularity} aria-label="趋势粒度"/></label></div>{trendError&&<Alert type="warning" message="趋势读取失败" description={trendError}/>}<Spin spinning={trendLoading}><div className="trend-chart-shell" aria-busy={trendLoading}>{trendMode==='data'?<MetricTable exportFilename={`${label}月度趋势-${year}`} rows={visibleTrend} view="overall" layoutView="product" period="year" month={month} quarter={quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={()=>{}}/>:<TrendChart rows={visibleTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} onMonth={selectTrendPeriod}/>}</div></Spin><div className="chart-footnote"><span>指标由来源分量汇总,使用当前生效公式。</span><span>点击期间筛选</span></div></section>
|
||||
<section className="panel section-panel defects-panel">
|
||||
<div className="section-heading-row"><SectionHeading title="不良具体构成" subtitle={`${label} · 占比为分类报废内占比;废率为该类重量 ÷ 总重量`}/></div>
|
||||
<section className="defect-stage-column" aria-label={`${label}不良构成`}>
|
||||
<h3 className={`defect-stage-title ${stage}`}><i/>{label}</h3>
|
||||
{current?.defects[stage]?.length ? <DefectBreakdown items={current.defects[stage]} stage={stage} totalWeight={summary?.totalWeight} maximum={Math.max(0,...current.defects[stage].map(item=>item.weight||0))} onDetail={()=>openDetail(null,stage)}/> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={loading?'正在查询不良数据…':'当前条件下暂无不良分类数据'}/>}
|
||||
</section>
|
||||
{current&&applied&&<DefectParetoPanel releaseId={current.release?.id} query={applied} onlyStage={stage} externalScrapWeight={stage==='black'?current.defects.black.find(item=>item.name==='外废')?.weight:undefined} onUnauthorized={onUnauthorized}/>}
|
||||
</section></div>
|
||||
<Modal open={basisOpen} title={`${label}计算口径`} onCancel={()=>setBasisOpen(false)} footer={<Button onClick={()=>setBasisOpen(false)}>关闭</Button>}><p>{readableMetricFormula((current?.context.metricFormulaDescriptions as Record<string,unknown>|undefined)?.[formulaKey])}</p></Modal>
|
||||
{records&&<RecordsDrawer key={JSON.stringify(records)} open row={records.row} query={records.query} stage={stage} lockedStage onStage={()=>{}} onClose={()=>setRecords(null)} onUnauthorized={onUnauthorized}/>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Alert, Button, Select, Spin } from 'antd';
|
||||
import { CloseOutlined } from '@ant-design/icons';
|
||||
import { api } from './api';
|
||||
import type { QueryParams, SourceColumnField, SourceColumnFilter, Stage } from './types';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
|
||||
function SourceValues({field,stage,query,value,onChange,onUnauthorized}:{field:SourceColumnField;stage:Stage;query:QueryParams;value:string[];onChange:(value:string[])=>void;onUnauthorized:(error:unknown)=>boolean}) {
|
||||
const [search,setSearch]=useState('');const [choices,setChoices]=useState<string[]>([]);const [busy,setBusy]=useState(false);const [error,setError]=useState('');const [more,setMore]=useState(false);const [revision,setRevision]=useState(0);
|
||||
const contextKey=JSON.stringify(query);const current=useRef(0);
|
||||
useEffect(()=>{
|
||||
const generation=++current.current,controller=new AbortController();setBusy(true);setError('');setChoices([]);
|
||||
const timer=window.setTimeout(()=>{
|
||||
const {year,month,quarter,department,group,product,projectGroup,includeUnassigned,columnFilters,releaseId}=query;
|
||||
void api.sourceColumnValues({releaseId,period:{year,...(month?{month}:{}),...(quarter?{quarter}:{})},filters:{...(department?{department}:{}),...(group?{group}:{}),...(product?{product}:{}),...(projectGroup?{projectGroup}:{}),includeUnassigned:!!includeUnassigned,columnFilters:(columnFilters||[]).filter(rule=>rule.field!==field.key)},field:field.key,stages:[stage],search,limit:50,offset:0},controller.signal)
|
||||
.then(result=>{if(current.current!==generation)return;setChoices(result.values.filter((v):v is string=>typeof v==='string'));setMore(result.hasMore===true||(result.total??0)>50);})
|
||||
.catch(failure=>{if(controller.signal.aborted||current.current!==generation)return;if(!onUnauthorized(failure))setError(failure instanceof Error?failure.message:'选项读取失败');})
|
||||
.finally(()=>{if(current.current===generation)setBusy(false);});
|
||||
},search?300:0);
|
||||
return()=>{window.clearTimeout(timer);controller.abort();current.current++;};
|
||||
},[field.key,stage,contextKey,search,revision,onUnauthorized]);
|
||||
return <Select {...readableSelectPopup} mode="multiple" allowClear showSearch aria-label={`${field.label}筛选值`} placeholder="选择筛选值" value={value} searchValue={search} filterOption={false} onSearch={setSearch} loading={busy} maxTagCount="responsive" onChange={values=>{onChange(values);setSearch('');}} options={[...new Set([...choices,...value])].map(v=>({label:v,value:v}))} notFoundContent={busy?<Spin size="small"/>:error?<Button size="small" onClick={()=>setRevision(v=>v+1)}>读取失败,重试</Button>:'暂无匹配值'} popupRender={menu=><>{menu}{more&&<div className="query-options-hint">输入关键词搜索更多值</div>}{error&&<div role="alert" className="query-options-hint">{error}</div>}</>}/>;
|
||||
}
|
||||
export function StageSourceFilters({stage,fields,query,value,onChange,onUnauthorized,part='both'}:{part?:'both'|'picker'|'rows';stage:Stage;fields:SourceColumnField[];query:QueryParams;value:SourceColumnFilter[];onChange:(value:SourceColumnFilter[])=>void;onUnauthorized:(error:unknown)=>boolean}) {
|
||||
const selected=value.map(rule=>rule.field);const patch=(key:string,change:Partial<SourceColumnFilter>)=>onChange(value.map(rule=>rule.field===key?{...rule,...change}:rule));
|
||||
return <div className="stage-source-filters">
|
||||
{part!=='rows'&&<Select {...readableSelectPopup} mode="multiple" maxCount={20} maxTagCount="responsive" showSearch optionFilterProp="label" allowClear aria-label="选择筛选字段" placeholder="添加筛选字段" value={selected} options={fields.map(field=>({label:field.label,value:field.key}))} onChange={keys=>onChange(keys.map(key=>value.find(rule=>rule.field===key)||{field:key,stages:[stage],operator:'in',values:[]}))}/>}
|
||||
{part!=='picker'&&value.map(rule=>{const field=fields.find(item=>item.key===rule.field);return field?<div className="stage-source-filter-row" key={rule.field}><strong>{field.label}</strong><Select {...readableSelectPopup} aria-label={`${field.label}筛选方式`} value={rule.operator} options={[{label:'等于任一值',value:'in'},{label:'不等于这些值',value:'not_in'},{label:'为空',value:'is_empty'},{label:'不为空',value:'not_empty'}]} onChange={operator=>patch(rule.field,{operator,values:[]})}/>{['in','not_in'].includes(rule.operator)?<SourceValues field={field} stage={stage} query={query} value={rule.values||[]} onChange={values=>patch(rule.field,{values})} onUnauthorized={onUnauthorized}/>:<span/>}<Button type="text" aria-label={`移除${field.label}筛选`} icon={<CloseOutlined/>} onClick={()=>onChange(value.filter(item=>item.field!==rule.field))}/></div>:<Alert key={rule.field} type="warning" message="所选来源字段当前不可用,请移除后重新选择" action={<Button onClick={()=>onChange(value.filter(item=>item.field!==rule.field))}>移除</Button>}/>;})}
|
||||
</div>;
|
||||
}
|
||||
@@ -388,7 +388,6 @@ export function RuleDefinitionEditor({ value, onChange, schema, schemaError }: D
|
||||
{ key: 'source', label: '来源字段', children: <div><p className="structured-config-note" style={{ marginBottom: 12 }}>将计算字段对应到来源表列名。未修改项沿用原列名,字段别名用于公式引用。</p><Tabs items={['black', 'bright'].map(stage => ({ key: stage, label: stage === 'black' ? '黑片字段' : '亮片字段', children: <Table size="small" bordered rowKey="alias" pagination={false} scroll={{ x: 670 }} dataSource={Object.entries(objectValue(fields[stage])).map(([alias, header]) => ({ alias, header: String(header) }))} columns={[
|
||||
{ title: '计算字段', dataIndex: 'header', width: 240 }, { title: '公式别名', dataIndex: 'alias', width: 200, render: alias => <code>{alias}</code> },
|
||||
{ title: '来源表列名', key: 'source', render: (_, row) => <Input aria-label={`${stage === 'black' ? '黑片' : '亮片'} ${row.header}来源列名`} value={String(objectValue(sourceFields[stage])[row.alias] ?? row.header)} maxLength={200} onChange={event => onChange({ ...value, sourceFields: { ...sourceFields, [stage]: { ...objectValue(sourceFields[stage]), [row.alias]: event.target.value } } })} /> },
|
||||
{ title: '操作', key: 'reset', width: 100, render: (_, row) => <Button type="link" onClick={() => { const next = { ...objectValue(sourceFields[stage]) }; delete next[row.alias]; onChange({ ...value, sourceFields: { ...sourceFields, [stage]: next } }); }}>恢复原列名</Button> },
|
||||
]} /> }))} /></div> },
|
||||
{ key: 'rows', label: `行计算(${rowRules.length})`, children: <div><div className="structured-config-toolbar"><span>按顺序执行;未覆盖的结果沿用原计算。</span><div className="structured-config-actions"><Button type="primary" icon={<PlusOutlined />} disabled={rowRules.length >= maxRowRules} onClick={() => editRow(null)}>新增行公式</Button></div></div><Table size="small" bordered rowKey="index" columns={ruleColumns} dataSource={rowRules.map((row, index) => ({ ...row, index }))} pagination={false} scroll={{ x: 980 }} locale={{ emptyText: '当前全部沿用原始行计算' }} /><p className="structured-config-note">修改报废等分量后,如需改变合计结果,请同时维护依赖它的合计公式。</p></div> },
|
||||
{ key: 'metrics', label: '指标公式', children: <div className="structured-config-rule-list"><p className="structured-config-note">未开启覆盖的指标沿用原始公式。公式可引用重量变量及排在前面的指标结果。</p>{metricCodes.map((metric, index) => {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { Alert, App, Button, Drawer, Empty, Progress, Select, Spin, Tabs, Tag } from 'antd';
|
||||
import { ReloadOutlined, SettingOutlined } from '@ant-design/icons';
|
||||
import { QualityTable as Table } from './QualityTable';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { api } from './api';
|
||||
import { usePageCache } from './pageCache';
|
||||
import type { AuthUser } from './types';
|
||||
import { BackupOperationsPanel, OperationsMonitorPanel } from './GovernanceCompletion';
|
||||
import { configurationDateTime } from './configurationName';
|
||||
import { backupSummary, isActive, isFailed, monitorLabel, orderedTasks, taskFailure, taskPercent, type MonitorRow } from './taskMonitorModel';
|
||||
|
||||
export function TasksMonitorPage({user,onUnauthorized}:{user:AuthUser;onUnauthorized:(error:unknown)=>boolean}) {
|
||||
const {message}=App.useApp();
|
||||
const {active,refreshKey}=usePageCache();
|
||||
const [busy,setBusy]=useState(false);
|
||||
const [items,setItems]=useState<MonitorRow[]>([]);
|
||||
const [backup,setBackup]=useState<MonitorRow>({});
|
||||
const [taskError,setTaskError]=useState(''); const [backupError,setBackupError]=useState('');
|
||||
const [loading,setLoading]=useState(true); const [advanced,setAdvanced]=useState(false);
|
||||
const [filter,setFilter]=useState('all'); const [selected,setSelected]=useState<MonitorRow|null>(null);
|
||||
const canManage=user.roles.some(role=>['SYSTEM_ADMIN','SYSTEM_OPERATOR'].includes(role));
|
||||
const load=useCallback(async()=>{
|
||||
setLoading(true);
|
||||
await Promise.all([
|
||||
api.taskOverview().then(value=>{setItems(value.items);setTaskError('');}).catch(error=>{if(!onUnauthorized(error))setTaskError(error instanceof Error?error.message:'任务读取失败');}),
|
||||
api.latestBackup().then(value=>{setBackup(value);setBackupError('');}).catch(error=>{if(!onUnauthorized(error))setBackupError(error instanceof Error?error.message:'备份状态读取失败');}),
|
||||
]);setLoading(false);
|
||||
},[onUnauthorized]);
|
||||
useEffect(()=>{if(active)void load();},[load,active,refreshKey]);
|
||||
useEffect(()=>{if(!active)return;const timer=window.setInterval(()=>{if(document.visibilityState==='visible')void load();},15000);return()=>window.clearInterval(timer);},[load,active]);
|
||||
const runAction=async(row:MonitorRow,action:'retry'|'cancel')=>{
|
||||
setBusy(true);
|
||||
try {
|
||||
if(action==='retry') {const releases=await api.releases();await api.retryTask(String(row.id),{idempotencyKey:crypto.randomUUID(),expectedCurrentReleaseId:releases.currentReleaseId??null});}
|
||||
else await api.cancelTask(String(row.id),{expectedStatus:String(row.status)});
|
||||
message.success(action==='retry'?'已提交重试,请查看最新任务状态':'已取消排队任务');setSelected(null);await load();
|
||||
} catch(error){if(!onUnauthorized(error))message.error(error instanceof Error?error.message:'任务操作失败');}
|
||||
finally{setBusy(false);}
|
||||
};
|
||||
const latest=(backup.latest || {}) as MonitorRow;
|
||||
const columns:ColumnsType<MonitorRow>=[
|
||||
{title:'任务',key:'task',width:230,render:(_,row)=>monitorLabel(row.type,'后台任务')},
|
||||
{title:'进度',key:'progress',width:210,render:(_,row)=>{const percent=taskPercent(row);return <div className="compact-task-progress"><Tag color={isFailed(row)?'red':isActive(row)?'blue':row.status==='CANCELLED'?undefined:'green'}>{monitorLabel(row.status,'状态待确认')}</Tag>{percent!==null&&<Progress percent={percent} size="small" status={isFailed(row)?'exception':isActive(row)?'active':'normal'}/>}</div>;}},
|
||||
{title:'失败原因',key:'failure',width:360,render:(_,row)=><span style={{whiteSpace:'pre-wrap',overflowWrap:'anywhere',color:isFailed(row)?'var(--ant-color-error)':''}}>{taskFailure(row)}</span>},
|
||||
{title:'提交时间',dataIndex:'createdAt',width:180,render:value=>configurationDateTime(value)||'—'},
|
||||
{title:'',key:'action',width:75,render:(_,row)=><Button type="link" onClick={()=>setSelected(row)}>详情</Button>},
|
||||
];
|
||||
return <>
|
||||
<section className="panel section-panel">
|
||||
<div className="completion-panel-heading"><strong>任务进度</strong><div className="completion-actions"><Select aria-label="筛选任务" value={filter} onChange={setFilter} options={[{value:'all',label:'全部任务'},{value:'active',label:'进行中'},{value:'failed',label:'失败 / 未完成'},{value:'completed',label:'已完成'}]}/><Button icon={<ReloadOutlined/>} loading={loading} onClick={()=>void load()}>刷新</Button></div></div>
|
||||
{taskError&&<Alert showIcon type="error" message="任务暂不可用" description={taskError}/>}
|
||||
{loading&&!items.length?<Spin/>:!taskError&&<Table size="small" bordered columns={columns} dataSource={orderedTasks(items,filter)} rowKey={row=>`${row.sourceKind}-${row.id}`} pagination={{pageSize:8,showSizeChanger:false}} scroll={{x:1000}} locale={{emptyText:<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无符合条件的任务"/>}}/>}
|
||||
<p className="completion-note">每类最多显示 50 条记录,进行中及失败任务优先。智能分析仅显示本人任务。</p>
|
||||
</section>
|
||||
<section className="panel section-panel"><div className="completion-panel-heading"><strong>最近备份状态</strong></div>
|
||||
{backupError?<Alert showIcon type="error" message="备份状态暂不可用" description={backupError}/>:loading&&!latest.createdAt?<Spin/>:<div className="governance-monitor-grid"><div><small>最近备份</small><strong>{backupSummary(latest)}</strong></div><div><small>备份时间</small><strong>{configurationDateTime(latest.createdAt)||'—'}</strong></div><div><small>恢复验证时间</small><strong>{configurationDateTime(latest.restoreVerifiedAt)||'—'}</strong></div><div><small>自动备份</small><strong>{backup.planActive===true?'已启用':'未启用'}</strong></div></div>}
|
||||
</section>
|
||||
{canManage&&<><Button icon={<SettingOutlined/>} aria-expanded={advanced} onClick={()=>setAdvanced(!advanced)}>{advanced?'收起高级设置':'管理员高级设置'}</Button>{advanced&&<Tabs items={[{key:'monitor',label:'运行监控与告警',children:<OperationsMonitorPanel user={user} onUnauthorized={onUnauthorized}/>},{key:'backups',label:'备份管理',children:<BackupOperationsPanel user={user} onUnauthorized={onUnauthorized}/>} ]}/>}</>}
|
||||
<Drawer open={!!selected} title="任务详情" width={Math.min(620,window.innerWidth)} onClose={()=>setSelected(null)}>{selected&&<dl className="nc-form-grid"><dt>任务</dt><dd>{monitorLabel(selected.type,'后台任务')}</dd><dt>状态</dt><dd>{monitorLabel(selected.status)}</dd><dt>阶段</dt><dd>{monitorLabel(selected.stage,monitorLabel(selected.status))}</dd>{Number(selected.total)>0&&<><dt>已处理 / 总数</dt><dd>{String(selected.processed??0)} / {String(selected.total)}</dd></>}<dt>提交时间</dt><dd>{configurationDateTime(selected.createdAt)}</dd>{isFailed(selected)&&<><dt>失败原因</dt><dd style={{whiteSpace:'pre-wrap',overflowWrap:'anywhere'}}>{taskFailure(selected)}</dd></>}<dt>任务编号</dt><dd style={{overflowWrap:'anywhere'}}>{String(selected.id)}</dd></dl>}{selected?.sourceKind==='TASK'&&<div className="completion-actions">{selected.status==='FAILED'&&!!selected.importRunId&&user.roles.some(role=>['SYSTEM_ADMIN','DATA_MAINTAINER'].includes(role))&&<Button loading={busy} onClick={()=>void runAction(selected,'retry')}>重试导入</Button>}{selected.status==='QUEUED'&&user.roles.some(role=>['SYSTEM_ADMIN','SYSTEM_OPERATOR','DATA_MAINTAINER'].includes(role))&&<Button danger loading={busy} onClick={()=>void runAction(selected,'cancel')}>取消排队任务</Button>}</div>}{selected?.sourceKind==='ANALYSIS'&&!!selected.sessionId&&<Button href={`?page=analysis&sessionId=${encodeURIComponent(String(selected.sessionId))}&turnId=${encodeURIComponent(String(selected.id))}`}>查看分析记录</Button>}</Drawer>
|
||||
</>;
|
||||
}
|
||||
+112
-38
@@ -2,98 +2,172 @@
|
||||
.analysis-simple-page .analysis-workspace{height:calc(var(--dynamic-viewport-height) - 105px);min-height:540px;grid-template-columns:205px minmax(0,1fr)}
|
||||
.page-heading.page-actions-only{min-height:0;margin:0;justify-content:flex-end}
|
||||
.analysis-composer-buttons{display:flex;align-items:center;gap:8px}
|
||||
.analysis-simple-page .analysis-chat-panel{min-height:0;overflow:hidden;background:#fff}
|
||||
/* Keep the zoomed conversation's scrollable overflow inside its own panel. */
|
||||
.analysis-simple-page .analysis-chat-panel{min-height:0;overflow:clip;contain:layout paint;background:#fff}
|
||||
.analysis-simple-page .analysis-new-content{align-self:center;flex:none;margin:2px 0;color:var(--primary-color,#1677ff)}
|
||||
.analysis-simple-page .analysis-session-panel{min-height:0;overflow:hidden}
|
||||
.analysis-simple-page .analysis-session-list{flex:1;overflow:auto}
|
||||
.analysis-simple-page .analysis-session-item{padding:14px 12px;gap:5px}
|
||||
.analysis-simple-page .analysis-session-item small{font-size:11px}
|
||||
.analysis-simple-page .analysis-session-item small{font-size:var(--font-note)}
|
||||
.analysis-session-state{float:right;color:#1680c5;font-weight:500;margin-left:6px}
|
||||
.analysis-session-menu{flex:0 0 auto;margin-right:6px;color:var(--muted-ink,#738198)}
|
||||
.analysis-turn-metadata{display:flex;flex-wrap:wrap;gap:5px 14px;font-size:12px;color:var(--muted-ink,#738198);font-variant-numeric:tabular-nums}
|
||||
.analysis-simple-page .analysis-conversation{min-height:0;gap:26px;padding:30px max(24px,calc((100% - 850px)/2));scroll-behavior:auto;overscroll-behavior:contain}
|
||||
.analysis-simple-page .analysis-turn{gap:16px}
|
||||
.analysis-turn-metadata{display:flex;flex-wrap:wrap;gap:5px 14px;font-size:var(--font-control);color:var(--muted-ink,#738198);font-variant-numeric:tabular-nums}
|
||||
.analysis-simple-page .analysis-conversation{min-height:0;gap:26px;padding:30px max(24px,calc((100% - 850px)/2));scroll-behavior:auto;overscroll-behavior:contain;overflow-anchor:none}
|
||||
.analysis-simple-page .analysis-turn{gap:10px}
|
||||
.analysis-simple-page .analysis-question{width:auto;max-width:85%;padding:10px 16px;border:0;border-radius:12px;background:#eef2fa}
|
||||
.analysis-simple-page .analysis-question p{margin:0;font-size:14px}
|
||||
.analysis-simple-page .analysis-question p{margin:0;font-size:var(--font-section)}
|
||||
.analysis-simple-page .analysis-answer{padding:0;border:0;background:transparent}
|
||||
.analysis-simple-page .ai-answer{font-size:14px;line-height:1.95;padding:0;white-space:normal;overflow-wrap:anywhere;word-break:break-word}
|
||||
.analysis-simple-page .ai-answer p{margin:0 0 10px;white-space:normal}
|
||||
.analysis-simple-page .ai-answer h1,.analysis-simple-page .ai-answer h2,.analysis-simple-page .ai-answer h3,.analysis-simple-page .ai-answer h4,.analysis-simple-page .ai-answer h5,.analysis-simple-page .ai-answer h6{margin:18px 0 8px;color:#263c5a;line-height:1.5}
|
||||
.analysis-simple-page .ai-answer h1{font-size:20px}.analysis-simple-page .ai-answer h2{font-size:18px}.analysis-simple-page .ai-answer h3{font-size:16px}.analysis-simple-page .ai-answer h4,.analysis-simple-page .ai-answer h5,.analysis-simple-page .ai-answer h6{font-size:14px}
|
||||
.analysis-simple-page .ai-answer ul,.analysis-simple-page .ai-answer ol{padding-left:24px;margin:4px 0 12px}
|
||||
.analysis-simple-page .ai-answer li{padding-left:2px;margin:3px 0;overflow-wrap:anywhere}
|
||||
.analysis-simple-page .ai-answer{font-size:var(--font-reading);line-height:1.65;padding:0;white-space:normal;overflow-wrap:anywhere;word-break:break-word}
|
||||
.analysis-simple-page .ai-answer p{margin:0 0 6px;white-space:normal}
|
||||
.analysis-simple-page .ai-answer h1,.analysis-simple-page .ai-answer h2,.analysis-simple-page .ai-answer h3,.analysis-simple-page .ai-answer h4,.analysis-simple-page .ai-answer h5,.analysis-simple-page .ai-answer h6{margin:14px 0 6px;color:#263c5a;line-height:1.5}
|
||||
.analysis-simple-page .ai-answer h1{font-size:var(--font-page-title)}.analysis-simple-page .ai-answer h2{font-size:var(--font-page-title)}.analysis-simple-page .ai-answer h3{font-size:var(--font-dialog-title)}.analysis-simple-page .ai-answer h4,.analysis-simple-page .ai-answer h5,.analysis-simple-page .ai-answer h6{font-size:var(--font-section)}
|
||||
.analysis-simple-page .ai-answer ul,.analysis-simple-page .ai-answer ol{padding-left:24px;margin:4px 0 8px}
|
||||
.analysis-simple-page .ai-answer li{padding-left:2px;margin:2px 0;overflow-wrap:anywhere}
|
||||
.ai-markdown code{padding:1px 4px;border-radius:3px;background:#f0f3f7;font:0.92em ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}
|
||||
.ai-markdown pre{max-width:100%;overflow:auto;padding:12px;background:#f4f6f9;border:1px solid #e5eaf0;white-space:pre-wrap;overflow-wrap:anywhere}
|
||||
.ai-markdown pre code{padding:0;background:transparent;white-space:pre-wrap}
|
||||
.ai-markdown-table-wrap{max-width:100%;margin:10px 0 14px;overflow:auto;border:1px solid var(--line,#dfe5ed);border-radius:6px;background:var(--surface,#fff)}
|
||||
.ai-markdown table{width:100%;border-collapse:collapse;table-layout:fixed;font-size:13px;line-height:1.65}
|
||||
.ai-markdown table{width:100%;border-collapse:collapse;table-layout:fixed;font-size:var(--font-body);line-height:1.65}
|
||||
.ai-markdown th,.ai-markdown td{padding:9px 12px;border:1px solid var(--line,#dfe5ef);text-align:center;vertical-align:middle;overflow-wrap:anywhere;word-break:break-word}
|
||||
.ai-markdown th{background:color-mix(in srgb,var(--surface,#fff) 84%,var(--blue-soft,#eef1ff));font-weight:650}
|
||||
.ai-markdown tbody tr:nth-child(even)>td{background:color-mix(in srgb,var(--surface,#fff) 96%,var(--blue-soft,#eef1ff))}
|
||||
.ai-markdown .ai-markdown-index{width:64px;color:var(--muted-ink,#738198);font-variant-numeric:tabular-nums;white-space:nowrap}
|
||||
.analysis-simple-page .analysis-message-actions{display:flex;gap:6px;margin-top:10px}
|
||||
.analysis-simple-page .analysis-message-actions .ant-btn{color:#627189}
|
||||
.analysis-simple-page .analysis-chat-notice{font-size:12px;color:#93671e}
|
||||
.analysis-simple-page .analysis-progress{background:transparent;padding:0;gap:10px;color:#63718a}
|
||||
.analysis-member-list{display:grid;gap:9px;min-width:0;margin-top:4px;padding:12px;border:1px solid var(--line,#e5ebf3);border-radius:8px;background:var(--surface-subtle,#fafcfe);color:var(--ink,#263c5a)}
|
||||
.analysis-member-list-heading,.analysis-member-list-controls{display:flex;align-items:center;justify-content:space-between;gap:10px;min-width:0}
|
||||
.analysis-member-list-heading{font-size:var(--font-body)}
|
||||
.analysis-member-list-heading span,.analysis-member-list-controls>span{color:var(--muted-ink,#738198);font-size:var(--font-control)}
|
||||
.analysis-member-list-table{min-width:0;overflow:hidden}
|
||||
.analysis-member-cell{overflow-wrap:anywhere;white-space:pre-wrap}
|
||||
.analysis-member-stages{display:inline-flex;gap:4px;white-space:nowrap}
|
||||
.analysis-member-stages .ant-tag{margin-inline-end:0}
|
||||
.analysis-member-list-controls{justify-content:flex-end;flex-wrap:wrap}
|
||||
.analysis-member-list-controls>span{margin-right:auto}
|
||||
.analysis-member-list-state{display:flex;align-items:center;gap:8px;min-height:32px;color:var(--muted-ink,#738198);font-size:var(--font-control)}
|
||||
.analysis-member-list-error{margin-top:4px}
|
||||
.analysis-member-list .ant-alert{margin:0}
|
||||
.analysis-member-list .ant-pagination{margin:0}
|
||||
.analysis-member-list .quality-table-frame{width:100%;max-width:100%}
|
||||
.analysis-member-list .quality-table .ant-table-cell{overflow-wrap:anywhere;word-break:break-word}
|
||||
.analysis-record-list .ant-select{max-width:min(100%,520px)}
|
||||
.analysis-record-list .analysis-record-cell{white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word}
|
||||
.analysis-record-list-completeness{margin:0;color:var(--muted-ink,#738198);font-size:var(--font-control)}
|
||||
.analysis-simple-page .analysis-chat-notice{font-size:var(--font-control);color:#93671e}
|
||||
.analysis-process{border:1px solid var(--line,#e5ebf3);border-radius:8px;background:var(--surface-subtle,#fafcfe);min-width:0;color:var(--ink,#263c5a);color-scheme:inherit}
|
||||
.analysis-process-toggle{display:flex;align-items:center;gap:9px;padding:11px 13px;width:100%;border:0;background:transparent;color:var(--ink,#536780);text-align:left;cursor:pointer;font:inherit}
|
||||
.analysis-process-toggle>span:nth-last-child(2){margin-left:auto;font-size:12px;font-weight:400;color:var(--muted-ink,#7b899d)}
|
||||
.analysis-process-toggle strong{font-size:13px;font-weight:550}
|
||||
.analysis-process-toggle>span:nth-last-child(2){margin-left:auto;font-size:var(--font-control);font-weight:400;color:var(--muted-ink,#7b899d)}
|
||||
.analysis-process-toggle strong{font-size:var(--font-body);font-weight:550}
|
||||
.analysis-process-body{padding:0 14px 12px;max-height:360px;overflow:auto;overscroll-behavior:contain}
|
||||
.analysis-process-body ol{list-style:none;padding:0;margin:0}
|
||||
.analysis-model-reasoning{padding:10px 0 14px;color:var(--muted-ink,#63758b)}
|
||||
.analysis-model-reasoning>strong{color:var(--ink);font-size:13px}
|
||||
.analysis-model-reasoning pre{margin:8px 0 0;max-height:240px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;font:inherit;font-size:12px;line-height:1.8}
|
||||
.analysis-model-reasoning p{margin:8px 0 0;font-size:12px}
|
||||
.analysis-model-reasoning>strong{color:var(--ink);font-size:var(--font-body)}
|
||||
.analysis-model-reasoning pre{margin:8px 0 0;max-height:240px;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;font:inherit;font-size:var(--font-control);line-height:1.8}
|
||||
.analysis-model-reasoning p{margin:8px 0 0;font-size:var(--font-control)}
|
||||
.analysis-process-body li{padding:10px 0;border-top:1px solid var(--line,#edf1f6)}
|
||||
.analysis-process-step{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--muted-ink,#63758b)}
|
||||
.analysis-process-step{display:flex;align-items:center;gap:8px;font-size:var(--font-control);color:var(--muted-ink,#63758b)}
|
||||
.analysis-process-step strong{color:var(--ink,#3e536e);font-weight:500}
|
||||
.analysis-process-step>span:last-child{margin-left:auto;color:var(--muted-ink,#8390a2);white-space:nowrap}
|
||||
.analysis-process-body details{margin:7px 0 0 23px;color:var(--muted-ink,#7b899c);font-size:12px}
|
||||
.analysis-process-body details{margin:7px 0 0 23px;color:var(--muted-ink,#7b899c);font-size:var(--font-control)}
|
||||
.analysis-process-body summary{cursor:pointer}
|
||||
.analysis-process-body pre{margin:6px 0;white-space:pre-wrap;overflow-wrap:anywhere;font-family:inherit;font-size:12px;line-height:1.8;color:var(--muted-ink,#5e7088)}
|
||||
.analysis-process-body li p,.analysis-process-current{font-size:12px;line-height:1.8;color:var(--muted-ink,#7b899b);margin:5px 0 0 23px}
|
||||
.analysis-process-body pre{margin:6px 0;white-space:pre-wrap;overflow-wrap:anywhere;font-family:inherit;font-size:var(--font-control);line-height:1.8;color:var(--muted-ink,#5e7088)}
|
||||
.analysis-process-body li p,.analysis-process-current{font-size:var(--font-control);line-height:1.8;color:var(--muted-ink,#7b899b);margin:5px 0 0 23px}
|
||||
.analysis-process-current{margin:10px 0 0;color:var(--ink,#526b8a)}
|
||||
:root[data-workspace-theme='dark'] .analysis-simple-page .ai-answer :is(h1,h2,h3,h4,h5,h6),
|
||||
:root[data-workspace-theme='dark'] .analysis-simple-page .analysis-empty strong{color:var(--ink)}
|
||||
:root[data-workspace-theme='dark'] .analysis-simple-page :is(.analysis-progress,.analysis-empty span,.ai-actions),
|
||||
:root[data-workspace-theme='dark'] .analysis-simple-page :is(.analysis-empty span,.ai-actions),
|
||||
:root[data-workspace-theme='dark'] .analysis-simple-page .analysis-message-actions .ant-btn{color:var(--muted-ink)}
|
||||
:root[data-workspace-theme='dark'] .analysis-simple-page .analysis-chat-notice{color:#e8bd74}
|
||||
:root[data-workspace-theme='dark'] .analysis-member-list{border-color:var(--line);background:var(--surface-subtle);color:var(--ink)}
|
||||
:root[data-workspace-theme='dark'] .analysis-simple-page .ai-markdown :is(code,pre){background:var(--surface-subtle);color:var(--ink);border-color:var(--line)}
|
||||
:root[data-workspace-theme='dark'] .analysis-simple-page .ai-markdown pre code{background:transparent}
|
||||
.analysis-simple-page .analysis-composer{padding:16px max(24px,calc((100% - 850px)/2));border-top:0;gap:7px}
|
||||
.analysis-simple-page .analysis-composer textarea{font-size:14px;padding:13px 15px;border-radius:10px!important;resize:none}
|
||||
.analysis-simple-page .ai-actions{font-size:11px;color:#7a8598}
|
||||
.analysis-simple-page .analysis-composer{flex:none;padding:16px max(24px,calc((100% - 850px)/2));border-top:0;gap:7px}
|
||||
.analysis-simple-page .analysis-composer textarea{font-size:var(--font-section);padding:13px 15px;border-radius:10px!important;resize:none}
|
||||
.analysis-simple-page .ai-actions{font-size:var(--font-note);color:#7a8598}
|
||||
.analysis-simple-page .analysis-empty{gap:10px}
|
||||
.analysis-simple-page .analysis-empty strong{font-size:20px;color:#3c4d67;font-weight:550}
|
||||
.analysis-simple-page .analysis-empty span{font-size:13px;color:#7b8799}
|
||||
.analysis-simple-page .analysis-empty strong{font-size:var(--font-page-title);color:#3c4d67;font-weight:550}
|
||||
.analysis-simple-page .analysis-empty span{font-size:var(--font-body);color:#7b8799}
|
||||
.analysis-report-preview{max-height:calc(var(--dynamic-viewport-height) * .65);overflow:auto;background:#edf1f5;border:1px solid #e6ebf2}
|
||||
.analysis-report-preview .q-report{margin:auto}
|
||||
.analysis-report-preview .native-analysis-report-frame{display:block;width:900px;max-width:none;margin:0 auto;border:0;background:#fff}
|
||||
.analysis-report-preview .native-analysis-report{box-sizing:border-box;width:900px;margin:0 auto;padding:48px;background:#fff;color:#263346;font:15px/1.85 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;overflow-wrap:anywhere;word-break:break-word}
|
||||
.analysis-report-preview .native-analysis-report{box-sizing:border-box;width:900px;margin:0 auto;padding:48px;background:#fff;color:#263346;font:var(--font-dialog-title)/1.85 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;overflow-wrap:anywhere;word-break:break-word}
|
||||
.native-analysis-report .ai-markdown h1,.native-analysis-report .ai-markdown h2,.native-analysis-report .ai-markdown h3,.native-analysis-report .ai-markdown h4,.native-analysis-report .ai-markdown h5,.native-analysis-report .ai-markdown h6{color:#253a58;line-height:1.5}
|
||||
.native-analysis-report .ai-markdown h1{font-size:28px;margin:0 0 22px;padding-bottom:14px;border-bottom:2px solid #355f9b}
|
||||
.native-analysis-report .ai-markdown h2{font-size:21px;margin:28px 0 12px}
|
||||
.native-analysis-report .ai-markdown h3{font-size:17px;margin:22px 0 9px}
|
||||
.native-analysis-report .ai-markdown p{margin:10px 0}
|
||||
.native-analysis-report .ai-markdown li{margin:4px 0}
|
||||
.native-analysis-report .ai-markdown table{font-size:13px}
|
||||
.native-analysis-report .ai-markdown table{font-size:var(--font-body)}
|
||||
.native-analysis-report .ai-markdown th,.native-analysis-report .ai-markdown td{padding:9px 10px}
|
||||
.native-analysis-report .ai-markdown th{background:#edf3fa}
|
||||
.native-analysis-report .ai-markdown pre{white-space:pre-wrap}
|
||||
@media(max-width:1000px){.analysis-simple-page .analysis-workspace{grid-template-columns:170px minmax(0,1fr)}.analysis-simple-page .analysis-conversation,.analysis-simple-page .analysis-composer{padding-left:20px;padding-right:20px}}
|
||||
@media(max-width:700px){.analysis-simple-page .analysis-workspace{grid-template-columns:1fr;height:calc(100dvh - 105px);min-height:480px}.analysis-simple-page .analysis-session-panel{max-height:100px}.analysis-simple-page .analysis-session-heading{min-height:36px}.analysis-simple-page .analysis-session-list{display:flex;overflow-x:auto}.analysis-simple-page .analysis-session-row{min-width:160px}.analysis-simple-page .analysis-session-item{padding:8px}.analysis-simple-page .analysis-session-item small{display:none}.analysis-simple-page .analysis-conversation{padding:18px 14px}.analysis-simple-page .analysis-composer{padding:12px 14px}.analysis-simple-page .analysis-question{max-width:92%}}
|
||||
@media(max-width:760px){.analysis-simple-page .analysis-workspace{height:calc(100dvh - 113px);min-height:0}}
|
||||
@media(max-width:700px){.analysis-simple-page .analysis-workspace{grid-template-columns:1fr;height:calc(100dvh - 113px);min-height:0}.analysis-simple-page .analysis-session-panel{max-height:100px}.analysis-simple-page .analysis-session-heading{min-height:36px}.analysis-simple-page .analysis-session-list{display:flex;overflow-x:auto}.analysis-simple-page .analysis-session-row{min-width:160px}.analysis-simple-page .analysis-session-item{padding:8px}.analysis-simple-page .analysis-session-item small{display:none}.analysis-simple-page .analysis-conversation{padding:18px 14px}.analysis-simple-page .analysis-composer{padding:12px 14px}.analysis-simple-page .analysis-question{max-width:92%}}
|
||||
@media(prefers-reduced-motion:reduce){.analysis-simple-page .analysis-conversation{scroll-behavior:auto}}
|
||||
|
||||
.analysis-event-stream { display: grid; gap: 6px; margin: 8px 0; }
|
||||
.analysis-thinking-block{margin:0;color:var(--muted-ink,#63758b);min-width:0}
|
||||
.analysis-thinking-block>summary{display:flex;align-items:center;gap:6px;width:fit-content;cursor:pointer;list-style:none;min-height:24px;font-size:var(--font-body)}
|
||||
.analysis-thinking-block>summary::-webkit-details-marker{display:none}
|
||||
.analysis-thinking-block>summary .anticon{font-size:var(--font-note);transition:transform .16s ease}
|
||||
.analysis-thinking-block[open]>summary .anticon{transform:rotate(90deg)}
|
||||
.analysis-thinking-block>summary:focus-visible{outline:2px solid var(--primary-color,#607ae1);outline-offset:3px}
|
||||
.analysis-thinking-text{border-left:2px solid var(--line,#e5ebf3);padding:2px 0 2px 12px;margin:6px 0 8px}
|
||||
.analysis-thinking-text pre{white-space:pre-wrap;overflow-wrap:anywhere;font:inherit;font-size:var(--font-body);line-height:1.65;margin:0;color:inherit;background:transparent;border:0}
|
||||
.analysis-agent-stream{display:grid;gap:6px;min-width:0;padding:4px 0 8px}
|
||||
.analysis-agent-process>summary{margin:0 0 4px}
|
||||
.analysis-agent-process>summary .analysis-turn-metadata{margin:0;padding:0;min-height:24px}
|
||||
.analysis-agent-stream .analysis-event-tool{border:0;background:transparent;border-radius:0}
|
||||
.analysis-agent-stream .analysis-tool-heading{padding:2px 0;height:auto;min-height:24px;font-size:var(--font-body)}
|
||||
.analysis-agent-stream .analysis-tool-heading strong{font-weight:400}
|
||||
.analysis-agent-stream .analysis-tool-chevron{margin-left:0}
|
||||
.analysis-agent-stream .analysis-tool-details{padding:0 0 4px 24px}
|
||||
.analysis-agent-stream .analysis-event-note{padding:0;background:transparent}
|
||||
.analysis-agent-stream .analysis-event-note .ai-answer{margin:0}
|
||||
@media(prefers-reduced-motion:reduce){.analysis-thinking-block>summary .anticon{transition:none}}
|
||||
.analysis-event-tool { min-width: 0; border-left: 2px solid var(--border-color, #667085); background: var(--panel-bg, rgba(127,127,127,.06)); border-radius: 0 6px 6px 0; overflow-wrap: anywhere; }
|
||||
.analysis-tool-heading { display: flex; align-items: center; gap: 8px; height: 36px; box-sizing: border-box; padding: 6px 12px; cursor: pointer; list-style: none; font-size: 12px; color: var(--muted-ink, #63758b); }
|
||||
.analysis-tool-heading { display: flex; align-items: center; gap: 8px; height: 36px; box-sizing: border-box; padding: 6px 12px; cursor: pointer; list-style: none; font-size: var(--font-control); color: var(--muted-ink, #63758b); }
|
||||
.analysis-tool-heading::-webkit-details-marker { display: none; }
|
||||
.analysis-tool-heading strong { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-weight: 550; }
|
||||
.analysis-tool-heading:focus-visible { outline: 2px solid #7b91ef; outline-offset: 2px; }
|
||||
.analysis-tool-chevron { margin-left: auto; font-size: 10px; }
|
||||
.analysis-tool-chevron { margin-left: auto; font-size: var(--font-note); }
|
||||
.analysis-event-tool[open] > summary .analysis-tool-chevron { transform: rotate(90deg); }
|
||||
.analysis-tool-details { padding: 0 12px 10px; font-size: 12px; color: var(--muted-ink, #63758b); }
|
||||
.analysis-event-tool p { margin: 8px 0; white-space: pre-wrap; }
|
||||
.analysis-event-conditions { font-size: 12px; opacity: .8; }
|
||||
.analysis-tool-details { padding: 0 12px 10px; font-size: var(--font-control); color: var(--muted-ink, #63758b); }
|
||||
.analysis-event-tool p { margin: 4px 0; white-space: pre-wrap; }
|
||||
.analysis-event-conditions { font-size: var(--font-control); opacity: .8; }
|
||||
.analysis-event-tool.is-failed { border-left-color: #d66; }
|
||||
.analysis-turn-scope{margin:0;color:var(--muted-ink,#63758b);font-size:var(--font-control);line-height:1.7;overflow-wrap:anywhere}
|
||||
.analysis-process-history{margin:0;min-width:0;color:var(--muted-ink,#63758b)}
|
||||
.analysis-process-history>summary{display:flex;align-items:center;gap:8px;width:fit-content;min-height:24px;cursor:pointer;list-style:none;font-size:var(--font-control)}
|
||||
.analysis-process-history>summary::-webkit-details-marker{display:none}
|
||||
.analysis-process-history>summary .anticon{font-size:var(--font-note);transition:transform .16s ease}
|
||||
.analysis-process-history[open]>summary .anticon{transform:rotate(90deg)}
|
||||
.analysis-process-history>summary:focus-visible{outline:2px solid var(--primary-color,#607ae1);outline-offset:3px}
|
||||
.analysis-process-history-body{padding:8px 0;max-height:360px;overflow:auto;overscroll-behavior:contain}
|
||||
.analysis-queued-followup{display:flex;align-items:center;gap:8px;color:var(--muted-ink,#63758b);font-size:var(--font-control);min-width:0}
|
||||
.analysis-queued-followup>span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.analysis-queued-followup .ant-btn{flex:none;font-size:var(--font-control)}
|
||||
@media(max-width:700px){.analysis-simple-page .ai-actions{align-items:flex-start;gap:8px;flex-wrap:wrap}.analysis-composer-buttons{margin-left:auto;gap:5px}}
|
||||
@media(prefers-reduced-motion:reduce){.analysis-process-history>summary .anticon{transition:none}}
|
||||
|
||||
@keyframes analysis-event-appear{from{opacity:.4;transform:translateY(2px)}to{opacity:1;transform:none}}
|
||||
.analysis-agent-stream>*{animation:analysis-event-appear .14s ease-out}
|
||||
@media(prefers-reduced-motion:reduce){.analysis-agent-stream>*{animation:none}}
|
||||
|
||||
:root[data-workspace-theme='dark'] .analysis-simple-page .analysis-turn .analysis-answer{background:transparent}
|
||||
|
||||
.analysis-clarification{max-width:720px;margin:6px 0 12px}
|
||||
.analysis-clarification fieldset{min-width:0;margin:0;padding:0;border:0}
|
||||
.analysis-clarification legend{display:block;width:100%;margin:0 0 14px;padding:0;color:var(--ink,#263c5a);font-size:var(--font-dialog-title);line-height:1.7;overflow-wrap:anywhere}
|
||||
.analysis-clarification-options{display:grid;gap:8px;margin-bottom:12px}
|
||||
.analysis-clarification-option{display:flex;align-items:center;gap:10px;padding:11px 13px;border:1px solid var(--line,#e5ebf3);border-radius:7px;cursor:pointer;background:var(--surface,#fff);color:var(--ink,#263c5a)}
|
||||
.analysis-clarification-option:hover,.analysis-clarification-option.is-selected{border-color:var(--primary-color,#607ae1);background:var(--blue-soft,#eef1ff)}
|
||||
.analysis-clarification-option input{flex:0 0 auto;width:15px;height:15px;margin:0;accent-color:var(--primary-color,#607ae1)}
|
||||
.analysis-clarification-option>span:nth-child(2){min-width:0;flex:1;overflow-wrap:anywhere}
|
||||
.analysis-clarification-option strong{display:block;font-size:var(--font-section);font-weight:500}
|
||||
.analysis-clarification-option small{display:block;margin-top:3px;color:var(--muted-ink,#738198);font-size:var(--font-control);line-height:1.6}
|
||||
.analysis-clarification-index{color:var(--muted-ink,#738198);font-size:var(--font-control)}
|
||||
.analysis-clarification-actions{display:flex;justify-content:flex-end;margin-top:10px}
|
||||
.analysis-clarification fieldset:disabled .analysis-clarification-option{cursor:default;opacity:.65}
|
||||
.analysis-clarification-option:focus-within{outline:2px solid var(--primary-color,#607ae1);outline-offset:2px}
|
||||
|
||||
@@ -2,66 +2,138 @@
|
||||
.analysis-narrative-section{min-width:0;padding:22px 0;border-bottom:1px solid var(--line,#dfe5ef)}
|
||||
.analysis-narrative-section:first-child{padding-top:2px}
|
||||
.analysis-narrative-section:last-of-type{border-bottom:0}
|
||||
.analysis-narrative-title{margin:0 0 12px;font-size:18px;line-height:1.55;color:var(--ink,#263c5a);font-weight:650}
|
||||
.analysis-narrative-section>.ai-answer{font-size:14px;line-height:1.85}
|
||||
.analysis-narrative-section.is-overview>.ai-answer>p:first-child{font-size:16px;line-height:1.85}
|
||||
.analysis-narrative-details{margin:12px 0 0;padding-top:8px;color:var(--muted-ink,#65748b);font-size:12px}
|
||||
.analysis-narrative-title{margin:0 0 12px;font-size:var(--font-page-title);line-height:1.55;color:var(--ink,#263c5a);font-weight:650}
|
||||
.analysis-narrative-section>.ai-answer{font-size:var(--font-reading);line-height:1.85}
|
||||
.analysis-narrative-section.is-overview>.ai-answer>p:first-child{font-size:var(--font-dialog-title);line-height:1.85}
|
||||
.analysis-focus-products{min-width:0}
|
||||
.analysis-focus-table-wrap{max-width:100%;overflow-x:auto;border:1px solid var(--line,#dfe5ef)}
|
||||
.analysis-focus-table{width:100%;min-width:580px;border-collapse:collapse;font-size:var(--font-control);line-height:1.6;font-variant-numeric:tabular-nums}
|
||||
.analysis-focus-table th,.analysis-focus-table td{padding:9px 11px;border-right:1px solid var(--line,#dfe5ef);border-bottom:1px solid var(--line,#dfe5ef);vertical-align:middle;text-align:left}
|
||||
.analysis-focus-table th:last-child,.analysis-focus-table td:last-child{border-right:0}
|
||||
.analysis-focus-table tbody tr:last-child>*{border-bottom:0}
|
||||
.analysis-focus-table thead th{font-weight:600;background:var(--surface-subtle,#f4f7fb);white-space:nowrap}
|
||||
.analysis-focus-table .is-index{width:40px;text-align:center;color:var(--muted-ink,#65748b)}
|
||||
.analysis-focus-table .is-number{text-align:right}
|
||||
.analysis-focus-table .analysis-focus-product{min-width:135px;max-width:260px;font-weight:550;overflow-wrap:anywhere;word-break:normal}
|
||||
.analysis-focus-rate{min-width:108px}
|
||||
.analysis-focus-rate>span{display:block;color:var(--muted-ink,#65748b);font-size:var(--font-note)}
|
||||
.analysis-focus-rate.is-worse{color:var(--danger,#c64446)}
|
||||
.analysis-focus-rate.is-better{color:var(--success,#008f7d)}
|
||||
:root[data-workspace-theme='dark'] .analysis-conversation .analysis-narrative:not(.report-narrative) .analysis-focus-rate.is-worse{color:#ff9292}
|
||||
:root[data-workspace-theme='dark'] .analysis-conversation .analysis-narrative:not(.report-narrative) .analysis-focus-rate.is-better{color:#61d8bb}
|
||||
.analysis-focus-basis{min-width:115px}
|
||||
.analysis-focus-basis .analysis-evidence-ref{display:block;margin-left:0;font-size:var(--font-note)}
|
||||
.analysis-focus-details .analysis-focus-detail{font-size:var(--font-control);line-height:1.85;color:var(--ink,#263c5a);overflow-wrap:anywhere}
|
||||
.analysis-focus-details .analysis-focus-detail+.analysis-focus-detail{margin-top:10px}
|
||||
.q-report .analysis-focus-table{font-size:var(--font-control);min-width:0}
|
||||
.q-report .analysis-focus-table th,.q-report .analysis-focus-table td{padding:10px 12px}
|
||||
.analysis-narrative-details{margin:12px 0 0;padding-top:8px;color:var(--muted-ink,#65748b);font-size:var(--font-control)}
|
||||
.analysis-narrative-details>summary{cursor:pointer;min-height:28px;line-height:28px;font-weight:550}
|
||||
.analysis-narrative-details[open]>summary{margin-bottom:8px}
|
||||
.analysis-narrative .analysis-visuals.is-embedded{margin:12px 0 4px;gap:16px}
|
||||
.analysis-visuals.is-embedded>.analysis-visual-card{padding:8px 0;border:0;box-shadow:none;background:transparent}
|
||||
.analysis-visuals.is-embedded .analysis-visual-heading h3{font-size:14px;font-weight:550}
|
||||
.analysis-visuals.is-embedded .analysis-visual-heading h3{font-size:var(--font-section);font-weight:550}
|
||||
.analysis-visuals.is-embedded .analysis-visual-heading-copy>p{display:none}
|
||||
.analysis-visuals.is-embedded .analysis-visual-context{margin-top:3px}
|
||||
.analysis-visuals.is-embedded .analysis-visual-type-label{display:none}
|
||||
.analysis-visuals.is-embedded .analysis-visual-note{border:0;background:transparent;padding:2px 0;font-size:11px}
|
||||
.analysis-visuals.is-embedded .analysis-visual-note{border:0;background:transparent;padding:2px 0;font-size:var(--font-note)}
|
||||
.analysis-rate-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,280px),1fr));gap:14px;margin:16px 0 10px}
|
||||
.analysis-rate-readout{padding:16px 18px;background:var(--surface-subtle,#f4f7fb);border-radius:6px;min-width:0;font-variant-numeric:tabular-nums}
|
||||
.analysis-rate-name{font-size:13px;font-weight:600;margin-bottom:12px;color:var(--muted-ink,#65748b)}
|
||||
.analysis-rate-scope{font-size:11px;line-height:1.6;margin:-5px 0 10px;color:var(--muted-ink,#65748b);overflow-wrap:anywhere}
|
||||
.analysis-rate-name{font-size:var(--font-body);font-weight:600;margin-bottom:12px;color:var(--muted-ink,#65748b)}
|
||||
.analysis-rate-scope{font-size:var(--font-note);line-height:1.6;margin:-5px 0 10px;color:var(--muted-ink,#65748b);overflow-wrap:anywhere}
|
||||
.analysis-rate-values{display:flex;align-items:center;gap:14px;flex-wrap:wrap}
|
||||
.analysis-rate-values small{display:block;font-size:11px;color:var(--muted-ink,#65748b);margin-bottom:4px}
|
||||
.analysis-rate-values small{display:block;font-size:var(--font-note);color:var(--muted-ink,#65748b);margin-bottom:4px}
|
||||
.analysis-rate-values span,.analysis-rate-values strong{font-variant-numeric:tabular-nums}
|
||||
.analysis-rate-values em{font-style:normal;font-size:.58em;margin-left:2px}
|
||||
.analysis-rate-previous>span{font-size:23px;font-weight:500;color:var(--muted-ink,#65748b)}
|
||||
.analysis-rate-current>strong{font-size:30px;font-weight:700;letter-spacing:-.6px;color:var(--ink,#263c5a)}
|
||||
.analysis-rate-arrow{color:var(--muted-ink,#65748b);font-size:18px}
|
||||
.analysis-rate-arrow{color:var(--muted-ink,#65748b);font-size:var(--font-page-title)}
|
||||
.analysis-rate-change{margin-left:auto;display:flex;flex-direction:column;gap:3px;text-align:right}
|
||||
.analysis-rate-change>strong{font-size:19px}
|
||||
.analysis-rate-change>span{font-size:10px;color:var(--muted-ink,#65748b)}
|
||||
.analysis-rate-change>strong{font-size:var(--font-page-title)}
|
||||
.analysis-rate-change>span{font-size:var(--font-note);color:var(--muted-ink,#65748b)}
|
||||
.analysis-rate-change.is-worse>strong{color:var(--danger,#c64446)}
|
||||
.analysis-rate-change.is-better>strong{color:var(--success,#008f7d)}
|
||||
.analysis-evidence-ref{font-size:.78em;font-weight:500;white-space:nowrap;text-decoration:none;color:var(--muted-ink,#65748b);margin-left:4px}
|
||||
.analysis-evidence-ref:hover{text-decoration:underline;color:var(--blue,#607ae1)}
|
||||
.analysis-narrative-evidence{margin-top:20px;padding-top:14px;border-top:1px solid var(--line,#dfe5ef);font-size:11px;color:var(--muted-ink,#65748b)}
|
||||
.analysis-narrative-evidence h3{font-size:12px;margin:0 0 8px;font-weight:600}
|
||||
.analysis-narrative-evidence{margin-top:20px;padding-top:14px;border-top:1px solid var(--line,#dfe5ef);font-size:var(--font-note);color:var(--muted-ink,#65748b)}
|
||||
.analysis-narrative-evidence h3{font-size:var(--font-control);margin:0 0 8px;font-weight:600}
|
||||
.analysis-narrative-evidence ol{list-style:none;padding:0;margin:0;display:grid;gap:7px}
|
||||
.analysis-narrative-evidence li{display:flex;gap:8px;flex-wrap:wrap;scroll-margin-top:22px;line-height:1.7}
|
||||
.analysis-narrative-evidence li>strong{font-weight:550;min-width:40px}
|
||||
.analysis-narrative-evidence li>span{flex:1;min-width:130px}
|
||||
.analysis-narrative-evidence code{background:transparent;font:inherit;opacity:.85}
|
||||
.q-report .analysis-narrative-section{padding:24px 0}
|
||||
.q-report .analysis-narrative-title{font-size:20px!important;margin:0 0 12px!important}
|
||||
.q-report .q-report-question{font-size:12px;color:#65748b;margin:10px 0 0}
|
||||
.q-report .q-report-contents{display:flex;flex-wrap:wrap;gap:8px 18px;padding:16px 0 8px;font-size:11px;line-height:1.8}
|
||||
.q-report .analysis-narrative-title{font-size:var(--font-page-title)!important;margin:0 0 12px!important}
|
||||
.q-report .q-report-question{font-size:var(--font-control);color:#65748b;margin:10px 0 0}
|
||||
.q-report .q-report-contents{display:flex;flex-wrap:wrap;gap:8px 18px;padding:16px 0 8px;font-size:var(--font-note);line-height:1.8}
|
||||
.q-report .q-report-contents a,.q-report-detail-link a{color:#65748b;text-decoration:none}
|
||||
.q-report .q-report-contents a:hover,.q-report-detail-link a:hover{text-decoration:underline}
|
||||
.q-report .q-report-detail-link{font-size:11px}
|
||||
.q-report .q-report-detail-link{font-size:var(--font-note)}
|
||||
.q-report .analysis-narrative-evidence{padding-top:14px!important;margin-top:22px!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-narrative-evidence summary{font-size:var(--font-body)!important}
|
||||
.q-report .analysis-rate-grid{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
.q-report .analysis-rate-grid:has(>.analysis-rate-readout:only-child){grid-template-columns:1fr}
|
||||
.q-report .analysis-rate-readout{--surface-subtle:#f4f7fb}
|
||||
.q-report .analysis-narrative-details>summary{font-size:12px;color:#65748b}
|
||||
.q-report .analysis-narrative-details>summary{font-size:var(--font-control);color:#65748b}
|
||||
.q-report-visual{margin:14px 0}
|
||||
.q-report-visual figcaption{font-size:12px;line-height:1.8;color:#65748b;margin:8px 0 12px}
|
||||
.q-report-visual figcaption{font-size:var(--font-control);line-height:1.8;color:#65748b;margin:8px 0 12px}
|
||||
.q-report-visual>img{display:block;width:100%;height:auto}
|
||||
.q-report-visual-heading{display:flex;justify-content:space-between;gap:16px;align-items:baseline;margin:10px 0 4px}
|
||||
.q-report-visual-heading strong{font-size:14px;font-weight:600}
|
||||
.q-report-visual-heading span{font-size:11px;color:#65748b}
|
||||
.q-report-visual-heading strong{font-size:var(--font-section);font-weight:600}
|
||||
.q-report-visual-heading span{font-size:var(--font-note);color:#65748b}
|
||||
.q-report-appendix{margin-top:30px;padding-top:14px;border-top:1px solid #dfe5ef}
|
||||
.q-report-appendix>summary{font-size:15px;font-weight:600;cursor:pointer;line-height:2}
|
||||
.q-report-appendix h3{font-size:14px;margin:20px 0 9px}
|
||||
@media(max-width:640px){.analysis-narrative-section{padding:18px 0}.analysis-narrative-title{font-size:17px}.analysis-rate-readout{padding:13px}.analysis-rate-values{gap:10px}.analysis-rate-change>span{font-size:11px}.analysis-narrative-evidence li{display:block}.analysis-narrative-evidence li>*{margin-right:6px}}
|
||||
.q-report-appendix>summary{font-size:var(--font-dialog-title);font-weight:600;cursor:pointer;line-height:2}
|
||||
.q-report-appendix h3{font-size:var(--font-section);margin:20px 0 9px}
|
||||
@media(max-width:640px){.analysis-narrative-section{padding:18px 0}.analysis-narrative-title{font-size:17px}.analysis-rate-readout{padding:13px}.analysis-rate-values{gap:10px}.analysis-rate-change>span{font-size:var(--font-note)}.analysis-narrative-evidence li{display:block}.analysis-narrative-evidence li>*{margin-right:6px}}
|
||||
@media print{.q-report details:not([open])>*:not(summary){display:block}.q-report details>summary{list-style:none}.q-report .analysis-narrative-section{break-before:auto}.q-report figure,.q-report .analysis-rate-readout{break-inside:avoid}.q-report .analysis-evidence-ref{color:#65748b}}
|
||||
|
||||
.analysis-reading-summary{padding:18px 0 12px}
|
||||
.analysis-reading-summary .analysis-narrative-title{margin:0 0 12px}
|
||||
.analysis-reading-evidence h4{font-size:var(--font-body);font-weight:600;margin:14px 0 6px;color:var(--muted-ink,#65748b)}
|
||||
.analysis-reading-evidence>ul{padding-left:20px;margin:0}
|
||||
.analysis-reading-evidence .ai-markdown>p{margin:5px 0}
|
||||
.analysis-reading-notices{border-left:3px solid #d4b064;padding:4px 12px;margin:14px 0;color:#866326}
|
||||
.analysis-full-appendix{margin-top:12px;padding-top:12px;border-top:1px solid var(--line,#dfe5ef)}
|
||||
.analysis-full-appendix>summary{cursor:pointer;color:var(--muted-ink,#65748b);font-size:var(--font-body);font-weight:600;padding:6px 0}
|
||||
.analysis-full-appendix[open]>summary{margin-bottom:8px}
|
||||
.analysis-full-appendix .analysis-narrative-section:first-child{padding-top:16px}
|
||||
|
||||
/* A conclusion reads as a headline, short findings and comparisons, not a wall of prose. */
|
||||
.analysis-narrative .analysis-conclusion-layout{font-size:var(--font-section);line-height:1.75;font-variant-numeric:tabular-nums}
|
||||
.analysis-narrative .analysis-conclusion-layout>p{margin:12px 0;max-width:76ch;text-wrap:pretty}
|
||||
.analysis-narrative .analysis-conclusion-layout>.analysis-conclusion-lead{margin:0 0 18px;padding:0 0 0 16px;border-left:3px solid var(--blue,#607ae1);font-size:var(--font-page-title);line-height:1.65;font-weight:550;max-width:none;color:var(--ink,#263c5a)}
|
||||
.analysis-conclusion-layout>.analysis-conclusion-lead strong{font-weight:750;color:var(--blue,#4265c8);white-space:nowrap}
|
||||
.analysis-narrative .analysis-conclusion-layout>:is(h1,h2,h3,h4,h5,h6){margin:28px 0 12px;font-size:17px;line-height:1.55;font-weight:650;color:var(--ink,#263c5a)}
|
||||
.analysis-narrative .analysis-conclusion-layout>.analysis-conclusion-points{display:grid;gap:8px;max-width:76ch;margin:12px 0 18px;padding-left:20px;list-style:disc}
|
||||
.analysis-conclusion-layout>.analysis-conclusion-points>li{margin:0;padding-left:4px;line-height:1.75;text-wrap:pretty}
|
||||
.analysis-conclusion-layout>.analysis-conclusion-points>li::marker{color:var(--muted-ink,#738198);font-size:.8em}
|
||||
.analysis-narrative .analysis-conclusion-layout>.ai-markdown-table-wrap{margin:12px 0 10px}
|
||||
.analysis-narrative .analysis-conclusion-layout>.analysis-conclusion-context{margin:8px 0 18px;max-width:none;color:var(--muted-ink,#65748b);font-size:var(--font-body);line-height:1.65}
|
||||
.q-report .analysis-conclusion-layout>.analysis-conclusion-lead{font-size:21px}
|
||||
@media(max-width:640px){.analysis-narrative .analysis-conclusion-layout>.analysis-conclusion-lead{font-size:var(--font-page-title);padding-left:12px}.analysis-narrative .analysis-conclusion-layout>:is(h1,h2,h3,h4,h5,h6){font-size:var(--font-dialog-title);margin-top:24px}.analysis-conclusion-layout table{min-width:620px}}
|
||||
|
||||
.analysis-conclusion-section{min-width:0;padding:26px 0;border-bottom:1px solid var(--line,#dfe5ef);scroll-margin-top:24px}
|
||||
.analysis-conclusion-section:first-child{padding-top:0}
|
||||
.analysis-conclusion-section:last-child{border-bottom:0;padding-bottom:0}
|
||||
.analysis-conclusion-title{margin:0 0 16px;color:var(--ink,#263c5a);font-size:var(--font-page-title);line-height:1.5;font-weight:650;text-wrap:pretty}
|
||||
.analysis-conclusion-section>.analysis-conclusion-context{margin:10px 0 14px;color:var(--muted-ink,#65748b);font-size:var(--font-body);line-height:1.7}
|
||||
.analysis-conclusion-section>.analysis-conclusion-layout>p:first-child{margin-top:0}
|
||||
.analysis-conclusion-section>.analysis-conclusion-layout>p:last-child{margin-bottom:0}
|
||||
.analysis-comparison{margin:0 0 18px;padding:20px 24px;background:var(--surface-subtle,#f4f7fb);border-radius:6px;font-variant-numeric:tabular-nums}
|
||||
.analysis-comparison-name{font-size:var(--font-body);font-weight:600;color:var(--muted-ink,#65748b);margin-bottom:16px}
|
||||
.analysis-comparison-values{display:flex;align-items:center;gap:22px;flex-wrap:wrap}
|
||||
.analysis-comparison-values>div{display:flex;flex-direction:column;gap:6px}
|
||||
.analysis-comparison-values>div>span{font-size:var(--font-control);color:var(--muted-ink,#65748b)}
|
||||
.analysis-comparison-values strong{font-size:30px;line-height:1.35;white-space:nowrap}
|
||||
.analysis-comparison-previous strong{font-size:25px;color:var(--muted-ink,#65748b);font-weight:550}
|
||||
.analysis-comparison-current strong{font-weight:750;color:var(--ink,#263c5a)}
|
||||
.analysis-comparison-arrow{font-size:22px;color:var(--muted-ink,#65748b);align-self:flex-end;padding-bottom:6px}
|
||||
.analysis-comparison-values>.analysis-comparison-change{margin-left:auto;text-align:right;align-self:flex-end}
|
||||
.analysis-comparison-change strong{font-size:21px;font-weight:650}
|
||||
.analysis-comparison-change.is-worse strong{color:var(--danger,#c64446)}
|
||||
.analysis-comparison-change.is-better strong{color:var(--success,#008f7d)}
|
||||
.q-report .analysis-conclusion-title{font-size:var(--font-page-title);margin:0 0 16px}
|
||||
.q-report .analysis-conclusion-document{padding-top:28px}
|
||||
@media(max-width:640px){.analysis-conclusion-section{padding:22px 0}.analysis-conclusion-title{font-size:var(--font-page-title)}.analysis-comparison{padding:16px}.analysis-comparison-values{gap:12px}.analysis-comparison-values strong{font-size:27px}.analysis-comparison-previous strong{font-size:23px}.analysis-comparison-change strong{font-size:var(--font-page-title)}.analysis-comparison-values>.analysis-comparison-change{flex-basis:100%;margin:6px 0 0;padding-top:12px;border-top:1px solid var(--line,#dfe5ef);flex-direction:row;gap:6px;align-items:baseline}.analysis-comparison-arrow{font-size:var(--font-page-title)}}
|
||||
@media print{.analysis-comparison{break-inside:avoid}.analysis-conclusion-title{break-after:avoid}.analysis-conclusion-section{break-inside:auto}}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
.analysis-product-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 12px;
|
||||
margin-top: 5px;
|
||||
}
|
||||
.analysis-product-actions .ant-btn {
|
||||
height: auto;
|
||||
padding: 0;
|
||||
font-size: var(--font-control);
|
||||
font-weight: 400;
|
||||
line-height: 1.7;
|
||||
}
|
||||
.analysis-product-unavailable {
|
||||
display: block;
|
||||
margin-top: 5px;
|
||||
color: var(--muted-ink);
|
||||
font-size: var(--font-control);
|
||||
font-weight: 400;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.analysis-product-drawer .ant-drawer-title { overflow-wrap: anywhere; }
|
||||
.analysis-product-controls { display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 20px; }
|
||||
.analysis-product-controls .ant-segmented { max-width: 100%; }
|
||||
.analysis-product-context { color: var(--muted-ink); line-height: 1.7; margin: 0 0 16px; }
|
||||
.analysis-product-loading { min-height: 240px; display: flex; justify-content: center; align-items: center; gap: 10px; color: var(--muted-ink); }
|
||||
.analysis-product-source-row summary { color: var(--blue); cursor: pointer; }
|
||||
.analysis-product-source-row dl { max-height: 360px; overflow: auto; margin: 10px 0 0; min-width: 250px; }
|
||||
.analysis-product-source-row dl > div { display: grid; grid-template-columns: minmax(90px, 1fr) minmax(90px, 1fr); gap: 12px; padding: 5px 0; border-bottom: 1px solid var(--line); }
|
||||
.analysis-product-source-row dt, .analysis-product-source-row dd { margin: 0; overflow-wrap: anywhere; }
|
||||
.analysis-product-source-row dt { color: var(--muted-ink); }
|
||||
@@ -0,0 +1,9 @@
|
||||
.analysis-report-options{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:0 0 16px}
|
||||
.analysis-report-options .ant-segmented{max-width:100%}
|
||||
.analysis-report-export-status{margin:8px 0 12px;color:var(--muted-ink,#738197);font-size:13px}
|
||||
.analysis-report-export-error{margin-bottom:12px}
|
||||
.q-report .analysis-focus-table-wrap{overflow:visible}
|
||||
.q-report[data-report-mode="summary"] .analysis-narrative-section{padding:20px 0}
|
||||
.q-report[data-report-mode="summary"] .analysis-focus-details>summary{cursor:default}
|
||||
.q-report[data-report-mode="summary"] .analysis-focus-details>summary::marker{content:""}
|
||||
@media(max-width:600px){.analysis-report-options{align-items:stretch;flex-direction:column}.analysis-report-options .ant-segmented{width:100%}}
|
||||
@@ -22,6 +22,7 @@
|
||||
.analysis-visual-placeholder,.analysis-visual-chart-error{display:flex;align-items:center;justify-content:center;min-height:86px;padding:12px;color:var(--muted-ink,#728198);font-size:12px;text-align:center}
|
||||
.analysis-visual-placeholder{position:absolute;inset:0;pointer-events:none}
|
||||
.analysis-visual-chart-error{border:1px dashed var(--line,#dfe5ef);border-radius:6px;background:var(--surface-subtle,#f8fafd)}
|
||||
.analysis-visual-chart-wrap>.analysis-visual-chart-error{position:absolute;inset:0;z-index:1;flex-direction:column;gap:10px}
|
||||
.analysis-visual-summary{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
|
||||
.analysis-visual-table{min-width:0;max-width:100%;margin-top:10px;overflow:hidden;border-radius:6px;color:var(--ink,#263c5a)}
|
||||
.analysis-visual-table .ant-table{color:var(--ink,#263c5a);font-size:12px}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
type Row = Record<string, unknown>;
|
||||
const object = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||
const text = (value: unknown, maximum = 1000): string => typeof value === 'string' ? value.trim().slice(0, maximum) : '';
|
||||
|
||||
export interface ClarificationOption { label: string; value: string; description?: string }
|
||||
export interface ClarificationRequest { question: string; options: ClarificationOption[]; allowCustom: boolean }
|
||||
|
||||
/** Only saved clarification payloads supply choices; answer prose is never parsed into options. */
|
||||
export function analysisClarificationRequest(turn: Row): ClarificationRequest | null {
|
||||
const result = object(turn.result);
|
||||
if (String(turn.status || result.status || '').toUpperCase() !== 'NEEDS_CLARIFICATION') return null;
|
||||
const plan = object(turn.plan);
|
||||
const task = object(result.agentTask || turn.agentTask || plan.task || plan.agentTask);
|
||||
const request = object(result.clarificationRequest || turn.clarificationRequest || task.clarificationRequest);
|
||||
const resolution = object(task.productResolution || result.productResolution || turn.productResolution);
|
||||
const match = object(resolution.productMatch);
|
||||
const candidates = Array.isArray(request.options) ? request.options
|
||||
: match.status === 'ambiguous' && Array.isArray(match.candidates) ? match.candidates : [];
|
||||
const seen = new Set<string>();
|
||||
const options = candidates.slice(0, 20).flatMap(candidate => {
|
||||
const item = typeof candidate === 'string' ? { label: candidate, value: candidate } : object(candidate);
|
||||
const value = typeof (item.value || item.name || item.label) === 'string' ? String(item.value || item.name || item.label).trim() : '';
|
||||
const label = text(item.label || item.name || item.value, 300);
|
||||
if (!value || value.length > 300 || !label || seen.has(value)) return [];
|
||||
seen.add(value);
|
||||
const description = text(item.description, 500);
|
||||
return [{ value, label, ...(description ? { description } : {}) }];
|
||||
});
|
||||
const question = text(request.question || task.clarification || result.answer || turn.answer) || '请补充本轮分析需要的信息。';
|
||||
return { question, options, allowCustom: request.allowCustom !== false || !options.length };
|
||||
}
|
||||
|
||||
/** A continuation stays in the existing session and does not restate or replace its business goal. */
|
||||
export function clarificationContinuation(request: ClarificationRequest, selected: string, supplement: string): string | null {
|
||||
const choice = request.options.find(option => option.value === selected);
|
||||
const custom = request.allowCustom ? supplement.trim().slice(0, 1200) : '';
|
||||
if (!choice && !custom) return null;
|
||||
return ['继续上一轮分析,保留未修改的原目标和条件。',
|
||||
...(choice ? [`我的选择:${choice.value}`] : []),
|
||||
...(custom ? [`补充说明:${custom}`] : []),
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/** Reloading a waiting conversation restores only its newest unanswered clarification. */
|
||||
export function pendingClarificationTurnId(turns: Row[]): string {
|
||||
const latest = turns.at(-1);
|
||||
return latest && analysisClarificationRequest(latest) && typeof latest.id === 'string' ? latest.id : '';
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { conclusionMarkdown, conclusionDisplayText, type AnalysisReadingSummary } from './analysisReadingModel.ts';
|
||||
import { analysisTextEvidenceRefs } from './analysisEvidenceRefs.ts';
|
||||
import type { AnalysisVisual } from './analysisVisualsModel.ts';
|
||||
|
||||
export interface ConclusionComparison {
|
||||
metric: string; previousLabel: string; currentLabel: string;
|
||||
previous: string; current: string; direction: string; change: string; unit: string;
|
||||
original: string;
|
||||
}
|
||||
export interface ConclusionSection {
|
||||
id: string; title: string; markdown: string; note: string; visuals: AnalysisVisual[];
|
||||
}
|
||||
|
||||
/** Read only an explicit, checked comparison sentence. No KPI or difference is calculated. */
|
||||
export function checkedConclusionComparison(sentence: string): ConclusionComparison | null {
|
||||
const value = sentence.replace(/\*\*/g, '').trim();
|
||||
const match = value.match(/^([^。;\n]{1,50}?)(综合合格率|黑片合格率|亮片合格率|合格率)(?:为|是|[::])?\s*(\d+(?:\.\d+)?%)\s*[,,]\s*(?:较|相比|对比|比)\s*([^,,。;\n]{1,30}?)的?\s*(\d+(?:\.\d+)?%)\s*(下降|上升|提高|降低)\s*(\d+(?:\.\d+)?)(个百分点|pp)[。.]?$/);
|
||||
if (!match || [match[3], match[5]].some(rate => Number.parseFloat(rate) > 100)) return null;
|
||||
return { metric: match[2], currentLabel: match[1], current: match[3], previousLabel: match[4].replace(/的$/, ''), previous: match[5], direction: match[6], change: match[7], unit: match[8], original: value };
|
||||
}
|
||||
|
||||
function topicMatches(title: string, visual: AnalysisVisual): boolean {
|
||||
if (/黑片/.test(title) && !/亮片/.test(title) && visual.stage === 'bright'
|
||||
|| /亮片/.test(title) && !/黑片/.test(title) && visual.stage === 'black') return false;
|
||||
if (visual.dimension === 'product') return /产品|规格/.test(title);
|
||||
if (visual.dimension === 'department') return /产业部|部门/.test(title);
|
||||
if (visual.dimension === 'group') return /业务分组|分组|区域/.test(title);
|
||||
if (visual.dimension === 'defect' || visual.metric.startsWith('source_defect')) return /缺陷|源字段|缺角|磕边|隐裂/.test(title);
|
||||
if (visual.sectionKey?.startsWith('category')) return /报废大类|报废类别|正式报废/.test(title);
|
||||
if (visual.type === 'waterfall' || visual.metric === 'composite_impact_pp') return /结论|总体|阶段/.test(title);
|
||||
if (visual.type === 'line' || visual.type === 'area') return /趋势|逐月|期间/.test(title);
|
||||
return /结论|总体|阶段/.test(title) && /^(?:composite|black|bright)_rate$/.test(visual.metric);
|
||||
}
|
||||
|
||||
/** Chapters preserve the model's checked words/order; figures must also share its actual reference. */
|
||||
export function buildConclusionDocument(reading: AnalysisReadingSummary, visuals: AnalysisVisual[]) {
|
||||
const raw = conclusionMarkdown(reading, true);
|
||||
const chunks: Array<{ title: string; lines: string[]; note: string }> = [{ title: '核心结论', lines: [], note: '' }];
|
||||
const lines = raw.split('\n');
|
||||
let fenced = false;
|
||||
for (let index = 0; index < lines.length; index += 1) {
|
||||
const line = lines[index];
|
||||
if (/^\s*```/.test(line)) { fenced = !fenced; chunks.at(-1)!.lines.push(line); continue; }
|
||||
const heading = !fenced ? line.match(/^#{1,6}\s+(.+?)\s*#*\s*$/) : null;
|
||||
const bold = !fenced ? line.match(/^\*\*([^*\n]{1,45})\*\*\s*(?:([((][^\n]*[))])\s*[::]?\s*$|[::]\s*([^\n]*)$|$)/) : null;
|
||||
// These are explicit topic introductions in saved prose, not inferred causes.
|
||||
const topic = !fenced ? line.match(/^(报废重量方面|黑片报废大类中|亮片报废大类中)[,,]\s*(.+)$/) : null;
|
||||
if (heading || bold && /[\p{L}]/u.test(bold[1]) || topic) {
|
||||
const category = topic && /报废大类中$/.test(topic[1]);
|
||||
const title = heading?.[1] || bold?.[1] || (category ? '报废类别变化' : topic![1].replace(/方面$/, ''));
|
||||
chunks.push({ title, lines: bold?.[3] ? [bold[3]] : topic ? [category ? line : topic[2]] : [], note: bold?.[2] || '' });
|
||||
} else chunks.at(-1)!.lines.push(line);
|
||||
}
|
||||
const clean = (value: string) => conclusionDisplayText(value, reading.evidenceRefs);
|
||||
const sections = chunks.filter(chunk => chunk.lines.join('').trim() || chunk.note).map((chunk, index) => {
|
||||
const cited = chunk.lines.join('\n').trim();
|
||||
return { id: `conclusion-${index + 1}`, title: clean(chunk.title), markdown: clean(cited), note: clean(chunk.note), visuals: [] as AnalysisVisual[], refs: analysisTextEvidenceRefs(cited) };
|
||||
});
|
||||
// The card replaces exactly one explicit comparison sentence. Other words,
|
||||
// such as scope, mechanisms and limitations, remain in their original section.
|
||||
const first = sections[0];
|
||||
const sentence = first?.markdown.match(/^[^\n]*?[。](?:\s*|$)/)?.[0].trim();
|
||||
const comparison = sentence ? checkedConclusionComparison(sentence) : null;
|
||||
if (comparison) first.markdown = first.markdown.slice(sentence!.length).trimStart();
|
||||
|
||||
for (const visual of visuals) {
|
||||
const candidates = sections.filter(section => topicMatches(section.title, visual) && visual.evidenceRefs.some(ref => section.refs.includes(ref)));
|
||||
if (candidates.length === 1) candidates[0].visuals.push(visual);
|
||||
else sections.push({ id: `conclusion-chart-${sections.length + 1}`, title: visual.title, markdown: '', note: '', visuals: [visual], refs: [] });
|
||||
}
|
||||
return { comparison, sections: sections.map(({ refs: _refs, ...section }) => section) as ConclusionSection[] };
|
||||
}
|
||||
@@ -77,9 +77,13 @@ export function compactAnalysisTimeline(entries: Record<string, unknown>[]): Rec
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function analysisScrollFollows(previousTop: number, currentTop: number, distanceFromBottom: number, following: boolean): boolean {
|
||||
if (currentTop < previousTop - 0.1) return false;
|
||||
return distanceFromBottom <= 24 ? true : following;
|
||||
export type AnalysisScrollIntent = 'up' | 'down' | null;
|
||||
|
||||
/** Only explicit user movement changes follow state; layout-driven scroll events preserve it. */
|
||||
export function analysisScrollFollows(distanceFromBottom: number, following: boolean, intent: AnalysisScrollIntent = null): boolean {
|
||||
if (intent === 'up') return false;
|
||||
if (intent === 'down' && distanceFromBottom <= 24) return true;
|
||||
return following;
|
||||
}
|
||||
|
||||
export function partialAnalysisNotice(reason: unknown): string {
|
||||
|
||||
@@ -81,6 +81,7 @@ export function sanitizeAnalysisDisplayText(value: string): string {
|
||||
// Clean only punctuation made redundant by a removed metadata field. Do not trim leading colons:
|
||||
// HTML commonly stores a bold label and its business value in separate text nodes.
|
||||
return cleaned
|
||||
.replace(/数学/g, '')
|
||||
.replace(/[((]\s*[`*_~,,;;::/|\-–—\s]*[))]/g, '')
|
||||
.replace(/[,,;;::]{2,}/g, marks => marks.includes(':') || marks.includes(':') ? ':' : ';')
|
||||
.replace(/([。!?!?])\1+/g, '$1')
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/** Query IDs retain their reserved Q namespace; history facts keep their server IDs. */
|
||||
export const isQueryEvidenceRef = (value: unknown): value is string => typeof value === 'string' && /^Q[A-F0-9]{8}$/.test(value);
|
||||
export const isHistoryEvidenceRef = (value: unknown): value is string => typeof value === 'string'
|
||||
&& !value.startsWith('Q') && /^[A-Za-z0-9][A-Za-z0-9:._/-]{0,199}$/.test(value);
|
||||
export const isAnalysisEvidenceRef = (value: unknown): value is string => isQueryEvidenceRef(value) || isHistoryEvidenceRef(value);
|
||||
|
||||
/** History citations are bracketed opaque IDs. Ordinary bare prose never becomes a fact reference. */
|
||||
export function analysisTextEvidenceRefs(value: string): string[] {
|
||||
const queries = value.match(/\bQ[A-F0-9]{8}\b/g) || [];
|
||||
const history = [...value.matchAll(/\[([^\]\r\n]{1,200})\]/g)].map(match => match[1]).filter(isHistoryEvidenceRef);
|
||||
return [...new Set([...queries, ...history])];
|
||||
}
|
||||
|
||||
export function analysisEvidenceParts(value: string): Array<{ text: string; ref?: string }> {
|
||||
return value.split(/(\[[^\]\r\n]{1,200}\]|\bQ[A-F0-9]{8}\b)/g).map(text => {
|
||||
const candidate = text.startsWith('[') && text.endsWith(']') ? text.slice(1, -1) : text;
|
||||
return { text, ...(isQueryEvidenceRef(candidate) || text.startsWith('[') && isHistoryEvidenceRef(candidate) ? { ref: candidate } : {}) };
|
||||
});
|
||||
}
|
||||
|
||||
/** Historical native citations must resolve to actual server-rendered fact anchors. */
|
||||
export function nativeReadingEvidenceTargets(doc: Pick<Document, 'querySelectorAll' | 'getElementById'>, refs: string[]): Record<string, string> {
|
||||
const targets: Record<string, string> = {};
|
||||
const facts = [...doc.querySelectorAll('[data-history-fact-id]')];
|
||||
const ids = [...doc.querySelectorAll('[id]')];
|
||||
for (const ref of refs) {
|
||||
if (isQueryEvidenceRef(ref)) { targets[ref] = '#platform-evidence-' + ref; continue; }
|
||||
const matches = facts.filter(element => element.getAttribute('data-history-fact-id') === ref && element.id);
|
||||
if (matches.length !== 1) continue;
|
||||
const element = matches[0];
|
||||
if (doc.getElementById(element.id) !== element || ids.filter(item => item.id === element.id).length !== 1) continue;
|
||||
targets[ref] = '#' + encodeURIComponent(element.id);
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { analysisPeriodLabel, parseAnalysisPeriod } from './analysisPeriodModel.ts';
|
||||
import { sanitizeAnalysisDisplayText } from './analysisDisplayText.ts';
|
||||
|
||||
export type AnalysisMemberStage = 'black' | 'bright';
|
||||
|
||||
export type AnalysisMemberList = {
|
||||
schemaVersion: 1;
|
||||
releaseId: string;
|
||||
period: { year: number; month?: number; quarter?: number; monthStart?: number; monthEnd?: number };
|
||||
fields: { key: string; label: string }[];
|
||||
rows: { values: Record<string, string | null>; stages: AnalysisMemberStage[] }[];
|
||||
totalCount: number;
|
||||
rowsReturned: number;
|
||||
queryComplete: boolean;
|
||||
};
|
||||
|
||||
export type MemberListReadState<T> = { data: T | null; error: string };
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
||||
|
||||
function count(value: unknown): value is number {
|
||||
return Number.isSafeInteger(value) && Number(value) >= 0;
|
||||
}
|
||||
|
||||
/** Reject malformed snapshot data before it reaches the table. Values stay plain strings. */
|
||||
export function parseAnalysisMemberList(value: unknown): AnalysisMemberList | null {
|
||||
if (!isRecord(value) || value.schemaVersion !== 1 || typeof value.releaseId !== 'string' || !value.releaseId.trim()) return null;
|
||||
if (!isRecord(value.period)) return null;
|
||||
const period = parseAnalysisPeriod(value.period, 1900, 2100);
|
||||
if (!period?.year) return null;
|
||||
if (!Array.isArray(value.fields) || value.fields.length < 1 || value.fields.length > 5 || !Array.isArray(value.rows) || value.rows.length > 4000 ||
|
||||
!count(value.totalCount) || !count(value.rowsReturned) || value.rowsReturned > 4000 || value.rowsReturned > value.totalCount ||
|
||||
value.rows.length !== value.rowsReturned || typeof value.queryComplete !== 'boolean' ||
|
||||
value.queryComplete && value.rowsReturned !== value.totalCount) return null;
|
||||
|
||||
const fields: AnalysisMemberList['fields'] = [];
|
||||
const fieldKeys = new Set<string>();
|
||||
for (const field of value.fields) {
|
||||
if (!isRecord(field) || typeof field.key !== 'string' || !field.key.trim() || typeof field.label !== 'string' || !field.label.trim() || fieldKeys.has(field.key)) return null;
|
||||
fieldKeys.add(field.key);
|
||||
fields.push({ key: field.key, label: field.label });
|
||||
}
|
||||
|
||||
const rows: AnalysisMemberList['rows'] = [];
|
||||
for (const row of value.rows) {
|
||||
if (!isRecord(row) || !isRecord(row.values) || !Array.isArray(row.stages) || !row.stages.length || new Set(row.stages).size !== row.stages.length) return null;
|
||||
const valueKeys = Object.keys(row.values);
|
||||
if (valueKeys.length !== fieldKeys.size || valueKeys.some(key => !fieldKeys.has(key))) return null;
|
||||
const values = Object.create(null) as Record<string, string | null>;
|
||||
for (const [key, cell] of Object.entries(row.values)) {
|
||||
if (cell !== null && typeof cell !== 'string') return null;
|
||||
values[key] = cell;
|
||||
}
|
||||
if (!row.stages.every(stage => stage === 'black' || stage === 'bright')) return null;
|
||||
rows.push({ values, stages: [...new Set(row.stages)] as AnalysisMemberStage[] });
|
||||
}
|
||||
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
releaseId: value.releaseId,
|
||||
period: period as AnalysisMemberList['period'],
|
||||
fields,
|
||||
rows,
|
||||
totalCount: value.totalCount,
|
||||
rowsReturned: value.rowsReturned,
|
||||
queryComplete: value.queryComplete,
|
||||
};
|
||||
}
|
||||
|
||||
export function analysisMemberListPeriod(period: AnalysisMemberList['period']): string {
|
||||
return analysisPeriodLabel(period, 1900, 2100);
|
||||
}
|
||||
|
||||
export function analysisMemberListFullyRead(list: AnalysisMemberList): boolean {
|
||||
return list.queryComplete && list.rowsReturned >= list.totalCount;
|
||||
}
|
||||
|
||||
export function analysisMemberListPage(list: AnalysisMemberList, page: number, pageSize: number) {
|
||||
const size = Math.max(1, Math.trunc(pageSize));
|
||||
const pageCount = Math.max(1, Math.ceil(list.rowsReturned / size));
|
||||
const currentPage = Math.min(Math.max(1, Math.trunc(page)), pageCount);
|
||||
const offset = (currentPage - 1) * size;
|
||||
return { page: currentPage, pageSize: size, offset, pageCount, rows: list.rows.slice(offset, offset + size) };
|
||||
}
|
||||
|
||||
/** A failed current snapshot authorization always returns an empty data slot. */
|
||||
export async function authorizedMemberListRead<T>(
|
||||
data: T,
|
||||
authorize: () => Promise<unknown>,
|
||||
onUnauthorized: (error: unknown) => boolean,
|
||||
): Promise<MemberListReadState<T>> {
|
||||
try {
|
||||
await authorize();
|
||||
return { data, error: '' };
|
||||
} catch (error) {
|
||||
const handled = onUnauthorized(error);
|
||||
const detail = error instanceof Error
|
||||
? sanitizeAnalysisDisplayText(error.message).replace(/\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b/gi, '[隐藏标识]').slice(0, 300)
|
||||
: '';
|
||||
return { data: null, error: handled ? '访问权限已更新,成员清单已清空。' : detail || '当前快照复核失败,成员清单已清空。' };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
export type ModelThinking = { id: string; model: string; phase: string; status: string; text: string; version: number; source: 'api'; streaming: boolean; truncated: boolean; recovering?: boolean; finishReason?: string; at?: string; startedAt?: string; finishedAt?: string };
|
||||
|
||||
/** Reveal only received text, catching up within 100ms without splitting a UTF-16 pair. */
|
||||
export function thinkingTextFrame(from: string, target: string, elapsedMs: number): string {
|
||||
if (!target.startsWith(from) || elapsedMs >= 100) return target;
|
||||
let end = from.length + Math.ceil((target.length - from.length) * Math.max(0, elapsedMs) / 100);
|
||||
if (end < target.length && end > 0 && /[\uD800-\uDBFF]/.test(target[end - 1])) end--;
|
||||
return target.slice(0, end);
|
||||
}
|
||||
const object = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
|
||||
export function mergeModelThinking(existing: unknown, update: unknown): ModelThinking[] {
|
||||
let rows: ModelThinking[] = Array.isArray(existing) ? existing.map(value => ({ ...object(value) }) as ModelThinking) : [];
|
||||
const next = object(update);
|
||||
if (typeof next.id !== 'string' || next.source !== 'api' || typeof next.version !== 'number') return rows;
|
||||
const prior = rows.find(row => row.id === next.id);
|
||||
if (prior && prior.version >= next.version) return rows;
|
||||
if (next.reset === true && !prior) rows = [];
|
||||
let text: string;
|
||||
let recovering = false;
|
||||
if (typeof next.text === 'string') text = next.text;
|
||||
else if (typeof next.delta === 'string' && !prior?.recovering && (prior?.version || 0) === next.baseVersion) text = (prior?.text || '') + next.delta;
|
||||
else { text = prior?.text || ''; recovering = true; }
|
||||
const row = { ...prior, ...next, text, recovering } as ModelThinking;
|
||||
const index = rows.findIndex(item => item.id === next.id);
|
||||
if (index < 0) rows.push(row); else rows[index] = row;
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function modelThinkingEntries(turn: Record<string, unknown>): ModelThinking[] {
|
||||
const plan = object(turn.plan || object(turn.result).plan);
|
||||
let rows: ModelThinking[] = [];
|
||||
for (const source of [plan.modelThinking, turn.modelThinking]) {
|
||||
if (Array.isArray(source)) for (const block of source) rows = mergeModelThinking(rows, block);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function thinkingStatus(entry: ModelThinking, running: boolean): string {
|
||||
if (entry.recovering) return '正在恢复完整文本…';
|
||||
if (entry.finishReason === 'length') return '达到模型输出上限,保留已返回文本';
|
||||
if (entry.status === 'interrupted' && !entry.text) return '调用已中断,未收到思考文本';
|
||||
if (entry.status === 'not_returned') return '接口未返回思考文本';
|
||||
if (entry.status === 'interrupted' || entry.status === 'running' && !running) return '已中断,保留已返回文本';
|
||||
if (entry.status === 'running') return entry.text ? '正在输出' : '等待接口返回…';
|
||||
return '已返回';
|
||||
}
|
||||
|
||||
|
||||
/** Merge only recorded provider text and recorded analysis events, ordered by their actual timestamps. */
|
||||
export function orderedAnalysisProcess(turn: Record<string, unknown>, timeline: Record<string, unknown>[]): Record<string, unknown>[] {
|
||||
const thoughts = modelThinkingEntries(turn).filter(entry => entry.text).map(entry => ({ ...entry, kind: 'thinking', key: `thinking:${entry.id}` }));
|
||||
const events = timeline.map((entry, index) => ({ ...entry, key: `event:${entry.sequence ?? index}` }));
|
||||
const rows: Record<string, unknown>[] = [...thoughts, ...events];
|
||||
const time = (entry: Record<string, unknown>) => {
|
||||
const stamp = Date.parse(String(entry.at || entry.startedAt || ''));
|
||||
return Number.isFinite(stamp) ? stamp : Number.NEGATIVE_INFINITY;
|
||||
};
|
||||
// Stable ordering preserves source order for old records without timestamps. Never invent historical times.
|
||||
return rows.sort((a, b) => { const left=time(a), right=time(b); return left === right ? 0 : left < right ? -1 : 1; });
|
||||
}
|
||||
|
||||
|
||||
/** Adjacent provider calls read as one uninterrupted thought, without extra phase/model headings. */
|
||||
export function groupAdjacentThinking(events: Record<string, unknown>[]): Record<string, unknown>[] {
|
||||
const grouped: Record<string, unknown>[] = [];
|
||||
for (const event of events) {
|
||||
const previous = grouped.at(-1);
|
||||
if (event.kind === 'thinking' && previous?.kind === 'thinking') {
|
||||
previous.text = `${String(previous.text || '')}\n\n${String(event.text || '')}`;
|
||||
previous.status = previous.status === 'running' || event.status === 'running' ? 'running' : event.status;
|
||||
previous.truncated = Boolean(previous.truncated || event.truncated);
|
||||
} else grouped.push({ ...event });
|
||||
}
|
||||
return grouped;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
export type AnalysisPeriod = {
|
||||
year?: number;
|
||||
month?: number;
|
||||
quarter?: number;
|
||||
monthStart?: number;
|
||||
monthEnd?: number;
|
||||
};
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
const record = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||
const present = (value: unknown) => value !== undefined && value !== null && value !== '';
|
||||
|
||||
/** Parse the numeric part of an analysis period without coercing strings. Other
|
||||
* legacy display fields (label/start/end) are intentionally left to callers. */
|
||||
export function parseAnalysisPeriod(value: unknown, minYear = 1900, maxYear = 2200): AnalysisPeriod | null {
|
||||
const raw = record(value);
|
||||
const year = raw.year, month = raw.month, quarter = raw.quarter;
|
||||
const monthStart = raw.monthStart, monthEnd = raw.monthEnd;
|
||||
const hasMonth = present(month), hasQuarter = present(quarter);
|
||||
const hasMonthStart = present(monthStart), hasMonthEnd = present(monthEnd);
|
||||
if (!present(raw.year) && (hasMonth || hasQuarter || hasMonthStart || hasMonthEnd)) return null;
|
||||
if (present(raw.year) && (!Number.isInteger(year) || Number(year) < minYear || Number(year) > maxYear)) return null;
|
||||
if (hasMonth && (!Number.isInteger(month) || Number(month) < 1 || Number(month) > 12)) return null;
|
||||
if (hasQuarter && (!Number.isInteger(quarter) || Number(quarter) < 1 || Number(quarter) > 4)) return null;
|
||||
if (hasMonthStart !== hasMonthEnd) return null;
|
||||
if (hasMonthStart && (!Number.isInteger(monthStart) || Number(monthStart) < 1 || Number(monthStart) > 12
|
||||
|| !Number.isInteger(monthEnd) || Number(monthEnd) < 1 || Number(monthEnd) > 12 || Number(monthStart) > Number(monthEnd))) return null;
|
||||
if ([hasMonth, hasQuarter, hasMonthStart].filter(Boolean).length > 1) return null;
|
||||
return {
|
||||
...(present(year) ? { year: Number(year) } : {}),
|
||||
...(hasMonth ? { month: Number(month) } : {}),
|
||||
...(hasQuarter ? { quarter: Number(quarter) } : {}),
|
||||
...(hasMonthStart ? { monthStart: Number(monthStart), monthEnd: Number(monthEnd) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function hasAnalysisPeriodFields(value: unknown): boolean {
|
||||
const raw = record(value);
|
||||
return ['year', 'month', 'quarter', 'monthStart', 'monthEnd'].some(key => present(raw[key]));
|
||||
}
|
||||
|
||||
export function isValidAnalysisPeriodContext(value: unknown, minYear = 1900, maxYear = 2200): boolean {
|
||||
return parseAnalysisPeriod(value, minYear, maxYear) !== null;
|
||||
}
|
||||
|
||||
export function analysisPeriodLabel(value: unknown, minYear = 1900, maxYear = 2200): string {
|
||||
const period = parseAnalysisPeriod(value, minYear, maxYear);
|
||||
if (!period?.year) return '';
|
||||
if (period.monthStart !== undefined && period.monthEnd !== undefined) {
|
||||
return period.monthStart === period.monthEnd
|
||||
? `${period.year}年${period.monthStart}月`
|
||||
: `${period.year}年${period.monthStart}—${period.monthEnd}月`;
|
||||
}
|
||||
if (period.month !== undefined) return `${period.year}年${period.month}月`;
|
||||
if (period.quarter !== undefined) return `${period.year}年第${period.quarter}季度`;
|
||||
return `${period.year}年`;
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { parseAnalysisVisuals } from './analysisVisualsModel.ts';
|
||||
import type { AnalysisVisual } from './analysisVisualsModel.ts';
|
||||
import type { FocusProductRow } from './analysisReportModel.ts';
|
||||
import type { MetricsResponse, QueryParams, Stage, TrendMetricRow } from './types.ts';
|
||||
import { analysisPeriodLabel, parseAnalysisPeriod } from './analysisPeriodModel.ts';
|
||||
|
||||
type Data = Record<string, unknown>;
|
||||
export type ProductDrilldownView = 'defects' | 'trend' | 'records';
|
||||
export type DrilldownPeriod = { year: number; month?: number; quarter?: number; monthStart?: number; monthEnd?: number };
|
||||
export interface ProductDrilldownBinding {
|
||||
turnId: string;
|
||||
product: string;
|
||||
stages: Stage[];
|
||||
query: QueryParams & { releaseId: string };
|
||||
periods: Array<{ key: 'current' | 'comparison'; label: string; period: DrilldownPeriod }>;
|
||||
evidenceRefs: string[];
|
||||
}
|
||||
export type ProductDrilldownResolution = { binding: ProductDrilldownBinding; reason?: never } | { binding?: never; reason: string };
|
||||
|
||||
const record = (value: unknown): Data => value && typeof value === 'object' && !Array.isArray(value) ? value as Data : {};
|
||||
const present = (value: unknown) => value !== undefined && value !== null && value !== '';
|
||||
const canonical = (value: unknown): string => JSON.stringify(value && typeof value === 'object'
|
||||
? Array.isArray(value) ? value.map(item => canonical(item)) : Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value);
|
||||
const dimensions = ['department', 'group', 'product', 'projectGroup'] as const;
|
||||
const scopeKeys = new Set(['year', 'month', 'quarter', 'monthStart', 'monthEnd', 'releaseId', ...dimensions, 'productSearch', 'includeUnassigned', 'extraFilters', 'exclusions', 'stage', 'view', 'trendGranularity']);
|
||||
const hasExclusions = (value: unknown) => present(value) && (typeof value !== 'object' || Array.isArray(value) || Object.keys(record(value)).length > 0);
|
||||
|
||||
function periodOf(value: unknown): DrilldownPeriod | null {
|
||||
const raw = record(value);
|
||||
if (Object.keys(raw).some(key => !['year', 'month', 'quarter', 'monthStart', 'monthEnd'].includes(key))) return null;
|
||||
const period = parseAnalysisPeriod(raw, 2000, 2100);
|
||||
return period?.year ? period as DrilldownPeriod : null;
|
||||
}
|
||||
export function drilldownPeriodLabel(period: DrilldownPeriod): string {
|
||||
return analysisPeriodLabel(period, 2000, 2100);
|
||||
}
|
||||
|
||||
function selection(value: unknown): string[] | null {
|
||||
if (Array.isArray(value)) return value.every(item => typeof item === 'string' && item.trim()) ? value as string[] : null;
|
||||
if (typeof value !== 'string' || !value.trim()) return null;
|
||||
if (value.startsWith('[')) { try { return selection(JSON.parse(value)); } catch { return null; } }
|
||||
if (value.startsWith('~qv1~')) {
|
||||
try {
|
||||
const encoded = value.slice(5).replaceAll('-', '+').replaceAll('_', '/');
|
||||
return selection(JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(encoded.padEnd(Math.ceil(encoded.length / 4) * 4, '=')), character => character.charCodeAt(0)))));
|
||||
} catch { return null; }
|
||||
}
|
||||
return [value];
|
||||
}
|
||||
function wireSelection(value: unknown): string | null {
|
||||
const values = selection(value);
|
||||
if (!values?.length) return null;
|
||||
if (values.length === 1) return values[0];
|
||||
let binary = '';
|
||||
new TextEncoder().encode(JSON.stringify(values)).forEach(byte => { binary += String.fromCharCode(byte); });
|
||||
return `~qv1~${btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/g, '')}`;
|
||||
}
|
||||
function sameValue(key: string, a: unknown, b: unknown): boolean {
|
||||
if (dimensions.includes(key as typeof dimensions[number])) return canonical(selection(a)) === canonical(selection(b));
|
||||
return canonical(a) === canonical(b);
|
||||
}
|
||||
|
||||
/** A row must have its own cited, server-bound product chart. Never infer a
|
||||
* period from prose or borrow the mutable session / query-page filters. */
|
||||
export function resolveProductDrilldown(turn: Data, row: FocusProductRow): ProductDrilldownResolution {
|
||||
const result = Object.keys(record(turn.result)).length ? record(turn.result) : turn;
|
||||
const plan = record(turn.plan || result.plan);
|
||||
const turnId = String(turn.id || turn.turnId || '');
|
||||
if (!turnId) return { reason: '本轮结果尚未保存,暂不能下钻。' };
|
||||
const visuals = parseAnalysisVisuals(result.visuals || turn.visuals).visuals.filter(visual => visual.originTurnId === turnId
|
||||
&& visual.dimension === 'product' && row.evidenceRefs.length === 1 && visual.evidenceRefs.includes(row.evidenceRefs[0])
|
||||
&& visual.categories.some(category => category.key === row.product && category.label === row.product));
|
||||
if (!visuals.length) return { reason: '本条依据未保存完整查询条件,暂不能下钻。' };
|
||||
const bindings = visuals.map(visual => ({ scope: visual.scope, period: visual.period, comparisonPeriod: visual.comparisonPeriod, stage: visual.stage }));
|
||||
if (new Set(bindings.map(canonical)).size !== 1) return { reason: '本条依据对应多个查询范围,暂不能下钻。' };
|
||||
const visual = visuals[0], scope = record(visual.scope);
|
||||
const current = periodOf(visual.period), comparison = visual.comparisonPeriod ? periodOf(visual.comparisonPeriod) : null;
|
||||
if (!current || (visual.comparisonPeriod && !comparison)) return { reason: '本条依据的期间不完整,暂不能下钻。' };
|
||||
if (Object.keys(scope).some(key => !scopeKeys.has(key))) return { reason: '本条依据含当前下钻不支持的筛选条件。' };
|
||||
const contexts = [record(plan.context), record(plan.frozenContext), record(result.context), record(turn.context)];
|
||||
if ([scope, ...contexts].some(context => hasExclusions(context.exclusions))) return { reason: '本轮含排除条件,现有查询入口无法完整沿用,暂不能下钻。' };
|
||||
const releases = [scope.releaseId, result.releaseId, turn.releaseId, plan.releaseId, ...contexts.map(context => context.releaseId)].filter(present);
|
||||
if (!releases.length || releases.some(value => typeof value !== 'string' || !value.trim()) || new Set(releases).size !== 1) return { reason: '本轮数据版本缺失或不一致,暂不能下钻。' };
|
||||
for (const key of ['year', 'month', 'quarter', 'monthStart', 'monthEnd']) if (present(scope[key]) && scope[key] !== current[key as keyof DrilldownPeriod]) return { reason: '本条依据的期间与筛选不一致,暂不能下钻。' };
|
||||
const stage = visual.stage || scope.stage || row.stage;
|
||||
if (!['black', 'bright', 'all', 'combined'].includes(String(stage)) || (row.stage && row.stage !== 'all' && row.stage !== stage)
|
||||
|| (visual.stage && present(scope.stage) && visual.stage !== scope.stage)) return { reason: '本条依据的阶段不明确,暂不能下钻。' };
|
||||
const merged = { ...scope, ...current, stage };
|
||||
for (const context of contexts) {
|
||||
for (const [key, value] of Object.entries(context)) {
|
||||
if (!present(value) || ['releaseId', 'view', 'resultRef', 'metricCode', 'trendGranularity'].includes(key)) continue;
|
||||
if (!scopeKeys.has(key)) return { reason: '本轮冻结条件无法完整沿用,暂不能下钻。' };
|
||||
if (key === 'exclusions' && !Object.keys(record(value)).length) continue;
|
||||
if (key === 'extraFilters' && !Object.keys(record(value)).length) continue;
|
||||
if (key === 'stage' && ['all', 'combined'].includes(String(value))) continue;
|
||||
if (!sameValue(key, value, merged[key as keyof typeof merged])) return { reason: '本条依据与本轮冻结条件不一致,暂不能下钻。' };
|
||||
}
|
||||
}
|
||||
const semantic = record(plan.semantic);
|
||||
if (semantic.compare === true && Object.keys(record(semantic.priorContext)).length) {
|
||||
const prior = record(semantic.priorContext);
|
||||
if (!comparison || ['year', 'month', 'quarter', 'monthStart', 'monthEnd'].some(key => present(prior[key]) && prior[key] !== comparison[key as keyof DrilldownPeriod])
|
||||
|| Object.entries(prior).some(([key, value]) => present(value) && !['year', 'month', 'quarter', 'monthStart', 'monthEnd', 'view', 'trendGranularity', 'resultRef', 'metricCode'].includes(key)
|
||||
&& !(key === 'exclusions' && !hasExclusions(value)) && !(key === 'extraFilters' && !Object.keys(record(value)).length)
|
||||
&& !sameValue(key, value, key === 'releaseId' ? releases[0] : merged[key as keyof typeof merged]))) return { reason: '比较期的冻结条件不同,暂不能沿用同一范围下钻。' };
|
||||
}
|
||||
if (present(scope.product) && !selection(scope.product)?.includes(row.product)) return { reason: '该产品不在本条依据的查询范围内。' };
|
||||
if (present(scope.productSearch) && (typeof scope.productSearch !== 'string' || !row.product.toLocaleLowerCase().includes(scope.productSearch.toLocaleLowerCase()))) return { reason: '该产品与本轮检索条件不一致。' };
|
||||
const query: ProductDrilldownBinding['query'] = { ...current, view: 'product', releaseId: String(releases[0]), product: row.product };
|
||||
for (const key of dimensions.filter(key => key !== 'product')) {
|
||||
if (!present(scope[key])) continue;
|
||||
const value = wireSelection(scope[key]);
|
||||
if (!value) return { reason: '本条依据的组织筛选不完整,暂不能下钻。' };
|
||||
query[key] = value;
|
||||
}
|
||||
if (present(scope.includeUnassigned) && typeof scope.includeUnassigned !== 'boolean') return { reason: '本轮未分类筛选无效,暂不能下钻。' };
|
||||
query.includeUnassigned = scope.includeUnassigned === true;
|
||||
if (typeof scope.productSearch === 'string') query.productSearch = scope.productSearch;
|
||||
if (present(scope.extraFilters)) {
|
||||
if (typeof scope.extraFilters !== 'object' || Array.isArray(scope.extraFilters) || Object.values(record(scope.extraFilters)).some(value => !Array.isArray(value) || value.some(item => typeof item !== 'string'))) return { reason: '本轮附加筛选无效,暂不能下钻。' };
|
||||
query.extraFilters = structuredClone(scope.extraFilters) as Record<string, string[]>;
|
||||
}
|
||||
return { binding: { turnId, product: row.product, stages: stage === 'black' || stage === 'bright' ? [stage] : ['black', 'bright'], query,
|
||||
periods: [{ key: 'current', label: drilldownPeriodLabel(current), period: current }, ...(comparison ? [{ key: 'comparison' as const, label: drilldownPeriodLabel(comparison), period: comparison }] : [])], evidenceRefs: [...row.evidenceRefs] } };
|
||||
}
|
||||
|
||||
export function productDrilldownQuery(binding: ProductDrilldownBinding, period: DrilldownPeriod): QueryParams & { releaseId: string } {
|
||||
const { month: _month, quarter: _quarter, monthStart: _monthStart, monthEnd: _monthEnd, ...query } = binding.query;
|
||||
return { ...structuredClone(query), ...period };
|
||||
}
|
||||
|
||||
/** Only dates inside the original periods can appear in this drawer. The
|
||||
* metrics API also supplies the whole year's trend, so slice it explicitly. */
|
||||
export function productTrendVisual(binding: ProductDrilldownBinding, snapshots: MetricsResponse[]): AnalysisVisual[] {
|
||||
const points = new Map<string, TrendMetricRow>();
|
||||
snapshots.forEach((snapshot, index) => {
|
||||
const period = binding.periods[index].period;
|
||||
if (snapshot.release?.id !== binding.query.releaseId) throw new Error('查询返回的数据版本已变化,请重新打开本轮分析。');
|
||||
if (period.month) {
|
||||
const key = `${period.year}-${String(period.month).padStart(2, '0')}`;
|
||||
points.set(key, { ...snapshot.summary, month: key, period: key });
|
||||
return;
|
||||
}
|
||||
snapshot.trend.forEach(row => {
|
||||
const raw = String(row.period ?? row.month);
|
||||
const match = raw.match(/^(\d{4})-(\d{1,2})$/);
|
||||
const year = match ? Number(match[1]) : row.year ?? period.year;
|
||||
const month = match ? Number(match[2]) : Number(row.month);
|
||||
if (year !== period.year || !Number.isInteger(month) || month < 1 || month > 12
|
||||
|| period.quarter && Math.ceil(month / 3) !== period.quarter
|
||||
|| period.monthStart !== undefined && (month < period.monthStart || month > Number(period.monthEnd))) return;
|
||||
points.set(`${year}-${String(month).padStart(2, '0')}`, row);
|
||||
});
|
||||
});
|
||||
const entries = [...points].sort(([a], [b]) => a.localeCompare(b));
|
||||
if (!entries.length) return [];
|
||||
const series = binding.stages.map(stage => ({ key: `${stage}_rate`, label: stage === 'black' ? '黑片合格率' : '亮片合格率', values: entries.map(([, row]) => row.coverage?.[stage === 'black' ? 'blackRows' : 'brightRows'] > 0 ? row[stage]?.rate ?? null : null) }));
|
||||
if (binding.stages.length === 2) series.unshift({ key: 'composite_rate', label: '综合合格率', values: entries.map(([, row]) => row.coverage?.blackRows > 0 && row.coverage?.brightRows > 0 ? row.compositeRate ?? null : null) });
|
||||
if (!series.some(item => item.values.some(value => value !== null))) return [];
|
||||
return parseAnalysisVisuals([{ id: `drill-trend-${binding.turnId}`, type: 'line', title: '合格率趋势', subtitle: '', unit: 'ratio',
|
||||
categories: entries.map(([key]) => ({ key, label: key })), series, evidenceRefs: [], requiredFields: [], scope: { product: binding.product }, period: binding.periods[0].period,
|
||||
metric: 'composite_rate', coverage: { totalRows: entries.length, returnedRows: entries.length, truncated: false }, originTurnId: binding.turnId }]).visuals;
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
import { buildAnalysisNarrative, type AnalysisNarrativeModel } from './analysisReportModel.ts';
|
||||
import { sanitizeAnalysisDisplayText } from './analysisDisplayText.ts';
|
||||
import { parseAnalysisVisuals, type AnalysisVisual } from './analysisVisualsModel.ts';
|
||||
import { parseAnalysisPeriod } from './analysisPeriodModel.ts';
|
||||
import { isAnalysisEvidenceRef, isQueryEvidenceRef, analysisTextEvidenceRefs, analysisEvidenceParts } from './analysisEvidenceRefs.ts';
|
||||
|
||||
/** The server owns the semantic selection; the frontend only validates and presents it. */
|
||||
export interface ServerAnalysisReadingSummary {
|
||||
version: 1;
|
||||
lead: string;
|
||||
evidence: string[];
|
||||
notices: string[];
|
||||
evidenceRefs: string[];
|
||||
visualIds?: string[];
|
||||
}
|
||||
export interface AnalysisReadingSummary {
|
||||
lead: string;
|
||||
evidence: string[];
|
||||
notices: string[];
|
||||
evidenceRefs: string[];
|
||||
hasAppendix: boolean;
|
||||
fullAnswer: string;
|
||||
visualCount: number;
|
||||
}
|
||||
type Row = Record<string, unknown>;
|
||||
const object = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||
const text = (value: unknown): value is string => typeof value === 'string' && !!value.trim() && value.length <= 20000 && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(value);
|
||||
const texts = (value: unknown): value is string[] => Array.isArray(value) && value.length <= 100 && value.every(text);
|
||||
|
||||
/** A nested durable result wins even when a stale flattened field still exists. */
|
||||
export function parseServerReadingSummary(turn: unknown): ServerAnalysisReadingSummary | null {
|
||||
const source = object(turn);
|
||||
const result = source.result && typeof source.result === 'object' && !Array.isArray(source.result) ? object(source.result) : source;
|
||||
const summary = object(result.readingSummary);
|
||||
if (Object.keys(summary).some(key => !['version', 'lead', 'evidence', 'notices', 'evidenceRefs', 'visualIds'].includes(key))
|
||||
|| summary.version !== 1 || !text(summary.lead) || !texts(summary.evidence) || !texts(summary.notices)
|
||||
|| !Array.isArray(summary.evidenceRefs) || summary.evidenceRefs.length > 100
|
||||
|| !summary.evidenceRefs.every(isAnalysisEvidenceRef)) return null;
|
||||
if (summary.visualIds !== undefined && (!Array.isArray(summary.visualIds) || summary.visualIds.length > 3
|
||||
|| summary.visualIds.some(id => typeof id !== 'string' || !id || id.length > 160))) return null;
|
||||
// An explicitly empty current evidence allowlist must never be filled from stale charts.
|
||||
const allowed = new Set<string>();
|
||||
if (Object.hasOwn(result, 'queryEvidenceRefs')) {
|
||||
if (!Array.isArray(result.queryEvidenceRefs) || !result.queryEvidenceRefs.every(isAnalysisEvidenceRef)) return null;
|
||||
result.queryEvidenceRefs.forEach(ref => allowed.add(ref));
|
||||
} else {
|
||||
for (const key of ['evidence', 'results']) if (Array.isArray(result[key])) for (const entry of result[key]) {
|
||||
const ref = object(entry).evidenceRef;
|
||||
if (isQueryEvidenceRef(ref)) allowed.add(ref);
|
||||
}
|
||||
for (const visual of parseAnalysisVisuals(result.visuals).visuals) for (const ref of visual.evidenceRefs) if (isQueryEvidenceRef(ref)) allowed.add(ref);
|
||||
}
|
||||
const declared = new Set(summary.evidenceRefs as string[]);
|
||||
if ([...declared].some(ref => !allowed.has(ref))
|
||||
|| [summary.lead, ...summary.evidence, ...summary.notices].flatMap(analysisTextEvidenceRefs).some(ref => !declared.has(ref))) return null;
|
||||
return { version: 1, lead: summary.lead, evidence: [...summary.evidence], notices: [...summary.notices], evidenceRefs: [...summary.evidenceRefs] as string[],
|
||||
...(summary.visualIds !== undefined ? { visualIds: [...summary.visualIds] as string[] } : {}) };
|
||||
}
|
||||
|
||||
/** Citations remain in the saved result and permission checks, not in the business answer. */
|
||||
export function conclusionDisplayText(value: string, refs: string[] = [], keepEvidence = false): string {
|
||||
const business = sanitizeAnalysisDisplayText(value).split('\n').filter(line => !/^(?:部分统计比较未通过核验,已保留对应正式数值。|部分无依据的贡献或增量表述已删除,其余已核验解释予以保留。)$/.test(line.trim())).join('\n');
|
||||
return keepEvidence ? business.trim() : analysisEvidenceParts(business).filter(part => !part.ref || !isQueryEvidenceRef(part.ref) && !refs.includes(part.ref)).map(part => part.text).join('').trim();
|
||||
}
|
||||
|
||||
export function conclusionMarkdown(reading: AnalysisReadingSummary, keepEvidence = false): string {
|
||||
// Preserve the checked business answer's original sections and tables. The old
|
||||
// summary split can separate a table from its heading, so it is not a renderer.
|
||||
let hiddenLevel = 0;
|
||||
const businessAnswer = reading.fullAnswer.split('\n').filter(line => {
|
||||
const heading = line.match(/^(#{1,6})\s+(.+?)\s*$/);
|
||||
if (heading) {
|
||||
if (hiddenLevel && heading[1].length <= hiddenLevel) hiddenLevel = 0;
|
||||
if (/^(完整统计依据|统计数据附录|数据明细|完整证据|历史事实依据)$/.test(heading[2])) hiddenLevel = heading[1].length;
|
||||
}
|
||||
return !hiddenLevel;
|
||||
}).join('\n').trim();
|
||||
const clean = (value: string) => conclusionDisplayText(value, reading.evidenceRefs, keepEvidence);
|
||||
const checkedBody = clean(businessAnswer);
|
||||
const selected = [reading.lead, ...reading.evidence].map(clean).filter(Boolean);
|
||||
const paragraphs = reading.hasAppendix ? selected.map(item => {
|
||||
// The model may put a selected comparison heading and its checked table in
|
||||
// separate blocks. Keep that table with the heading, without exposing other
|
||||
// detail paragraphs or replacing the model's semantic selection by position.
|
||||
if (item.includes('\n|')) return item;
|
||||
const start = checkedBody.indexOf(item);
|
||||
if (start < 0 || start !== checkedBody.lastIndexOf(item)) return item;
|
||||
const following = checkedBody.slice(start + item.length).trimStart();
|
||||
const table = following.match(/^(\|[^\n]*\|\s*\n\|[\s:|\-]+\|\s*\n(?:\|[^\n]*\|(?:\n|$))+)/)?.[1].trim();
|
||||
return table && !selected.some(other => other.includes(table)) ? item + '\n\n' + table : item;
|
||||
}) : [checkedBody];
|
||||
const body = [...new Set(paragraphs.map(clean).filter(Boolean))].join('\n\n');
|
||||
const notices = [...new Set(reading.notices.map(clean).filter(Boolean))].filter(notice => !body.includes(notice));
|
||||
return body + (notices.length ? '\n\n' + notices.join('\n\n') : '');
|
||||
}
|
||||
|
||||
/** Historical or invalid summaries keep all original prose visible, without positional extraction. */
|
||||
export function analysisReadingSummary(answer: string, model: AnalysisNarrativeModel, turn?: unknown): AnalysisReadingSummary {
|
||||
const summary = parseServerReadingSummary(turn);
|
||||
const source = object(turn), durable = Object.hasOwn(source, 'result') ? object(source.result) : source;
|
||||
return {
|
||||
lead: summary?.lead || '', evidence: summary?.evidence || [], notices: summary?.notices || [], evidenceRefs: summary?.evidenceRefs || [],
|
||||
hasAppendix: !!summary,
|
||||
fullAnswer: sanitizeAnalysisDisplayText(summary && typeof durable.answer === 'string' ? durable.answer : answer).trim(),
|
||||
visualCount: new Set(model.sections.flatMap(section => section.visuals.map(visual => visual.id))).size,
|
||||
};
|
||||
}
|
||||
|
||||
const stable = (value: unknown): string => {
|
||||
if (Array.isArray(value)) return JSON.stringify(value.map(stable).sort());
|
||||
if (value && typeof value === 'object') return JSON.stringify(Object.fromEntries(Object.entries(object(value)).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, stable(item)])));
|
||||
return JSON.stringify(value ?? null);
|
||||
};
|
||||
const selection = (value: unknown) => Array.isArray(value) ? value : value === undefined || value === null || value === '' ? [] : [value];
|
||||
const scopeFilters = ['department', 'group', 'product', 'projectGroup', 'productSearch', 'extraFilters', 'exclusions', 'columnFilters', 'columnLabels', 'includeUnassigned', 'category', 'defect'];
|
||||
const dimensionFilters = new Set(['department', 'group', 'product', 'projectGroup']);
|
||||
|
||||
/** The frozen server plan wins over flattened copies; never infer a request from answer text. */
|
||||
function readingTask(turn: Row, result: Row): Row {
|
||||
return [object(turn.plan).task, result.agentTask, turn.agentTask, turn.task, result.task].map(object).find(task => Object.keys(task).length > 0) || {};
|
||||
}
|
||||
function canonicalReadingPeriod(value: unknown): Row | null {
|
||||
const raw = object(value), numeric = parseAnalysisPeriod(raw);
|
||||
if (numeric?.year !== undefined) {
|
||||
const period = numeric.monthStart !== undefined && numeric.monthStart === numeric.monthEnd ? { year: numeric.year, month: numeric.monthStart } : numeric;
|
||||
if (raw.start !== undefined || raw.end !== undefined) {
|
||||
const descriptor = canonicalReadingPeriod({ start: raw.start, end: raw.end, granularity: raw.granularity });
|
||||
if (!descriptor || stable(descriptor) !== stable(period)) return null;
|
||||
}
|
||||
return period;
|
||||
}
|
||||
// A renderer may describe monthly chart bounds instead of repeating the numeric query frame.
|
||||
// Accept only exact machine-readable same-year bounds, never a display label or guessed dates.
|
||||
if (raw.granularity !== 'month' || typeof raw.start !== 'string' || typeof raw.end !== 'string'
|
||||
|| Object.keys(raw).some(key => !['start', 'end', 'granularity', 'label'].includes(key))) return null;
|
||||
const start = raw.start.match(/^(\d{4})-(0[1-9]|1[0-2])$/), end = raw.end.match(/^(\d{4})-(0[1-9]|1[0-2])$/);
|
||||
if (!start || !end || start[1] !== end[1] || Number(start[2]) > Number(end[2])) return null;
|
||||
const period = { year: Number(start[1]), monthStart: Number(start[2]), monthEnd: Number(end[2]) };
|
||||
if (!parseAnalysisPeriod(period)) return null;
|
||||
return period.monthStart === period.monthEnd ? { year: period.year, month: period.monthStart } : period;
|
||||
}
|
||||
function samePeriod(actual: unknown, expected: unknown): boolean {
|
||||
const period = canonicalReadingPeriod(expected), observed = canonicalReadingPeriod(actual);
|
||||
return !!period && !!observed && stable(observed) === stable(period);
|
||||
}
|
||||
function matchesFields(visual: AnalysisVisual, fields: unknown): boolean {
|
||||
if (!Array.isArray(fields) || !fields.length) return false;
|
||||
return fields.some(field => field === 'rate' ? /^(?:composite_rate|black_rate|bright_rate|rate_drop_pp|rate_change_pp)$/.test(visual.metric)
|
||||
: field === 'scrapRate' ? /^(?:black|bright)_scrap_rate$/.test(visual.metric)
|
||||
: field === 'totalWeight' ? /^(?:black|bright)_total_weight$/.test(visual.metric)
|
||||
: field === 'scrapWeight' && /^(?:current_scrap_weight|scrap_delta|source_defect_weight|source_defect_delta_weight|black_scrap_weight|bright_scrap_weight)$/.test(visual.metric));
|
||||
}
|
||||
function matchesTarget(visual: AnalysisVisual, task: Row, target: Row, filters: Row): boolean {
|
||||
if (Object.keys(filters).some(key => !scopeFilters.includes(key))
|
||||
|| Object.keys(visual.scope).some(key => ![...scopeFilters, 'year', 'month', 'quarter', 'monthStart', 'monthEnd', 'releaseId', 'stage', 'view', 'trendGranularity'].includes(key))) return false;
|
||||
if (!samePeriod(visual.period, task.period) || !samePeriod(visual.scope, task.period) || !matchesFields(visual, target.fields ?? task.fields)) return false;
|
||||
const comparison = target.comparisonRequired ?? task.comparisonRequired;
|
||||
if (comparison === true ? !samePeriod(visual.comparisonPeriod, task.comparisonPeriod) : !!visual.comparisonPeriod) return false;
|
||||
const visualType = target.visualType ?? task.visualType;
|
||||
if (visualType && visual.type !== visualType) return false;
|
||||
const purpose = String(target.purpose || (task.trendRequired === true ? 'trend' : ''));
|
||||
if (purpose === 'trend' && !['line', 'area', 'heatmap'].includes(visual.type)) return false;
|
||||
if (purpose !== 'trend' && !visualType && ['line', 'area', 'heatmap'].includes(visual.type)) return false;
|
||||
if (target.sort === 'rate_drop' && visual.metric !== 'rate_drop_pp'
|
||||
|| target.sort === 'current_rate' && !['composite_rate', 'black_rate', 'bright_rate'].includes(visual.metric)
|
||||
|| target.sort === 'scrap_delta' && !['scrap_delta', 'source_defect_delta_weight'].includes(visual.metric)
|
||||
|| target.sort === 'current_scrap' && !['current_scrap_weight', 'source_defect_weight', 'black_scrap_weight', 'bright_scrap_weight'].includes(visual.metric)) return false;
|
||||
if (typeof target.limit === 'number' && visual.categories.length > target.limit * (visual.sectionKey === 'defect_combined' ? 2 : 1)) return false;
|
||||
const dimension = target.dimension;
|
||||
if (typeof dimension === 'string' ? visual.dimension !== dimension
|
||||
: purpose === 'metrics' || purpose === 'trend' ? !!visual.dimension
|
||||
: Array.isArray(task.dimensions) && task.dimensions.length ? !task.dimensions.includes(visual.dimension) : !!visual.dimension) return false;
|
||||
const stages = selection(target.stages ?? task.stages);
|
||||
if (visual.stage ? !stages.includes(visual.stage)
|
||||
: visual.sectionKey === 'defect_combined' ? stable(stages) !== stable(['black', 'bright']) : stages.length > 0) return false;
|
||||
for (const key of scopeFilters) {
|
||||
const expected = filters[key], actual = visual.scope[key];
|
||||
if (key === 'includeUnassigned') { if ((actual === true) !== (expected === true)) return false; continue; }
|
||||
if (dimensionFilters.has(key)) { if (stable(selection(actual)) !== stable(selection(expected))) return false; }
|
||||
else if (stable(actual ?? (key === 'extraFilters' || key === 'exclusions' || key === 'columnLabels' ? {} : key === 'columnFilters' ? [] : ''))
|
||||
!== stable(expected ?? (key === 'extraFilters' || key === 'exclusions' || key === 'columnLabels' ? {} : key === 'columnFilters' ? [] : ''))) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Promote only explicit server chart targets with current, authorized evidence and an exact frame. */
|
||||
export function selectPrimaryAnalysisVisuals(model: AnalysisNarrativeModel, turn: unknown): AnalysisVisual[] {
|
||||
const source = object(turn), result = source.result && typeof source.result === 'object' && !Array.isArray(source.result) ? object(source.result) : source;
|
||||
const summary = parseServerReadingSummary(source);
|
||||
if (!summary) return [];
|
||||
const task = readingTask(source, result), nodes = Array.isArray(task.queryPlan) ? task.queryPlan.map(object) : [];
|
||||
const requiredNodes = nodes.filter(node => node.visualPreference === 'required');
|
||||
if (task.visualPreference === 'none' || task.visualPreference !== 'required' && !requiredNodes.length) return [];
|
||||
const refs = new Set(Array.isArray(result.queryEvidenceRefs) ? result.queryEvidenceRefs : summary.evidenceRefs);
|
||||
const turnId = String(source.id || source.turnId || '');
|
||||
if (!turnId) return [];
|
||||
const plan = object(source.plan);
|
||||
const releases = [result.releaseId, source.releaseId, plan.releaseId, object(plan.context).releaseId, task.releaseId].filter(value => value !== undefined && value !== null && value !== '');
|
||||
if (releases.some(value => typeof value !== 'string') || new Set(releases).size > 1) return [];
|
||||
const release = releases[0];
|
||||
const targets = nodes.length ? (requiredNodes.length ? requiredNodes : nodes.filter(node => node.visualPreference !== 'none')) : [task];
|
||||
const matches = (visual: AnalysisVisual) => targets.some(target => {
|
||||
if (['source', 'records'].includes(String(target.purpose || ''))) return false;
|
||||
const selector = object(target.selector), kind = selector.kind || 'base';
|
||||
const filters = { ...object(task.filters), ...(task.columnFilters ? { columnFilters: task.columnFilters } : {}), ...(task.columnLabels ? { columnLabels: task.columnLabels } : {}),
|
||||
...(target.category ?? task.category ? { category: target.category ?? task.category } : {}), ...(target.defect ?? task.defect ? { defect: target.defect ?? task.defect } : {}) };
|
||||
if (kind === 'base') return matchesTarget(visual, task, target, filters);
|
||||
if (kind === 'catalog_members' && typeof selector.dimension === 'string' && dimensionFilters.has(selector.dimension) && Array.isArray(selector.names)) {
|
||||
return selector.names.some(name => typeof name === 'string' && matchesTarget(visual, task, target, { ...filters, [String(selector.dimension)]: name }));
|
||||
}
|
||||
// Derived Top-N scopes require their server-resolved child frame; an unrelated chart is no substitute.
|
||||
return false;
|
||||
});
|
||||
return model.sections.flatMap(section => section.visuals).filter((visual, index, list) => list.findIndex(item => item.id === visual.id) === index
|
||||
&& visual.chartable && visual.originTurnId === turnId && visual.evidenceRefs.length > 0 && visual.evidenceRefs.every(ref => refs.has(ref))
|
||||
&& (!release || visual.scope.releaseId === release) && matches(visual));
|
||||
}
|
||||
|
||||
/** Show a few already-authorized business charts without requiring users to explicitly ask for a plot. */
|
||||
export function selectConclusionAnalysisVisuals(model: AnalysisNarrativeModel, turn: unknown): AnalysisVisual[] {
|
||||
const source = object(turn), result = Object.hasOwn(source, 'result') ? object(source.result) : source;
|
||||
const summary = parseServerReadingSummary(source);
|
||||
if (!summary) return [];
|
||||
const task = readingTask(source, result);
|
||||
if (task.visualPreference === 'none') return [];
|
||||
const required = selectPrimaryAnalysisVisuals(model, turn);
|
||||
if (required.length || task.visualPreference === 'required' || (Array.isArray(task.queryPlan) && task.queryPlan.some(node => object(node).visualPreference === 'required'))) return required;
|
||||
const refs = new Set(summary.evidenceRefs), filters = object(task.filters);
|
||||
const releases = [result.releaseId, source.releaseId, object(source.plan).releaseId, object(object(source.plan).context).releaseId].filter(Boolean);
|
||||
if (!Object.keys(task).length || new Set(releases).size > 1) return [];
|
||||
const release = releases[0], turnId = String(source.id || source.turnId || '');
|
||||
if (!release || Object.keys(filters).some(key => !scopeFilters.includes(key))) return [];
|
||||
const stages = selection(task.stages);
|
||||
const candidates = parseAnalysisVisuals(result.visuals).visuals.filter((visual, index, all) => all.findIndex(item => item.id === visual.id) === index
|
||||
&& visual.chartable && !!turnId && visual.originTurnId === turnId && visual.evidenceRefs.length > 0 && visual.evidenceRefs.every(ref => refs.has(ref))
|
||||
&& (!release || visual.scope.releaseId === release) && samePeriod(visual.period, task.period) && samePeriod(visual.scope, task.period)
|
||||
&& Object.keys(visual.scope).every(key => [...scopeFilters, 'year', 'month', 'quarter', 'monthStart', 'monthEnd', 'releaseId', 'stage', 'view', 'trendGranularity'].includes(key))
|
||||
&& (!stages.length || stages.includes(visual.stage))
|
||||
&& (visual.comparisonPeriod ? samePeriod(visual.comparisonPeriod, task.comparisonPeriod) : task.comparisonRequired !== true)
|
||||
&& Object.entries(filters).every(([key, value]) => key === 'includeUnassigned' ? (visual.scope[key] === true) === (value === true)
|
||||
: dimensionFilters.has(key) ? stable(selection(visual.scope[key])) === stable(selection(value)) : stable(visual.scope[key]) === stable(value)));
|
||||
if (summary.visualIds?.length) return summary.visualIds.map(id => candidates.find(visual => visual.id === id)).filter((visual): visual is AnalysisVisual => !!visual);
|
||||
const score = (visual: AnalysisVisual) => visual.metric === 'source_defect_delta_weight' ? 50
|
||||
: visual.metric === 'scrap_delta' && visual.dimension === 'product' ? 40
|
||||
: visual.type === 'waterfall' ? 60 : visual.dimension === 'department' ? 30 : visual.dimension === 'group' ? 20 : 10;
|
||||
const selected: AnalysisVisual[] = [];
|
||||
for (const visual of [...candidates].sort((a, b) => score(b) - score(a))) {
|
||||
if (selected.some(item => item.dimension === visual.dimension && item.metric === visual.metric && item.stage === visual.stage)) continue;
|
||||
selected.push(visual);
|
||||
if (selected.length === 3) break;
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
|
||||
/** Chat, HTML and PNG report views share this exact summary and evidence model. */
|
||||
export function buildAnalysisReadingModel(answer: string, visuals: unknown, question = '', turn?: unknown) {
|
||||
const summary = parseServerReadingSummary(turn);
|
||||
const model = buildAnalysisNarrative(answer, visuals, question, summary?.evidenceRefs);
|
||||
return { model, reading: analysisReadingSummary(answer, model, turn), primaryVisuals: selectConclusionAnalysisVisuals(model, turn) };
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import { analysisPeriodLabel, parseAnalysisPeriod } from './analysisPeriodModel.ts';
|
||||
import { sanitizeAnalysisDisplayText } from './analysisDisplayText.ts';
|
||||
|
||||
export type AnalysisRecordStage = 'black' | 'bright';
|
||||
export type AnalysisSourceRecord = {
|
||||
recordId: string | number;
|
||||
sourceRevisionId: string;
|
||||
buildId: string;
|
||||
sourceFile: string;
|
||||
sheet: string;
|
||||
rowNumber: number;
|
||||
product: string | null;
|
||||
group: string | null;
|
||||
values: Record<string, string | number | boolean | null>;
|
||||
};
|
||||
export type AnalysisSourceRecordSet = {
|
||||
id: string;
|
||||
nodeId: string;
|
||||
scopeId: string;
|
||||
label: string;
|
||||
stage: AnalysisRecordStage;
|
||||
period: { year: number; month?: number; quarter?: number; monthStart?: number; monthEnd?: number };
|
||||
filters: Record<string, unknown>;
|
||||
fields: string[];
|
||||
totalRows: number;
|
||||
loadedRows: number;
|
||||
complete: boolean;
|
||||
rows: AnalysisSourceRecord[];
|
||||
};
|
||||
export type AnalysisSourceRecordList = {
|
||||
schemaVersion: 1;
|
||||
kind: 'source_record_list';
|
||||
releaseId: string;
|
||||
queryComplete: boolean;
|
||||
totalRows: number;
|
||||
loadedRows: number;
|
||||
sets: AnalysisSourceRecordSet[];
|
||||
};
|
||||
|
||||
const MAX_ROWS = 4000;
|
||||
const MAX_BYTES = 4 * 1024 * 1024;
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
||||
&& (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
||||
const count = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;
|
||||
const nonEmptyString = (value: unknown): value is string => typeof value === 'string' && Boolean(value.trim());
|
||||
const hasExactKeys = (value: Record<string, unknown>, keys: string[]) => {
|
||||
const actual = Object.keys(value).sort();
|
||||
const expected = [...keys].sort();
|
||||
return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
|
||||
};
|
||||
|
||||
function validJsonValue(value: unknown, depth = 0): boolean {
|
||||
if (depth > 12) return false;
|
||||
if (value === null || typeof value === 'string' || typeof value === 'boolean') return true;
|
||||
if (typeof value === 'number') return Number.isFinite(value);
|
||||
if (Array.isArray(value)) return value.every(item => validJsonValue(item, depth + 1));
|
||||
if (!isRecord(value)) return false;
|
||||
return Object.entries(value).every(([key, item]) => typeof key === 'string' && validJsonValue(item, depth + 1));
|
||||
}
|
||||
|
||||
function sanitizeText(value: string): string {
|
||||
return sanitizeAnalysisDisplayText(value);
|
||||
}
|
||||
|
||||
/** Strictly parse the server-owned, bounded raw-row snapshot before display or export. */
|
||||
export function parseAnalysisSourceRecordList(value: unknown): AnalysisSourceRecordList | null {
|
||||
try {
|
||||
if (!isRecord(value) || !hasExactKeys(value, ['schemaVersion', 'kind', 'releaseId', 'queryComplete', 'totalRows', 'loadedRows', 'sets'])) return null;
|
||||
const encoded = JSON.stringify(value);
|
||||
if (typeof encoded !== 'string' || new TextEncoder().encode(encoded).byteLength > MAX_BYTES) return null;
|
||||
if (value.schemaVersion !== 1 || value.kind !== 'source_record_list' || !nonEmptyString(value.releaseId)
|
||||
|| typeof value.queryComplete !== 'boolean' || !count(value.totalRows) || !count(value.loadedRows)
|
||||
|| value.loadedRows > MAX_ROWS || value.loadedRows > value.totalRows || !Array.isArray(value.sets)) return null;
|
||||
|
||||
const setIds = new Set<string>();
|
||||
const sets: AnalysisSourceRecordSet[] = [];
|
||||
let summedTotalRows = 0;
|
||||
let summedLoadedRows = 0;
|
||||
for (const rawSet of value.sets) {
|
||||
if (!isRecord(rawSet) || !hasExactKeys(rawSet, ['id', 'nodeId', 'scopeId', 'label', 'stage', 'period', 'filters', 'fields', 'totalRows', 'loadedRows', 'complete', 'rows'])) return null;
|
||||
if (!nonEmptyString(rawSet.id) || setIds.has(rawSet.id) || !nonEmptyString(rawSet.nodeId) || !nonEmptyString(rawSet.scopeId)
|
||||
|| !nonEmptyString(rawSet.label) || (rawSet.stage !== 'black' && rawSet.stage !== 'bright')
|
||||
|| !isRecord(rawSet.period)
|
||||
|| !isRecord(rawSet.filters) || !validJsonValue(rawSet.filters)
|
||||
|| !Array.isArray(rawSet.fields) || rawSet.fields.length < 1 || rawSet.fields.length > 32
|
||||
|| !count(rawSet.totalRows) || !count(rawSet.loadedRows) || rawSet.loadedRows > rawSet.totalRows
|
||||
|| typeof rawSet.complete !== 'boolean' || !Array.isArray(rawSet.rows)
|
||||
|| rawSet.rows.length !== rawSet.loadedRows || rawSet.loadedRows > MAX_ROWS) return null;
|
||||
setIds.add(rawSet.id);
|
||||
|
||||
const period = parseAnalysisPeriod(rawSet.period, 1900, 2100);
|
||||
if (!period?.year) return null;
|
||||
const periodKeys = Object.keys(rawSet.period);
|
||||
if (periodKeys.some(key => !['year', 'month', 'quarter', 'monthStart', 'monthEnd'].includes(key))) return null;
|
||||
const fields: string[] = [];
|
||||
const fieldSet = new Set<string>();
|
||||
for (const field of rawSet.fields) {
|
||||
if (!nonEmptyString(field) || fieldSet.has(field)) return null;
|
||||
fieldSet.add(field);
|
||||
// Keep raw headers as the keys used by the server's values object. Display
|
||||
// sanitization is applied at the rendering boundary.
|
||||
fields.push(field);
|
||||
}
|
||||
if (rawSet.complete && rawSet.loadedRows !== rawSet.totalRows) return null;
|
||||
|
||||
const physicalIds = new Set<string>();
|
||||
const recordIds = new Set<string>();
|
||||
const rows: AnalysisSourceRecord[] = [];
|
||||
for (const rawRow of rawSet.rows) {
|
||||
if (!isRecord(rawRow) || !hasExactKeys(rawRow, ['recordId', 'sourceRevisionId', 'buildId', 'sourceFile', 'sheet', 'rowNumber', 'product', 'group', 'values'])) return null;
|
||||
const validRecordId = typeof rawRow.recordId === 'string' ? nonEmptyString(rawRow.recordId)
|
||||
: typeof rawRow.recordId === 'number' && Number.isSafeInteger(rawRow.recordId) && rawRow.recordId > 0;
|
||||
if (!validRecordId || !nonEmptyString(rawRow.sourceRevisionId) || !nonEmptyString(rawRow.buildId)
|
||||
|| !nonEmptyString(rawRow.sourceFile) || !nonEmptyString(rawRow.sheet)
|
||||
|| !Number.isSafeInteger(rawRow.rowNumber) || Number(rawRow.rowNumber) < 1
|
||||
|| (rawRow.product !== null && typeof rawRow.product !== 'string')
|
||||
|| (rawRow.group !== null && typeof rawRow.group !== 'string') || !isRecord(rawRow.values)) return null;
|
||||
const valueKeys = Object.keys(rawRow.values);
|
||||
if (valueKeys.length !== fieldSet.size || valueKeys.some(key => !fieldSet.has(key))) return null;
|
||||
const physicalId = JSON.stringify([rawRow.sourceRevisionId, rawRow.buildId, rawRow.sheet, rawRow.rowNumber]);
|
||||
const recordId = String(rawRow.recordId);
|
||||
if (physicalIds.has(physicalId) || recordIds.has(recordId)) return null;
|
||||
physicalIds.add(physicalId);
|
||||
recordIds.add(recordId);
|
||||
|
||||
const values = Object.create(null) as Record<string, string | number | boolean | null>;
|
||||
for (const field of fields) {
|
||||
const cell = rawRow.values[field];
|
||||
if (cell !== null && typeof cell !== 'string' && typeof cell !== 'number' && typeof cell !== 'boolean') return null;
|
||||
if (typeof cell === 'number' && !Number.isFinite(cell)) return null;
|
||||
// Source values are data. Preserve their exact text; React or DOM text
|
||||
// nodes provide escaping at the display boundary.
|
||||
values[field] = cell as string | number | boolean | null;
|
||||
}
|
||||
rows.push({
|
||||
recordId: rawRow.recordId as string | number,
|
||||
sourceRevisionId: rawRow.sourceRevisionId,
|
||||
buildId: rawRow.buildId,
|
||||
sourceFile: rawRow.sourceFile,
|
||||
sheet: rawRow.sheet,
|
||||
rowNumber: Number(rawRow.rowNumber),
|
||||
product: rawRow.product,
|
||||
group: rawRow.group,
|
||||
values,
|
||||
});
|
||||
}
|
||||
summedTotalRows += rawSet.totalRows;
|
||||
summedLoadedRows += rawSet.loadedRows;
|
||||
if (!Number.isSafeInteger(summedTotalRows) || !Number.isSafeInteger(summedLoadedRows) || summedLoadedRows > MAX_ROWS) return null;
|
||||
sets.push({
|
||||
id: rawSet.id, nodeId: rawSet.nodeId, scopeId: rawSet.scopeId, label: rawSet.label,
|
||||
stage: rawSet.stage, period: period as AnalysisSourceRecordSet['period'],
|
||||
filters: rawSet.filters, fields, totalRows: rawSet.totalRows, loadedRows: rawSet.loadedRows,
|
||||
complete: rawSet.complete, rows,
|
||||
});
|
||||
}
|
||||
if (summedTotalRows !== value.totalRows || summedLoadedRows !== value.loadedRows) return null;
|
||||
if (value.queryComplete && (value.loadedRows !== value.totalRows || sets.some(set => !set.complete || set.loadedRows !== set.totalRows))) return null;
|
||||
|
||||
return {
|
||||
schemaVersion: 1, kind: 'source_record_list', releaseId: value.releaseId,
|
||||
queryComplete: value.queryComplete, totalRows: value.totalRows, loadedRows: value.loadedRows, sets,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function analysisSourceRecordPeriod(period: AnalysisSourceRecordSet['period']): string {
|
||||
return analysisPeriodLabel(period, 1900, 2100);
|
||||
}
|
||||
|
||||
export function analysisSourceRecordSetLabel(set: AnalysisSourceRecordSet): string {
|
||||
const stage = set.stage === 'black' ? '黑片' : '亮片';
|
||||
return `${set.label} · ${stage} · ${analysisSourceRecordPeriod(set.period)}`;
|
||||
}
|
||||
|
||||
export function analysisSourceRecordSetFullyRead(set: AnalysisSourceRecordSet): boolean {
|
||||
return set.complete && set.loadedRows === set.totalRows;
|
||||
}
|
||||
|
||||
export function analysisSourceRecordListFullyRead(list: AnalysisSourceRecordList): boolean {
|
||||
return list.queryComplete && list.loadedRows === list.totalRows
|
||||
&& list.sets.every(analysisSourceRecordSetFullyRead);
|
||||
}
|
||||
|
||||
export function analysisSourceRecordSetReadStatus(set: AnalysisSourceRecordSet): string {
|
||||
return analysisSourceRecordSetFullyRead(set)
|
||||
? `已读取全部 ${set.loadedRows} / ${set.totalRows} 条`
|
||||
: `读取未完成 · 当前 ${set.loadedRows} / ${set.totalRows} 条`;
|
||||
}
|
||||
|
||||
export function analysisSourceRecordEmptyState(list: AnalysisSourceRecordList, set?: AnalysisSourceRecordSet): string {
|
||||
if (set) {
|
||||
if (set.complete && set.totalRows === 0) return '当前记录集没有原始记录';
|
||||
return '查询尚未完成,当前记录集没有已读取的原始记录';
|
||||
}
|
||||
return list.queryComplete ? '本次分析没有原始记录' : '查询尚未完成,尚未取得可展示记录';
|
||||
}
|
||||
|
||||
export function analysisSourceRecordCompletenessNotice(list: AnalysisSourceRecordList): string {
|
||||
return list.queryComplete ? '' : '本轮原始记录尚未查全,以下为已读取部分。';
|
||||
}
|
||||
|
||||
export function analysisSourceRecordPage(set: AnalysisSourceRecordSet, page: number, pageSize: number) {
|
||||
const size = Math.max(1, Math.trunc(pageSize));
|
||||
const pageCount = Math.max(1, Math.ceil(set.loadedRows / size));
|
||||
const currentPage = Math.min(Math.max(1, Math.trunc(page)), pageCount);
|
||||
const offset = (currentPage - 1) * size;
|
||||
return { page: currentPage, pageSize: size, offset, pageCount, rows: set.rows.slice(offset, offset + size) };
|
||||
}
|
||||
|
||||
export type AuthorizedRecordRead<T> = { data: T | null; error: string };
|
||||
|
||||
export async function authorizedSourceRecordRead<T>(
|
||||
data: T,
|
||||
authorize: () => Promise<unknown>,
|
||||
onUnauthorized: (error: unknown) => boolean,
|
||||
): Promise<AuthorizedRecordRead<T>> {
|
||||
try {
|
||||
await authorize();
|
||||
return { data, error: '' };
|
||||
} catch (error) {
|
||||
const handled = onUnauthorized(error);
|
||||
const detail = error instanceof Error
|
||||
? sanitizeText(error.message).replace(/\b[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\b/gi, '[隐藏标识]').slice(0, 300)
|
||||
: '';
|
||||
return { data: null, error: handled ? '访问权限已更新,原始记录已清空。' : detail || '当前快照复核失败,原始记录已清空。' };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
import { toCanvas, toSvg } from 'html-to-image';
|
||||
import { longReportImageSize, requiresFullResolutionStripCapture } from './analysisReportFiles.ts';
|
||||
import { encodeRgbaStripsToPng, reportLongImagePixelLimit, type RgbaStrip } from './analysisReportPng.ts';
|
||||
|
||||
type CaptureOptions = NonNullable<Parameters<typeof toCanvas>[1]>;
|
||||
const STRIP_HEIGHT = 2048;
|
||||
const MAX_STRIP_PIXELS = 4 * 1024 * 1024;
|
||||
const REPORT_TAIL_MARKER_WIDTH = 32;
|
||||
const REPORT_TAIL_MARKER_HEIGHT = 8;
|
||||
const REPORT_TAIL_PROBE_HEIGHT = 4096;
|
||||
const REPORT_TAIL_PROBE_PIXELS = 4 * 1024 * 1024;
|
||||
|
||||
function replaceSvgAttribute(openingTag: string, name: string, value: string) {
|
||||
const pattern = new RegExp(`(\\s${name}=")[^"]*(")`);
|
||||
if (!pattern.test(openingTag)) throw new Error('报告长图模板格式无效,请重试。');
|
||||
return openingTag.replace(pattern, (_match, before: string, after: string) => `${before}${value}${after}`);
|
||||
}
|
||||
|
||||
/** Prepare full-height and short SVG viewports over one html-to-image clone. */
|
||||
export function prepareReportSvgTemplate(svgDataUrl: string, width: number, sourceHeight: number) {
|
||||
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(sourceHeight) || width <= 0 || sourceHeight <= 0) {
|
||||
throw new Error('报告长图模板格式无效,请重试。');
|
||||
}
|
||||
const comma = svgDataUrl.indexOf(',');
|
||||
if (comma < 0 || !svgDataUrl.slice(0, comma).startsWith('data:image/svg+xml')) {
|
||||
throw new Error('报告长图模板格式无效,请重试。');
|
||||
}
|
||||
let markup: string;
|
||||
try { markup = decodeURIComponent(svgDataUrl.slice(comma + 1)); }
|
||||
catch { throw new Error('报告长图模板格式无效,请重试。'); }
|
||||
const openingEnd = markup.indexOf('>');
|
||||
const closingStart = markup.lastIndexOf('</svg>');
|
||||
if (openingEnd < 0 || closingStart <= openingEnd) throw new Error('报告长图模板格式无效,请重试。');
|
||||
|
||||
const rootOpening = markup.slice(0, openingEnd + 1);
|
||||
const inner = markup.slice(openingEnd + 1, closingStart);
|
||||
const foreignStart = inner.indexOf('<foreignObject');
|
||||
const foreignOpeningEnd = foreignStart < 0 ? -1 : inner.indexOf('>', foreignStart);
|
||||
if (foreignStart < 0 || foreignOpeningEnd < 0) throw new Error('报告长图模板格式无效,请重试。');
|
||||
const foreignOpening = inner.slice(foreignStart, foreignOpeningEnd + 1);
|
||||
const fullForeignOpening = replaceSvgAttribute(foreignOpening, 'width', `${width}`);
|
||||
const innerPrefix = inner.slice(0, foreignStart);
|
||||
const innerSuffix = inner.slice(foreignOpeningEnd + 1);
|
||||
const root = replaceSvgAttribute(rootOpening, 'width', `${width}`);
|
||||
|
||||
const fullReportInner = (fullHeight: number) => innerPrefix
|
||||
+ replaceSvgAttribute(fullForeignOpening, 'height', `${fullHeight}`) + innerSuffix;
|
||||
const rootFor = (viewportHeight: number, viewBox: string) => replaceSvgAttribute(
|
||||
replaceSvgAttribute(replaceSvgAttribute(root, 'height', `${viewportHeight}`), 'viewBox', viewBox),
|
||||
'width', `${width}`,
|
||||
);
|
||||
|
||||
return {
|
||||
fullMarkup(fullHeight: number) {
|
||||
if (!Number.isSafeInteger(fullHeight) || fullHeight <= 0) throw new Error('报告长图高度无效。');
|
||||
return `${rootFor(fullHeight, `0 0 ${width} ${fullHeight}`)}${fullReportInner(fullHeight)}</svg>`;
|
||||
},
|
||||
viewportMarkup(top: number, stripHeight: number, fullHeight: number) {
|
||||
if (!Number.isSafeInteger(fullHeight) || fullHeight <= 0) throw new Error('报告长图高度无效。');
|
||||
if (!Number.isSafeInteger(top) || !Number.isSafeInteger(stripHeight)
|
||||
|| top < 0 || stripHeight <= 0 || top + stripHeight > fullHeight) {
|
||||
throw new Error('报告长图条带范围无效。');
|
||||
}
|
||||
return `${rootFor(stripHeight, `0 ${top} ${width} ${stripHeight}`)}${fullReportInner(fullHeight)}</svg>`;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Prepare short SVG viewports over one html-to-image clone of the full report. */
|
||||
export function createReportSvgStripMarkupFactory(svgDataUrl: string, width: number, height: number) {
|
||||
const template = prepareReportSvgTemplate(svgDataUrl, width, height);
|
||||
return (top: number, stripHeight: number) => template.viewportMarkup(top, stripHeight, height);
|
||||
}
|
||||
|
||||
export function reportSvgDataUrl(markup: string) {
|
||||
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(markup)}`;
|
||||
}
|
||||
|
||||
export function requiresMeasuredReportSnapshot(hasSourceRecords: boolean, legacyCanvasWouldShrink: boolean) {
|
||||
return hasSourceRecords || legacyCanvasWouldShrink;
|
||||
}
|
||||
|
||||
export function resolveReportCanvasPixelRatio(hasSourceRecords: boolean, measuredPixelRatio: number) {
|
||||
return hasSourceRecords && measuredPixelRatio >= 1 ? 1 : measuredPixelRatio;
|
||||
}
|
||||
|
||||
function normalizeReportSvgRecordHeights(svgDataUrl: string, ownerDocument: Document) {
|
||||
const comma = svgDataUrl.indexOf(',');
|
||||
if (comma < 0) throw new Error('报告长图模板格式无效,请重试。');
|
||||
let markup: string;
|
||||
try { markup = decodeURIComponent(svgDataUrl.slice(comma + 1)); }
|
||||
catch { throw new Error('报告长图模板格式无效,请重试。'); }
|
||||
const Parser = ownerDocument.defaultView?.DOMParser ?? DOMParser;
|
||||
const parsed = new Parser().parseFromString(markup, 'image/svg+xml');
|
||||
if (parsed.querySelector('parsererror')) throw new Error('报告长图模板格式无效,请重试。');
|
||||
const targets = new Set<Element>();
|
||||
parsed.querySelectorAll('.q-report').forEach(element => targets.add(element));
|
||||
for (const list of Array.from(parsed.querySelectorAll('.q-source-record-list'))) {
|
||||
targets.add(list);
|
||||
list.querySelectorAll('.q-source-record-set,table,thead,tbody,tr,th,td').forEach(element => targets.add(element));
|
||||
}
|
||||
// Native historical tables also carry physical records, without the legacy appendix classes.
|
||||
// Release cloned row/cell heights and every flow ancestor so the raster tail follows wrapped values.
|
||||
for (const row of Array.from(parsed.querySelectorAll('tr[data-record-provenance]'))) {
|
||||
for (let flow: Element | null = row; flow && flow.localName !== 'foreignObject'; flow = flow.parentElement) {
|
||||
targets.add(flow);
|
||||
}
|
||||
row.querySelectorAll('th,td').forEach(element => targets.add(element));
|
||||
}
|
||||
for (const element of targets) {
|
||||
const style = (element as HTMLElement).style;
|
||||
style.setProperty('height', 'auto', 'important');
|
||||
style.setProperty('max-height', 'none', 'important');
|
||||
}
|
||||
const Serializer = ownerDocument.defaultView?.XMLSerializer ?? XMLSerializer;
|
||||
return reportSvgDataUrl(new Serializer().serializeToString(parsed.documentElement));
|
||||
}
|
||||
|
||||
export function normalizeReportRectOffset(renderedOffset: number, logicalHeight: number, renderedHeight: number) {
|
||||
if (!Number.isFinite(renderedOffset) || !Number.isFinite(logicalHeight) || !Number.isFinite(renderedHeight)
|
||||
|| logicalHeight <= 0 || renderedHeight <= 0) throw new Error('无法测量报告最终排版高度,请重试。');
|
||||
return renderedOffset * logicalHeight / renderedHeight;
|
||||
}
|
||||
|
||||
export function assertReportMeasurementAtOneX(renderedWidth: number, layoutWidth: number) {
|
||||
if (!Number.isFinite(renderedWidth) || !Number.isFinite(layoutWidth) || layoutWidth <= 0
|
||||
|| Math.abs(renderedWidth - layoutWidth) > 1) {
|
||||
throw new Error('无法在原始比例下测量报告排版,请重试。');
|
||||
}
|
||||
}
|
||||
|
||||
function isTailMarkerColor(data: Uint8ClampedArray, index: number, color: 'magenta' | 'cyan') {
|
||||
if (color === 'magenta') return data[index] >= 240 && data[index + 1] <= 40 && data[index + 2] >= 240 && data[index + 3] >= 240;
|
||||
return data[index] <= 40 && data[index + 1] >= 240 && data[index + 2] >= 240 && data[index + 3] >= 240;
|
||||
}
|
||||
|
||||
/** Return the first full raster row of the two-color tail marker, or fail closed. */
|
||||
export function findReportTailMarkerTop(data: Uint8ClampedArray, width: number, height: number, probeTop: number) {
|
||||
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || !Number.isSafeInteger(probeTop)
|
||||
|| width < REPORT_TAIL_MARKER_WIDTH || height <= 0 || probeTop < 0
|
||||
|| data.length !== width * height * 4) throw new Error('报告尾部像素探针尺寸无效,请重试。');
|
||||
let firstMatch = -1;
|
||||
let previousMatch = -2;
|
||||
for (let y = 0; y < height; y += 1) {
|
||||
let matched = true;
|
||||
for (let x = 0; x < REPORT_TAIL_MARKER_WIDTH; x += 1) {
|
||||
const offset = (y * width + x) * 4;
|
||||
const color = x < REPORT_TAIL_MARKER_WIDTH / 2 ? 'magenta' : 'cyan';
|
||||
if (!isTailMarkerColor(data, offset, color)) { matched = false; break; }
|
||||
}
|
||||
if (matched) {
|
||||
if (previousMatch === y - 1) return probeTop + firstMatch + 1;
|
||||
firstMatch = y;
|
||||
previousMatch = y;
|
||||
} else {
|
||||
previousMatch = -2;
|
||||
}
|
||||
}
|
||||
throw new Error('未能确认报告长图尾部位置,请缩小范围后重试。');
|
||||
}
|
||||
|
||||
function logicalTopWithin(element: HTMLElement, ancestor: HTMLElement) {
|
||||
const ancestorRect = ancestor.getBoundingClientRect();
|
||||
const elementRect = element.getBoundingClientRect();
|
||||
return normalizeReportRectOffset(elementRect.top - ancestorRect.top, ancestor.offsetHeight, ancestorRect.height);
|
||||
}
|
||||
|
||||
export function resolveReportSnapshotHeight(metrics: {
|
||||
layoutOffsetHeight: number;
|
||||
layoutScrollHeight: number;
|
||||
footerBottom: number;
|
||||
footerTextBottom: number;
|
||||
lastRecordBottom: number;
|
||||
}) {
|
||||
const height = Math.ceil(Math.max(metrics.layoutOffsetHeight, metrics.layoutScrollHeight,
|
||||
metrics.footerBottom, metrics.footerTextBottom, metrics.lastRecordBottom));
|
||||
if (!Number.isSafeInteger(height) || height <= 0) throw new Error('无法测量报告最终排版高度,请重试。');
|
||||
return height;
|
||||
}
|
||||
|
||||
export function assertReportFooterAfterLastRecord(footerTop: number, lastRowBottom: number) {
|
||||
if (!Number.isFinite(footerTop) || !Number.isFinite(lastRowBottom) || footerTop < lastRowBottom) {
|
||||
throw new Error('原始记录末行与报告页脚排版重叠,无法安全生成长图。');
|
||||
}
|
||||
}
|
||||
|
||||
export function isDocumentNodeFollowing(position: number) {
|
||||
return (position & 4) !== 0;
|
||||
}
|
||||
|
||||
async function calibrateReportTailHeight(svg: SVGSVGElement, foreignObject: SVGForeignObjectElement,
|
||||
measurementDocument: Document, width: number, measurementHeight: number, domMeasuredHeight: number,
|
||||
cancelled: () => boolean) {
|
||||
const probeHeight = Math.min(REPORT_TAIL_PROBE_HEIGHT, Math.floor(REPORT_TAIL_PROBE_PIXELS / width), measurementHeight);
|
||||
if (probeHeight < REPORT_TAIL_MARKER_HEIGHT + 2) throw new Error('报告尾部像素探针尺寸无效,请重试。');
|
||||
const probeTop = Math.max(0, Math.min(Math.floor(domMeasuredHeight - probeHeight / 2), measurementHeight - probeHeight));
|
||||
const checkCancelled = () => { if (cancelled()) throw new Error('已取消长图准备。'); };
|
||||
const marker = measurementDocument.createElementNS('http://www.w3.org/1999/xhtml', 'div') as HTMLElement;
|
||||
marker.style.cssText = 'display:block;width:32px;height:8px;margin:0;padding:0;border:0;overflow:hidden;box-sizing:border-box;background:#00ffff!important';
|
||||
const markerAccent = measurementDocument.createElementNS('http://www.w3.org/1999/xhtml', 'div') as HTMLElement;
|
||||
markerAccent.style.cssText = 'display:block;width:16px;height:8px;margin:0;padding:0;border:0;box-sizing:border-box;background:#ff00ff!important';
|
||||
marker.append(markerAccent);
|
||||
foreignObject.append(marker);
|
||||
|
||||
const Serializer = measurementDocument.defaultView?.XMLSerializer;
|
||||
if (!Serializer) throw new Error('无法序列化报告尾部探针,请重试。');
|
||||
svg.setAttribute('height', `${probeHeight}`);
|
||||
svg.setAttribute('viewBox', `0 ${probeTop} ${width} ${probeHeight}`);
|
||||
const image = measurementDocument.createElement('img');
|
||||
const canvas = measurementDocument.createElement('canvas');
|
||||
try {
|
||||
image.decoding = 'async';
|
||||
image.src = reportSvgDataUrl(new Serializer().serializeToString(svg));
|
||||
await image.decode();
|
||||
checkCancelled();
|
||||
if (image.naturalWidth !== width || image.naturalHeight !== probeHeight) {
|
||||
throw new Error('报告尾部像素探针超出可测量高度,请缩小范围后重试。');
|
||||
}
|
||||
canvas.width = width;
|
||||
canvas.height = probeHeight;
|
||||
const context = canvas.getContext('2d');
|
||||
if (!context) throw new Error('报告尾部像素探针栅格化失败,请重试。');
|
||||
context.fillStyle = '#fff';
|
||||
context.fillRect(0, 0, width, probeHeight);
|
||||
context.drawImage(image, 0, 0, width, probeHeight);
|
||||
const pixels = context.getImageData(0, 0, width, probeHeight).data;
|
||||
checkCancelled();
|
||||
return findReportTailMarkerTop(pixels, width, probeHeight, probeTop);
|
||||
} finally {
|
||||
canvas.width = 0;
|
||||
canvas.height = 0;
|
||||
image.removeAttribute('src');
|
||||
}
|
||||
}
|
||||
|
||||
async function measureReportSnapshotHeight(ownerDocument: Document, fullMarkup: string, width: number, minimumHeight: number,
|
||||
cancelled: () => boolean) {
|
||||
const measurementHeight = Math.max(minimumHeight, Math.floor(reportLongImagePixelLimit / width))
|
||||
+ REPORT_TAIL_MARKER_HEIGHT + 1;
|
||||
const Parser = ownerDocument.defaultView?.DOMParser ?? DOMParser;
|
||||
const parsed = new Parser().parseFromString(fullMarkup, 'image/svg+xml');
|
||||
if (parsed.querySelector('parsererror')) throw new Error('无法测量报告最终排版高度,请重试。');
|
||||
const mount = ownerDocument.body ?? ownerDocument.documentElement;
|
||||
const checkCancelled = () => { if (cancelled()) throw new Error('已取消长图准备。'); };
|
||||
const measurementFrame = ownerDocument.createElement('iframe');
|
||||
measurementFrame.setAttribute('sandbox', 'allow-same-origin');
|
||||
measurementFrame.setAttribute('aria-hidden', 'true');
|
||||
measurementFrame.tabIndex = -1;
|
||||
measurementFrame.style.cssText = `position:fixed;left:-100000px;top:0;width:${width}px;height:${measurementHeight}px;border:0;margin:0;padding:0;box-sizing:border-box;visibility:hidden;pointer-events:none`;
|
||||
const loaded = new Promise<void>((resolve, reject) => {
|
||||
measurementFrame.addEventListener('load', () => resolve(), { once: true });
|
||||
measurementFrame.addEventListener('error', () => reject(new Error('无法准备报告测量环境,请重试。')), { once: true });
|
||||
});
|
||||
measurementFrame.srcdoc = '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><style>:root,:root>body{width:100%!important;min-width:0!important;margin:0!important;padding:0!important;border:0!important;zoom:1!important;box-sizing:border-box!important}:root>body{min-height:0!important}</style></head><body></body></html>';
|
||||
mount.append(measurementFrame);
|
||||
try {
|
||||
await loaded;
|
||||
checkCancelled();
|
||||
const measurementDocument = measurementFrame.contentDocument;
|
||||
if (!measurementDocument?.body || !measurementDocument.defaultView) throw new Error('无法准备报告测量环境,请重试。');
|
||||
const svg = measurementDocument.importNode(parsed.documentElement, true) as unknown as SVGSVGElement;
|
||||
const foreignObject = svg.querySelector('foreignObject') as SVGForeignObjectElement | null;
|
||||
const clonedRoot = foreignObject?.firstElementChild as HTMLElement | null;
|
||||
if (!foreignObject || !clonedRoot) throw new Error('无法测量报告最终排版高度,请重试。');
|
||||
svg.setAttribute('width', `${width}`);
|
||||
svg.setAttribute('height', `${measurementHeight}`);
|
||||
svg.setAttribute('viewBox', `0 0 ${width} ${measurementHeight}`);
|
||||
foreignObject.setAttribute('width', `${width}`);
|
||||
foreignObject.setAttribute('height', `${measurementHeight}`);
|
||||
svg.style.cssText = 'display:block;overflow:visible;margin:0;padding:0;border:0';
|
||||
measurementDocument.body.style.cssText = 'width:100%;min-width:0;margin:0;padding:0;border:0;zoom:1';
|
||||
measurementDocument.body.append(svg);
|
||||
await measurementDocument.fonts?.ready;
|
||||
checkCancelled();
|
||||
await Promise.all([...svg.querySelectorAll('img')].map(image => image.decode?.().catch(() => undefined)));
|
||||
checkCancelled();
|
||||
await new Promise<void>(resolve => {
|
||||
const requestFrame = measurementDocument.defaultView?.requestAnimationFrame.bind(measurementDocument.defaultView);
|
||||
if (requestFrame) requestFrame(() => resolve());
|
||||
else requestAnimationFrame(() => resolve());
|
||||
});
|
||||
checkCancelled();
|
||||
assertReportMeasurementAtOneX(clonedRoot.getBoundingClientRect().width, clonedRoot.offsetWidth);
|
||||
// Native reports can have the report shell and raw-record appendix as body siblings.
|
||||
// Measure the capture root and query records/footers across that whole flow.
|
||||
const layoutRoot = clonedRoot;
|
||||
const footers = [...layoutRoot.querySelectorAll<HTMLElement>('footer')];
|
||||
const recordRows = layoutRoot.querySelectorAll<HTMLElement>('.q-source-record-list tbody tr,tr[data-record-provenance]');
|
||||
const lastRecordRow = recordRows.item(recordRows.length - 1) ?? null;
|
||||
const footer = lastRecordRow
|
||||
? footers.find(candidate => isDocumentNodeFollowing(lastRecordRow.compareDocumentPosition(candidate)))
|
||||
: footers.at(-1);
|
||||
const measuredFooter = footer ?? footers.at(-1) ?? null;
|
||||
const footerTop = measuredFooter ? logicalTopWithin(measuredFooter, layoutRoot) : 0;
|
||||
const lastRowBottom = lastRecordRow
|
||||
? logicalTopWithin(lastRecordRow, layoutRoot) + lastRecordRow.offsetHeight
|
||||
: 0;
|
||||
if (footer && lastRecordRow) assertReportFooterAfterLastRecord(footerTop, lastRowBottom);
|
||||
const footerRect = measuredFooter?.getBoundingClientRect();
|
||||
const rootRect = layoutRoot.getBoundingClientRect();
|
||||
const footerBottom = footerRect
|
||||
? normalizeReportRectOffset(footerRect.bottom - rootRect.top, layoutRoot.offsetHeight, rootRect.height)
|
||||
: 0;
|
||||
let footerTextRangeBottom = 0;
|
||||
if (measuredFooter) {
|
||||
const filter = measurementDocument.defaultView.NodeFilter.SHOW_TEXT;
|
||||
const walker = measurementDocument.createTreeWalker(measuredFooter, filter);
|
||||
let lastText: Text | null = null;
|
||||
let textNode: Node | null;
|
||||
while ((textNode = walker.nextNode())) {
|
||||
if (textNode.textContent?.trim()) lastText = textNode as Text;
|
||||
}
|
||||
if (lastText) {
|
||||
const range = measurementDocument.createRange();
|
||||
range.selectNodeContents(lastText);
|
||||
const rangeRect = range.getBoundingClientRect();
|
||||
footerTextRangeBottom = normalizeReportRectOffset(rangeRect.bottom - rootRect.top,
|
||||
layoutRoot.offsetHeight, rootRect.height);
|
||||
}
|
||||
}
|
||||
const domMeasuredHeight = resolveReportSnapshotHeight({ layoutOffsetHeight: layoutRoot.offsetHeight,
|
||||
layoutScrollHeight: layoutRoot.scrollHeight, footerBottom, footerTextBottom: footerTextRangeBottom,
|
||||
lastRecordBottom: lastRowBottom });
|
||||
const finalHeight = await calibrateReportTailHeight(svg, foreignObject, measurementDocument, width,
|
||||
measurementHeight, domMeasuredHeight, cancelled);
|
||||
return finalHeight;
|
||||
} finally {
|
||||
measurementFrame.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/** Capture the complete report in layout pixels, independently of workspace zoom. */
|
||||
export async function captureReportLongImage(node: HTMLElement, options: CaptureOptions,
|
||||
cancelled: () => boolean): Promise<Blob> {
|
||||
const details = [...node.querySelectorAll('details')].map(element => ({ element, open: element.open }));
|
||||
const checkCancelled = () => { if (cancelled()) throw new Error('已取消长图准备。'); };
|
||||
let canvas: HTMLCanvasElement | undefined;
|
||||
try {
|
||||
details.forEach(({ element }) => { element.open = true; });
|
||||
await node.ownerDocument.fonts?.ready;
|
||||
await Promise.all([...node.querySelectorAll('img')].map(image => image.decode?.().catch(() => undefined)));
|
||||
await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
|
||||
checkCancelled();
|
||||
const rawWidth = node.offsetWidth;
|
||||
const rawHeight = Math.max(node.scrollHeight, node.offsetHeight);
|
||||
const { width, height, pixelRatio } = longReportImageSize(rawWidth, rawHeight);
|
||||
const hasSourceRecordList = node.matches('.q-source-record-list') || Boolean(node.querySelector('.q-source-record-list,tr[data-record-provenance]'));
|
||||
if (requiresMeasuredReportSnapshot(hasSourceRecordList, requiresFullResolutionStripCapture(rawWidth, rawHeight))) {
|
||||
const svgDataUrl = await toSvg(node, {
|
||||
...options,
|
||||
width,
|
||||
height,
|
||||
backgroundColor: '#fff',
|
||||
style: { ...options.style, width: `${width}px`, height: 'auto', minHeight: '0', margin: '0', transform: 'none' },
|
||||
});
|
||||
checkCancelled();
|
||||
const normalizedSvgDataUrl = normalizeReportSvgRecordHeights(svgDataUrl, node.ownerDocument);
|
||||
const template = prepareReportSvgTemplate(normalizedSvgDataUrl, width, height);
|
||||
const finalHeight = await measureReportSnapshotHeight(node.ownerDocument,
|
||||
template.fullMarkup(Math.max(height, Math.ceil(reportLongImagePixelLimit / width))), width, height, cancelled);
|
||||
if (width * finalHeight > reportLongImagePixelLimit) {
|
||||
throw new Error('报告过长,超过单张清晰长图的安全尺寸上限。请缩小报告范围后重试。');
|
||||
}
|
||||
checkCancelled();
|
||||
const measuredSize = longReportImageSize(width, finalHeight);
|
||||
const image = node.ownerDocument.createElement('img');
|
||||
image.decoding = 'async';
|
||||
if (measuredSize.pixelRatio >= 1) {
|
||||
const capturePixelRatio = resolveReportCanvasPixelRatio(hasSourceRecordList, measuredSize.pixelRatio);
|
||||
try {
|
||||
image.src = reportSvgDataUrl(template.fullMarkup(finalHeight));
|
||||
await image.decode();
|
||||
checkCancelled();
|
||||
canvas = node.ownerDocument.createElement('canvas');
|
||||
canvas.width = width * capturePixelRatio;
|
||||
canvas.height = finalHeight * capturePixelRatio;
|
||||
const context = canvas.getContext('2d');
|
||||
if (!context) throw new Error('长图生成失败,请重试。');
|
||||
context.fillStyle = '#fff';
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
context.drawImage(image, 0, 0, canvas.width, canvas.height);
|
||||
const blob = await new Promise<Blob>((resolve, reject) => canvas!.toBlob(value => value
|
||||
? resolve(value) : reject(new Error('长图生成失败,请重试。')), 'image/png'));
|
||||
checkCancelled();
|
||||
return blob;
|
||||
} finally {
|
||||
image.removeAttribute('src');
|
||||
}
|
||||
}
|
||||
const stripHeightLimit = Math.max(1, Math.min(STRIP_HEIGHT, Math.floor(MAX_STRIP_PIXELS / width)));
|
||||
const strips = async function* (): AsyncGenerator<RgbaStrip> {
|
||||
for (let top = 0; top < finalHeight; top += stripHeightLimit) {
|
||||
checkCancelled();
|
||||
const stripHeight = Math.min(stripHeightLimit, finalHeight - top);
|
||||
let pixels: Uint8ClampedArray;
|
||||
let stripCanvas: HTMLCanvasElement | undefined;
|
||||
try {
|
||||
image.src = reportSvgDataUrl(template.viewportMarkup(top, stripHeight, finalHeight));
|
||||
await image.decode();
|
||||
checkCancelled();
|
||||
stripCanvas = node.ownerDocument.createElement('canvas');
|
||||
stripCanvas.width = width;
|
||||
stripCanvas.height = stripHeight;
|
||||
const context = stripCanvas.getContext('2d');
|
||||
if (!context) throw new Error('长图分段栅格化失败,请重试。');
|
||||
context.fillStyle = '#fff';
|
||||
context.fillRect(0, 0, width, stripHeight);
|
||||
context.drawImage(image, 0, 0, width, stripHeight);
|
||||
pixels = context.getImageData(0, 0, width, stripHeight).data;
|
||||
} finally {
|
||||
if (stripCanvas) { stripCanvas.width = 0; stripCanvas.height = 0; }
|
||||
image.removeAttribute('src');
|
||||
}
|
||||
yield { y: top, height: stripHeight, data: pixels };
|
||||
}
|
||||
};
|
||||
try { return await encodeRgbaStripsToPng(width, finalHeight, strips(), cancelled); }
|
||||
finally { image.removeAttribute('src'); }
|
||||
}
|
||||
canvas = await toCanvas(node, { ...options, width, height, pixelRatio, backgroundColor: '#fff', skipAutoScale: true,
|
||||
style: { ...options.style, width: `${width}px`, height: `${height}px`, minHeight: '0', margin: '0', transform: 'none' } });
|
||||
checkCancelled();
|
||||
const blob = await new Promise<Blob>((resolve, reject) => canvas!.toBlob(value => value ? resolve(value) : reject(new Error('长图生成失败,请重试。')), 'image/png'));
|
||||
checkCancelled();
|
||||
return blob;
|
||||
} finally {
|
||||
if (canvas) { canvas.width = 0; canvas.height = 0; }
|
||||
details.forEach(({ element, open }) => { element.open = open; });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
export function reportDownloadName(period: string) {
|
||||
const sameYear = period.match(/^(\d{4})-(\d{2})\s*→\s*\1-(\d{2})$/);
|
||||
const label = sameYear ? `${sameYear[1]}-${sameYear[2]}至${sameYear[3]}`
|
||||
: /^\d{4}(?:-(?:\d{2}|Q[1-4]))?(?:\s*→\s*\d{4}(?:-(?:\d{2}|Q[1-4]))?)?$/.test(period)
|
||||
? period.replace(/\s*→\s*/, '至') : '';
|
||||
return `质量分析${label ? `_${label}` : ''}_报告`;
|
||||
}
|
||||
|
||||
/** Fit the whole report into one PNG without cropping or changing its aspect ratio. */
|
||||
export function longReportImageSize(rawWidth: number, rawHeight: number) {
|
||||
if (!Number.isFinite(rawWidth) || !Number.isFinite(rawHeight) || rawWidth <= 0 || rawHeight <= 0) {
|
||||
throw new Error('报告尺寸无效,请重新打开报告。');
|
||||
}
|
||||
const width = Math.ceil(rawWidth), height = Math.ceil(rawHeight);
|
||||
const pixelRatio = Math.min(1.5, 30000 / width, 30000 / height, Math.sqrt(48000000 / (width * height)));
|
||||
return { width, height, pixelRatio };
|
||||
}
|
||||
|
||||
/** Switch to bounded, full-width strip rendering only when the legacy canvas must shrink the page. */
|
||||
export function requiresFullResolutionStripCapture(rawWidth: number, rawHeight: number) {
|
||||
return longReportImageSize(rawWidth, rawHeight).pixelRatio < 1;
|
||||
}
|
||||
|
||||
/** Verify access immediately before starting a prepared-file download. */
|
||||
export async function downloadAuthorizedReport(options: {
|
||||
authorize: () => Promise<void>;
|
||||
isCurrent: () => boolean;
|
||||
download: () => void;
|
||||
onDenied: (error: unknown) => void;
|
||||
}) {
|
||||
try {
|
||||
await options.authorize();
|
||||
} catch (error) {
|
||||
if (options.isCurrent()) options.onDenied(error);
|
||||
return;
|
||||
}
|
||||
if (options.isCurrent()) options.download();
|
||||
}
|
||||
@@ -2,6 +2,16 @@ import { sanitizeAnalysisDisplayText } from './analysisDisplayText.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 interface FocusProductRow {
|
||||
product: string;
|
||||
stage?: 'black' | 'bright' | 'all';
|
||||
scrapDelta: string;
|
||||
rateChange: string;
|
||||
rateLabel: string;
|
||||
basis: string;
|
||||
detail: string;
|
||||
evidenceRefs: string[];
|
||||
}
|
||||
export interface NarrativeSection {
|
||||
id: string;
|
||||
title: string;
|
||||
@@ -11,6 +21,7 @@ export interface NarrativeSection {
|
||||
tables: string[];
|
||||
visuals: AnalysisVisual[];
|
||||
evidenceRefs: string[];
|
||||
focusProducts?: FocusProductRow[];
|
||||
}
|
||||
export interface AnalysisNarrativeModel {
|
||||
sections: NarrativeSection[];
|
||||
@@ -61,6 +72,81 @@ export function narrativeParts(markdown: string): { narrative: string; tables: s
|
||||
return { narrative: prose.join('\n').trim(), tables };
|
||||
}
|
||||
|
||||
/** Only the deterministic report's exact table contract is eligible for a compact summary. */
|
||||
function productTableCells(line: string): string[] {
|
||||
const source = line.trim().replace(/^\|/, '').replace(/(?<!\\)\|$/, '');
|
||||
return source.split(/(?<!\\)\|/).map(cell => cell.trim().replaceAll('\\|', '|'));
|
||||
}
|
||||
|
||||
function focusProductCandidates(sections: NarrativeSection[]): Array<Omit<FocusProductRow, 'detail'>> {
|
||||
const candidates: Array<Omit<FocusProductRow, 'detail'>> = [];
|
||||
const number = /^(?:[+−-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|—)$/;
|
||||
for (const section of sections) {
|
||||
if (section.kind !== 'product' || !/(重点产品|产品率变化线索)/.test(section.title)) continue;
|
||||
const order = section.title.match(/[((]按(报废增量|当前报废重量|合格率降幅),本次返回前\d+[))]/)?.[1];
|
||||
if (!order) continue;
|
||||
const stage = section.title.startsWith('黑片') ? '黑片' : section.title.startsWith('亮片') ? '亮片' : '';
|
||||
for (const table of section.tables) {
|
||||
const lines = table.split('\n');
|
||||
const headers = productTableCells(lines[0] || '');
|
||||
const rateLabel = headers[2]?.match(/^(综合率|黑片合格率|亮片合格率):比较期→本期 \/ 变化$/)?.[1];
|
||||
const tableRefs = refs(lines.filter(line => !line.trim().startsWith('|')).join('\n'));
|
||||
if (headers.length !== 4 || headers[0] !== '规格' || headers[1] !== '本期报废 / 增量(kg)'
|
||||
|| headers[3] !== '阶段投入:比较期→本期(kg)' || !rateLabel || tableRefs.length !== 1) continue;
|
||||
for (const line of lines.slice(2)) {
|
||||
if (!line.trim().startsWith('|')) break;
|
||||
const cells = productTableCells(line);
|
||||
if (cells.length !== 4 || !cells[0] || !cells[3]) continue;
|
||||
const weights = cells[1].split(/\s*\/\s*/);
|
||||
const rateParts = cells[2].split(';');
|
||||
if (weights.length !== 2 || !weights.every(value => number.test(value)) || rateParts.length !== 2
|
||||
|| !/^(?:[\d,.]+%|—)→(?:[\d,.]+%|—)$/.test(rateParts[0])
|
||||
|| !/^(?:(?:上升|下降)[\d,.]+个百分点|持平|不可比)$/.test(rateParts[1])) continue;
|
||||
candidates.push({ product: cells[0], stage: stage === '黑片' ? 'black' : stage === '亮片' ? 'bright' : rateLabel === '黑片合格率' ? 'black' : rateLabel === '亮片合格率' ? 'bright' : 'all', scrapDelta: weights[1], rateChange: rateParts[1], rateLabel,
|
||||
basis: `${stage ? `${stage} · ` : ''}按${order}排序${order === '合格率降幅' ? ',仅作率变化线索' : ''}`,
|
||||
evidenceRefs: tableRefs });
|
||||
}
|
||||
}
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
/** Move selected, cited product facts near the conclusion without changing their order or numbers. */
|
||||
function bringFocusProductsForward(sections: NarrativeSection[]): NarrativeSection[] {
|
||||
const candidates = focusProductCandidates(sections);
|
||||
if (!candidates.length) return sections;
|
||||
const focusProducts: FocusProductRow[] = [];
|
||||
const remaining = sections.map(section => {
|
||||
if (section.kind !== 'action') return section;
|
||||
let fenced = false;
|
||||
let moved = false;
|
||||
const lines = section.narrative.split('\n').filter(line => {
|
||||
if (/^\s*```/.test(line)) fenced = !fenced;
|
||||
if (fenced) return true;
|
||||
const detail = line.match(/^\s*[-*+]\s+(.+)$/)?.[1];
|
||||
if (!detail) return true;
|
||||
const detailRefs = refs(detail);
|
||||
const matches = candidates.filter(row => detail.startsWith(`${row.product}:`)
|
||||
&& detailRefs.length === 1 && row.evidenceRefs[0] === detailRefs[0]
|
||||
&& detail.includes(`增量${row.scrapDelta} kg`) && detail.includes(row.rateChange));
|
||||
// A shared reference with more than one possible row is not enough to choose a scope.
|
||||
if (matches.length !== 1) return true;
|
||||
focusProducts.push({ ...matches[0], detail });
|
||||
moved = true;
|
||||
return false;
|
||||
});
|
||||
if (!moved) return section;
|
||||
const narrative = lines.join('\n').trim();
|
||||
const stillHasAction = /^\s*(?:[-*+]\s+|\d+[.)]\s+)/m.test(narrative);
|
||||
return { ...section, narrative, ...(stillHasAction ? {} : { title: '', kind: 'other' as const }) };
|
||||
}).filter(section => section.narrative || section.tables.length || section.visuals.length);
|
||||
if (!focusProducts.length) return sections;
|
||||
const insertAt = Math.max(0, remaining.findIndex(section => section.kind === 'overview') + 1);
|
||||
remaining.splice(insertAt, 0, { id: 'focus-product-summary', title: '重点产品', kind: 'product', markdown: '',
|
||||
narrative: '', tables: [], visuals: [], evidenceRefs: [...new Set(focusProducts.flatMap(row => row.evidenceRefs))], focusProducts });
|
||||
return remaining;
|
||||
}
|
||||
|
||||
function visualKind(visual: AnalysisVisual): NarrativeKind {
|
||||
const key = (visual as AnalysisVisual & { sectionKey?: string }).sectionKey;
|
||||
if (key?.startsWith('category_')) return 'category';
|
||||
@@ -117,7 +203,7 @@ function sectionScore(section: NarrativeSection, visual: AnalysisVisual, primary
|
||||
return score;
|
||||
}
|
||||
|
||||
export function buildAnalysisNarrative(answer: string, rawVisuals: unknown, question = ''): AnalysisNarrativeModel {
|
||||
export function buildAnalysisNarrative(answer: string, rawVisuals: unknown, question = '', additionalEvidenceRefs: string[] = []): AnalysisNarrativeModel {
|
||||
const safe = sanitizeAnalysisDisplayText(answer).replaceAll('\r\n', '\n').replaceAll('\r', '\n');
|
||||
const visuals = combineStageDefectVisuals(parseAnalysisVisuals(rawVisuals).visuals);
|
||||
const scopeDepth = (visual: AnalysisVisual) => ['department','group','product','category','defect'].filter(key => visual.scope[key]).length;
|
||||
@@ -152,7 +238,7 @@ export function buildAnalysisNarrative(answer: string, rawVisuals: unknown, ques
|
||||
else sections.push({ id: `section-${sections.length + 1}`, title, kind, markdown: '', narrative: '', tables: [], visuals: [visual], evidenceRefs: visual.evidenceRefs });
|
||||
}
|
||||
}
|
||||
const allRefs = [...new Set([...refs(safe), ...visuals.flatMap(visual => visual.evidenceRefs)])];
|
||||
const allRefs = [...new Set([...additionalEvidenceRefs, ...refs(safe), ...visuals.flatMap(visual => visual.evidenceRefs)])];
|
||||
const evidenceLabels = Object.fromEntries(allRefs.map((ref, index) => [ref, `依据 ${index + 1}`]));
|
||||
const evidence = allRefs.map(ref => {
|
||||
const charts = visuals.filter(visual => visual.evidenceRefs.includes(ref));
|
||||
@@ -169,5 +255,5 @@ export function buildAnalysisNarrative(answer: string, rawVisuals: unknown, ques
|
||||
: main?.metric === 'composite_rate' ? '质量变化分析' : '质量数据分析';
|
||||
const title = period && (broad || cleanQuestion.length > 40 || /用.*图|展示|查看/.test(cleanQuestion))
|
||||
? `${period} ${topic}` : cleanQuestion || '质量分析报告';
|
||||
return { sections, evidence, evidenceLabels, period, scope, title };
|
||||
return { sections: bringFocusProductsForward(sections), evidence, evidenceLabels, period, scope, title };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
const PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||
const MAX_REPORT_PIXELS = 100_000_000;
|
||||
const MAX_REPORT_WIDTH = 16_384;
|
||||
const IDAT_CHUNK_SIZE = 64 * 1024;
|
||||
|
||||
export type RgbaStrip = {
|
||||
y: number;
|
||||
height: number;
|
||||
data: Uint8Array | Uint8ClampedArray;
|
||||
};
|
||||
|
||||
const CRC_TABLE = (() => {
|
||||
const table = new Uint32Array(256);
|
||||
for (let index = 0; index < table.length; index += 1) {
|
||||
let value = index;
|
||||
for (let bit = 0; bit < 8; bit += 1) value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
|
||||
table[index] = value >>> 0;
|
||||
}
|
||||
return table;
|
||||
})();
|
||||
|
||||
function writeUint32(target: Uint8Array, offset: number, value: number) {
|
||||
target[offset] = (value >>> 24) & 0xff;
|
||||
target[offset + 1] = (value >>> 16) & 0xff;
|
||||
target[offset + 2] = (value >>> 8) & 0xff;
|
||||
target[offset + 3] = value & 0xff;
|
||||
}
|
||||
|
||||
function crc32(bytes: Uint8Array) {
|
||||
let value = 0xffffffff;
|
||||
for (const byte of bytes) value = CRC_TABLE[(value ^ byte) & 0xff] ^ (value >>> 8);
|
||||
return (value ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function pngChunk(type: string, data: Uint8Array) {
|
||||
const bytes = new Uint8Array(12 + data.length);
|
||||
writeUint32(bytes, 0, data.length);
|
||||
bytes.set(new TextEncoder().encode(type), 4);
|
||||
bytes.set(data, 8);
|
||||
writeUint32(bytes, 8 + data.length, crc32(bytes.subarray(4, 8 + data.length)));
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function pngHeader(width: number, height: number) {
|
||||
const header = new Uint8Array(13);
|
||||
writeUint32(header, 0, width);
|
||||
writeUint32(header, 4, height);
|
||||
header[8] = 8; // bit depth
|
||||
header[9] = 6; // truecolour with alpha
|
||||
return header;
|
||||
}
|
||||
|
||||
function filteredRows(strip: RgbaStrip, width: number) {
|
||||
const rowBytes = width * 4;
|
||||
const filteredRowBytes = rowBytes + 1;
|
||||
const output = new Uint8Array(filteredRowBytes * strip.height);
|
||||
for (let row = 0; row < strip.height; row += 1) {
|
||||
const outputStart = row * filteredRowBytes;
|
||||
output[outputStart] = 0; // PNG filter None
|
||||
output.set(strip.data.subarray(row * rowBytes, (row + 1) * rowBytes), outputStart + 1);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function validateDimensions(width: number, height: number) {
|
||||
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width <= 0 || height <= 0) {
|
||||
throw new Error('报告尺寸无效,无法生成长图。');
|
||||
}
|
||||
if (width > MAX_REPORT_WIDTH || width * height > MAX_REPORT_PIXELS) {
|
||||
throw new Error('报告过长,超过单张清晰长图的安全尺寸上限。请缩小报告范围后重试。');
|
||||
}
|
||||
}
|
||||
|
||||
function cancelledError() {
|
||||
return new Error('已取消长图准备。');
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode ordered RGBA strips into one PNG without allocating a full-height
|
||||
* canvas or uncompressed image buffer. The compressed IDAT stream is framed
|
||||
* into ordinary PNG chunks as it arrives.
|
||||
*/
|
||||
export async function encodeRgbaStripsToPng(
|
||||
width: number,
|
||||
height: number,
|
||||
strips: AsyncIterable<RgbaStrip>,
|
||||
cancelled: () => boolean = () => false,
|
||||
): Promise<Blob> {
|
||||
validateDimensions(width, height);
|
||||
const checkCancelled = () => { if (cancelled()) throw cancelledError(); };
|
||||
checkCancelled();
|
||||
if (typeof CompressionStream === 'undefined') {
|
||||
throw new Error('当前浏览器不支持分段长图编码,请更新浏览器后重试。');
|
||||
}
|
||||
|
||||
const stream = new CompressionStream('deflate');
|
||||
const writer = stream.writable.getWriter();
|
||||
const reader = stream.readable.getReader();
|
||||
const parts: BlobPart[] = [PNG_SIGNATURE, pngChunk('IHDR', pngHeader(width, height))];
|
||||
let pendingIdat = new Uint8Array(IDAT_CHUNK_SIZE);
|
||||
let pendingLength = 0;
|
||||
const flushIdat = () => {
|
||||
if (pendingLength === 0) return;
|
||||
parts.push(pngChunk('IDAT', pendingIdat.slice(0, pendingLength)));
|
||||
pendingIdat = new Uint8Array(IDAT_CHUNK_SIZE);
|
||||
pendingLength = 0;
|
||||
};
|
||||
const consumeCompressed = (async () => {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
let offset = 0;
|
||||
while (offset < value.length) {
|
||||
const copied = Math.min(IDAT_CHUNK_SIZE - pendingLength, value.length - offset);
|
||||
pendingIdat.set(value.subarray(offset, offset + copied), pendingLength);
|
||||
pendingLength += copied;
|
||||
offset += copied;
|
||||
if (pendingLength === IDAT_CHUNK_SIZE) flushIdat();
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
try {
|
||||
let expectedY = 0;
|
||||
for await (const strip of strips) {
|
||||
checkCancelled();
|
||||
if (!Number.isSafeInteger(strip.y) || !Number.isSafeInteger(strip.height)
|
||||
|| strip.height <= 0 || strip.y !== expectedY
|
||||
|| strip.data.byteLength !== width * strip.height * 4) {
|
||||
throw new Error('报告长图条带数据不连续或尺寸无效。');
|
||||
}
|
||||
if (strip.y + strip.height > height) throw new Error('报告长图条带超出图像范围。');
|
||||
await writer.write(filteredRows(strip, width));
|
||||
expectedY += strip.height;
|
||||
}
|
||||
checkCancelled();
|
||||
if (expectedY !== height) throw new Error('报告长图内容未完整栅格化。');
|
||||
await writer.close();
|
||||
await consumeCompressed;
|
||||
flushIdat();
|
||||
parts.push(pngChunk('IEND', new Uint8Array()));
|
||||
checkCancelled();
|
||||
return new Blob(parts, { type: 'image/png' });
|
||||
} catch (error) {
|
||||
try { await writer.abort(error); } catch { /* stream may already be closed */ }
|
||||
try { await reader.cancel(error); } catch { /* stream may already be closed */ }
|
||||
try { await consumeCompressed; } catch { /* preserve the original error */ }
|
||||
throw error;
|
||||
} finally {
|
||||
writer.releaseLock();
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
export const reportLongImagePixelLimit = MAX_REPORT_PIXELS;
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { AnalysisNarrativeModel } from './analysisReportModel.ts';
|
||||
|
||||
export type AnalysisReportMode = 'summary' | 'full';
|
||||
|
||||
/** Select complete, already-evidenced sections; never shorten sentences or calculate new values. */
|
||||
export function selectAnalysisReport(model: AnalysisNarrativeModel, mode: AnalysisReportMode): AnalysisNarrativeModel {
|
||||
if (mode === 'full') return model;
|
||||
const hasFocus = model.sections.some(section => section.focusProducts?.length);
|
||||
const selected = model.sections.filter(section => ['overview', 'stage', 'action', 'other'].includes(section.kind)
|
||||
|| section.focusProducts?.length || section.kind === 'product' && !hasFocus);
|
||||
// Free-form/historical reports have no safe summary contract. Keep their complete content.
|
||||
const retained = selected.some(section => section.markdown || section.focusProducts?.length) ? selected : model.sections;
|
||||
const sections = retained.map(section => {
|
||||
if (!section.focusProducts?.length) return section;
|
||||
const focusRefs = new Set(section.focusProducts.flatMap(row => row.evidenceRefs));
|
||||
const related = model.sections.filter(item => item.kind === 'product' && !retained.includes(item))
|
||||
.flatMap(item => item.visuals).filter(visual => visual.evidenceRefs.some(ref => focusRefs.has(ref)));
|
||||
const visuals = [...section.visuals, ...related].filter((visual, index, list) => list.findIndex(item => item.id === visual.id) === index);
|
||||
return { ...section, visuals };
|
||||
});
|
||||
const refs = new Set(sections.flatMap(section => [...section.evidenceRefs,
|
||||
...section.visuals.flatMap(visual => visual.evidenceRefs),
|
||||
...(section.focusProducts || []).flatMap(row => row.evidenceRefs)]));
|
||||
return { ...model, sections, evidence: model.evidence.filter(item => refs.has(item.ref)) };
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { sanitizeAnalysisDisplayText } from './analysisDisplayText.ts';
|
||||
|
||||
const cleanTitle = (value: unknown): string => {
|
||||
if (typeof value !== 'string') return '';
|
||||
const cleaned = sanitizeAnalysisDisplayText(value)
|
||||
.replace(/^\s*#{1,6}\s*/, '')
|
||||
.replace(/^\s*(?:\*\*|__|`+)(.+?)(?:\*\*|__|`+)\s*$/, '$1')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
if (!cleaned) return '';
|
||||
return cleaned.length > 100 ? `${cleaned.slice(0, 99).trimEnd()}…` : cleaned;
|
||||
};
|
||||
|
||||
function headingLineIndex(lines: string[]): number {
|
||||
let fence = '';
|
||||
for (let index = 0; index < lines.length; index += 1) {
|
||||
const line = lines[index];
|
||||
const marker = line.match(/^ {0,3}(`{3,}|~{3,})/);
|
||||
if (marker) {
|
||||
const token = marker[1][0];
|
||||
if (!fence) fence = token;
|
||||
else if (fence === token) fence = '';
|
||||
continue;
|
||||
}
|
||||
if (!fence && /^ {0,3}#(?!#)\s+\S/.test(line)) return index;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function h1Text(line: string): string {
|
||||
return line.replace(/^ {0,3}#\s+/, '').replace(/\s+#+\s*$/, '').trim();
|
||||
}
|
||||
|
||||
function comparable(value: string): string {
|
||||
return cleanTitle(value).replace(/\s+/g, '').toLocaleLowerCase();
|
||||
}
|
||||
|
||||
export function firstMarkdownH1(markdown: string): string {
|
||||
const lines = markdown.replace(/^\uFEFF/, '').split(/\r?\n/);
|
||||
const index = headingLineIndex(lines);
|
||||
return index < 0 ? '' : cleanTitle(h1Text(lines[index]));
|
||||
}
|
||||
|
||||
export function stripDuplicateFirstMarkdownH1(markdown: string, title: string): string {
|
||||
const lines = markdown.replace(/^\uFEFF/, '').split(/\r?\n/);
|
||||
const index = headingLineIndex(lines);
|
||||
if (index < 0 || !comparable(h1Text(lines[index])) || comparable(h1Text(lines[index])) !== comparable(title)) return markdown;
|
||||
lines.splice(index, 1);
|
||||
if (lines[index] === '') lines.splice(index, 1);
|
||||
return lines.join('\n').replace(/^\n+/, '');
|
||||
}
|
||||
|
||||
function specificScopeLabel(scope: string): string {
|
||||
const match = scope.match(/(?:产品|产业部|业务分组|项目组):([^·]+)/);
|
||||
if (match?.[1]) return cleanTitle(match[1]);
|
||||
const candidates = scope.split(/\s*[·|]\s*/).filter(part => part
|
||||
&& !/^(?:\d{4}|对比\s*\d{4}|当前授权范围|含未分类|不含未分类)/.test(part));
|
||||
return cleanTitle(candidates.at(-1) || '');
|
||||
}
|
||||
|
||||
/** Titles come from the answer or its Markdown heading, never from the user's prompt/session name. */
|
||||
export function resolveAnalysisReportTitle(
|
||||
resultTitle: unknown,
|
||||
turnTitle: unknown,
|
||||
reportMarkdown: string,
|
||||
period: string,
|
||||
scope: string,
|
||||
): string {
|
||||
const generated = cleanTitle(resultTitle) || cleanTitle(turnTitle);
|
||||
if (generated) return generated;
|
||||
const legacyHeading = firstMarkdownH1(reportMarkdown);
|
||||
if (legacyHeading) return legacyHeading;
|
||||
|
||||
const periodLabel = cleanTitle(period)
|
||||
|| cleanTitle(scope.split(/\s*[·|]\s*/).find(part => /^(?:19|20)\d{2}/.test(part)) || '');
|
||||
const scopeLabel = specificScopeLabel(scope);
|
||||
const anchor = [periodLabel, scopeLabel].filter(Boolean).join(' · ');
|
||||
return cleanTitle(anchor ? `${anchor}质量分析报告` : '质量分析报告');
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { parseAnalysisVisuals, analysisExclusionSummary, columnFilterSummary, isValidAnalysisExclusions } from './analysisVisualsModel.ts';
|
||||
import { analysisPeriodLabel, hasAnalysisPeriodFields } from './analysisPeriodModel.ts';
|
||||
|
||||
type Data = Record<string, unknown>;
|
||||
const record = (value: unknown): Data => value && typeof value === 'object' && !Array.isArray(value) ? value as Data : {};
|
||||
const meaningful = (value: unknown) => value !== undefined && value !== null && value !== '';
|
||||
const SCOPE_KEYS = ['department', 'group', 'product', 'productSearch', 'projectGroup', 'stage', 'includeUnassigned', 'extraFilters', 'columnFilters', 'exclusions'];
|
||||
const BINDING_KEYS = ['year', 'month', 'quarter', 'monthStart', 'monthEnd', 'period', ...SCOPE_KEYS];
|
||||
const canonical = (value: unknown): string => Array.isArray(value) ? JSON.stringify(value)
|
||||
: value && typeof value === 'object' ? JSON.stringify(Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)]))) : JSON.stringify(value);
|
||||
|
||||
export function analysisPeriodText(value: unknown): string {
|
||||
const period = record(value);
|
||||
if (hasAnalysisPeriodFields(period)) return analysisPeriodLabel(period, 2000, 2200);
|
||||
if (typeof period.label === 'string' && period.label.trim()) return period.label.trim();
|
||||
if (typeof period.start === 'string' && typeof period.end === 'string') return `${period.start}—${period.end}`;
|
||||
return '';
|
||||
}
|
||||
|
||||
function scopeValue(value: unknown): string {
|
||||
if (Array.isArray(value)) return value.filter(item => typeof item === 'string' || typeof item === 'number').join('、');
|
||||
if (typeof value !== 'string' && typeof value !== 'number') return '';
|
||||
const text = String(value);
|
||||
if (text.startsWith('[')) {
|
||||
try { const values: unknown = JSON.parse(text); if (Array.isArray(values)) return scopeValue(values); } catch { /* retain the bound label */ }
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/** A native turn may only save its release in the plan. Use an unambiguous
|
||||
* broadest chart binding, never a local product investigation or a mixture. */
|
||||
function visualBinding(turn: Data, result: Data): Data | undefined {
|
||||
const turnId = String(turn.id || turn.turnId || result.turnId || '');
|
||||
const visuals = parseAnalysisVisuals(turn.visuals || result.visuals).visuals
|
||||
.filter(visual => !turnId || !visual.originTurnId || visual.originTurnId === turnId);
|
||||
if (!visuals.length) return undefined;
|
||||
const depth = (scope: Data) => ['department', 'group', 'product', 'productSearch', 'projectGroup', 'stage', 'category', 'defect', 'extraFilters', 'exclusions'].filter(key => meaningful(scope[key])).length;
|
||||
const bindings = visuals.map(visual => ({ ...visual.scope, ...(visual.stage ? { stage: visual.stage } : {}), period: visual.period,
|
||||
...(visual.comparisonPeriod ? { comparisonPeriod: visual.comparisonPeriod } : {}) }));
|
||||
const shallowest = Math.min(...bindings.map(depth));
|
||||
const roots = bindings.filter(binding => depth(binding) === shallowest);
|
||||
const signature = (binding: Data) => canonical(binding);
|
||||
if (new Set(roots.map(signature)).size === 1) return roots[0];
|
||||
const stages = new Set(roots.map(binding => binding.stage));
|
||||
const withoutStage = (binding: Data) => Object.fromEntries(Object.entries(binding).filter(([key]) => key !== 'stage'));
|
||||
if (stages.size === 2 && stages.has('black') && stages.has('bright')
|
||||
&& new Set(roots.map(binding => signature(withoutStage(binding)))).size === 1) {
|
||||
return { ...withoutStage(roots[0]), stage: 'all' };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Display server-bound fields only. Never infer filters from question prose,
|
||||
* or reuse the mutable current session context for an older turn. */
|
||||
export function analysisScopeText(turn: Data): string {
|
||||
const result = record(turn.result), plan = record(turn.plan || result.plan);
|
||||
const contexts = [record(plan.context), record(plan.frozenContext), record(result.context), record(turn.context)];
|
||||
const context = contexts.find(value => BINDING_KEYS.some(key => meaningful(value[key])));
|
||||
const visual = visualBinding(turn, result);
|
||||
const visualContext = visual ? { ...visual, ...record(visual.period) } : undefined;
|
||||
const compatible = context && visualContext && BINDING_KEYS.filter(key => meaningful(context[key]))
|
||||
.every(key => key === 'stage' && ['all', 'combined'].includes(String(context.stage)) && !meaningful(visualContext.stage)
|
||||
|| canonical(context[key]) === canonical(visualContext[key]));
|
||||
const binding = compatible ? { ...context, ...visual } : context || visual;
|
||||
if (!binding) return '';
|
||||
if (meaningful(binding.exclusions) && !isValidAnalysisExclusions(binding.exclusions)) return '';
|
||||
const semantic = record(plan.semantic);
|
||||
const period = analysisPeriodText(binding.period || binding);
|
||||
// Legacy semantic plans store a comparison query in priorContext only when
|
||||
// compare is explicitly true; an unmarked previous context is not evidence.
|
||||
const comparison = analysisPeriodText(binding.comparisonPeriod || (context && semantic.compare === true ? semantic.priorContext : undefined));
|
||||
const parts = [period, comparison ? `对比 ${comparison}` : ''];
|
||||
const labels: Record<string, string> = { department: '产业部', group: '业务分组', product: '产品', productSearch: '产品检索', projectGroup: '项目组' };
|
||||
for (const [key, label] of Object.entries(labels)) {
|
||||
const value = scopeValue(binding[key]);
|
||||
if (value) parts.push(`${label}:${value}`);
|
||||
}
|
||||
if (!Object.keys(labels).some(key => meaningful(binding[key])) && (visual === binding || compatible || binding.view === 'overall')) parts.push('当前授权范围');
|
||||
const stage = binding.stage;
|
||||
if (stage === 'black') parts.push('黑片');
|
||||
if (stage === 'bright') parts.push('亮片');
|
||||
if (stage === 'all' || stage === 'combined') parts.push('黑片与亮片');
|
||||
if (binding.includeUnassigned === true) parts.push('含未分类');
|
||||
if (binding.includeUnassigned === false) parts.push('不含未分类');
|
||||
const filters = record(binding.extraFilters);
|
||||
for (const [key, value] of Object.entries(filters)) {
|
||||
const text = scopeValue(value);
|
||||
if (text) parts.push(`${key}:${text}`);
|
||||
}
|
||||
parts.push(...analysisExclusionSummary(binding.exclusions));
|
||||
parts.push(...columnFilterSummary(binding.columnFilters, binding.columnLabels || record(plan.task).sourceFieldLabels));
|
||||
return parts.filter(Boolean).join(' · ');
|
||||
}
|
||||
|
||||
export function restoredAnalysisDraft(draft: string, queued: string): string {
|
||||
if (!queued.trim() || queued.trim() === draft.trim()) return draft || queued;
|
||||
return draft.trim() ? `${queued}\n\n${draft}` : queued;
|
||||
}
|
||||
|
||||
export function analysisComposerState(busy: boolean, stopping: boolean, historyLoading: boolean, draft: string, queued: string) {
|
||||
return {
|
||||
showStop: busy,
|
||||
stopDisabled: stopping || historyLoading,
|
||||
sendDisabled: historyLoading || stopping || !draft.trim() || (busy && Boolean(queued)),
|
||||
sendLabel: busy ? '排队发送' : '发送',
|
||||
};
|
||||
}
|
||||
|
||||
/** Re-arm following only after the submitted turn is committed to the DOM.
|
||||
* An observer still looking at the preceding completed turn must not consume it. */
|
||||
export function analysisFollowRequestReady(request: string | null, turn: Data | null): boolean {
|
||||
return Boolean(request && turn?._uiFollowKey === request);
|
||||
}
|
||||
@@ -17,10 +17,24 @@ function canonical(value: unknown): string {
|
||||
|
||||
export function reportSnapshotIdentity(turn: Row): string {
|
||||
const result = analysisSnapshotResult(turn);
|
||||
const value = (key: string, fallback: unknown) => result[key] ?? turn[key] ?? fallback;
|
||||
const value = (key: string, fallback: unknown) => ['readingSummary', 'queryEvidenceRefs'].includes(key)
|
||||
? result[key] ?? fallback : result[key] ?? turn[key] ?? fallback;
|
||||
return canonical({ answer: value('answer', ''), visuals: value('visuals', []),
|
||||
results: value('results', []), reportMarkdown: value('reportMarkdown', ''),
|
||||
reportHtml: value('reportHtml', ''), question: turn.question || '' });
|
||||
reportHtml: value('reportHtml', ''), memberList: value('memberList', null),
|
||||
recordList: value('recordList', null), readingSummary: value('readingSummary', null), queryEvidenceRefs: value('queryEvidenceRefs', []), question: turn.question || '' });
|
||||
}
|
||||
|
||||
export function reportSnapshotDifferences(left: Row, right: Row): string[] {
|
||||
const fields = ['answer', 'visuals', 'results', 'reportMarkdown', 'reportHtml', 'memberList', 'recordList', 'readingSummary', 'queryEvidenceRefs', 'question'];
|
||||
return fields.filter(key => {
|
||||
const value = (turn: Row) => {
|
||||
const result = analysisSnapshotResult(turn);
|
||||
return key === 'question' ? turn.question || '' : ['readingSummary', 'queryEvidenceRefs'].includes(key)
|
||||
? result[key] ?? (key === 'readingSummary' ? null : []) : result[key] ?? turn[key] ?? (key === 'memberList' || key === 'recordList' || key === 'readingSummary' ? null : key === 'visuals' || key === 'results' || key === 'queryEvidenceRefs' ? [] : '');
|
||||
};
|
||||
return canonical(value(left)) !== canonical(value(right));
|
||||
});
|
||||
}
|
||||
|
||||
/** A download rechecks the same stored turn, rather than silently querying new data. */
|
||||
@@ -31,7 +45,9 @@ export async function authorizeAnalysisSnapshot(turn: Row): Promise<void> {
|
||||
if (!['COMPLETED', 'PARTIAL', 'CANCELLED'].includes(String(current.status || '').toUpperCase())) {
|
||||
throw new Error('分析结果仍在更新,请完成后再生成报告。');
|
||||
}
|
||||
if (reportSnapshotIdentity(current) !== reportSnapshotIdentity(turn)) {
|
||||
throw new Error('分析结果或访问权限已变化,请重新打开这条分析后再导出。');
|
||||
const differences = reportSnapshotDifferences(current, turn);
|
||||
if (differences.length) {
|
||||
const labels: Record<string, string> = { answer: '回答', visuals: '图表', results: '查询结果', reportMarkdown: '报告正文', reportHtml: '报告 HTML', memberList: '成员清单', recordList: '原始记录', readingSummary: '核心结论', queryEvidenceRefs: '数据依据', question: '问题' };
|
||||
throw new Error(`分析结果或访问权限已变化(${differences.map(key => labels[key] || key).join('、')}),请重新打开这条分析后再导出。`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
type Context = Record<string, unknown> | undefined;
|
||||
export type SubmissionInput = { sessionId: string; question: string; context?: Context; generation: number };
|
||||
export type AnalysisSubmission = SubmissionInput & {
|
||||
idempotencyKey: string;
|
||||
contextKey: string;
|
||||
inFlight: boolean;
|
||||
turnRequestStarted: boolean;
|
||||
uncertain: boolean;
|
||||
cancelRequested: boolean;
|
||||
acceptedTurnId?: string;
|
||||
};
|
||||
|
||||
function canonical(value: unknown): string {
|
||||
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
|
||||
if (value && typeof value === 'object') return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(',')}}`;
|
||||
return JSON.stringify(value ?? null);
|
||||
}
|
||||
|
||||
/** Only an uncertain retry of the same question, session and frozen context reuses its key. */
|
||||
export function beginAnalysisSubmission(previous: AnalysisSubmission | null, input: SubmissionInput, key: () => string = () => crypto.randomUUID()): AnalysisSubmission {
|
||||
const contextKey = canonical(input.context || {});
|
||||
if (previous?.uncertain && previous.generation === input.generation && previous.sessionId === input.sessionId
|
||||
&& previous.question === input.question && previous.contextKey === contextKey) {
|
||||
previous.inFlight = true;
|
||||
return previous;
|
||||
}
|
||||
return { ...input, contextKey, idempotencyKey: key(), inFlight: true, turnRequestStarted: false, uncertain: false, cancelRequested: false };
|
||||
}
|
||||
|
||||
/** A connection failure, server timeout or 5xx does not prove that a POST was rejected. */
|
||||
export function submissionOutcomeUnknown(error: unknown): boolean {
|
||||
const status = error && typeof error === 'object' && 'status' in error ? Number(error.status) : NaN;
|
||||
return !Number.isFinite(status) || status < 400 || status === 408 || status >= 500;
|
||||
}
|
||||
|
||||
export function requestSubmissionCancellation(attempt: AnalysisSubmission | null, generation: number): boolean {
|
||||
if (!attempt || !attempt.inFlight || attempt.generation !== generation) return false;
|
||||
attempt.cancelRequested = true;
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export function supportsThinkingEffort(model: string | undefined): boolean {
|
||||
return !/^mimo-v2\.6(?:-|$)/i.test(model || '');
|
||||
}
|
||||
|
||||
export function effectiveThinkingEffort(model: string | undefined, effort: string | undefined): string {
|
||||
return supportsThinkingEffort(model) ? effort || 'medium' : 'auto';
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { api } from './api';
|
||||
import { analysisSnapshotResult, reportSnapshotDifferences, reportSnapshotIdentity } from './analysisSnapshot';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
const object = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||
|
||||
export function canRecoverAnalysisVisuals(turn: Row): boolean {
|
||||
const result=analysisSnapshotResult(turn),plan=object(turn.plan),task=object(plan.task);
|
||||
const state=String(result.visualState||'');
|
||||
const status=String(turn.status||result.status||'').toUpperCase();
|
||||
const planned=Array.isArray(task.queryPlan)&&task.queryPlan.some(raw=>{
|
||||
const node=object(raw);return ['ranking','trend','defects'].includes(String(node.purpose))&&node.visualPreference!=='none';
|
||||
});
|
||||
const requested=task.trendRequired===true||task.visualPreference==='required'||Boolean(task.visualType)||planned;
|
||||
return plan.protocolVersion===1&&['metrics','analysis'].includes(String(task.kind))
|
||||
&&['COMPLETED','PARTIAL'].includes(status)&&task.visualPreference!=='none'&&requested
|
||||
&&object(result.visualRecovery).complete!==true&&(state!=='ready'||status==='PARTIAL');
|
||||
}
|
||||
|
||||
/** A late chart recovery can replace only presentation belonging to this exact saved execution. */
|
||||
export function useAnalysisVisualRecovery(source: Row,onUnauthorized:(error:unknown)=>boolean) {
|
||||
const plan=object(source.plan);
|
||||
const key=JSON.stringify([source.id||source.turnId,plan.attemptId,plan.executionId,plan.revision,reportSnapshotIdentity(source)]);
|
||||
const identity=useRef(key);identity.current=key;
|
||||
const generation=useRef(0),pending=useRef(false);
|
||||
const [recovered,setRecovered]=useState<{key:string;turn:Row}|null>(null);
|
||||
const [recovering,setRecovering]=useState(false),[error,setError]=useState('');
|
||||
useEffect(()=>{
|
||||
generation.current++;pending.current=false;setRecovered(null);setRecovering(false);setError('');
|
||||
return()=>{generation.current++;pending.current=false;};
|
||||
},[key]);
|
||||
const recover=useCallback(async()=>{
|
||||
if(pending.current||!canRecoverAnalysisVisuals(source))return;
|
||||
const request=++generation.current,capturedKey=key,id=String(source.id||source.turnId||'');
|
||||
const current=()=>request===generation.current&&capturedKey===identity.current;
|
||||
pending.current=true;setRecovering(true);setError('');
|
||||
try {
|
||||
const value=await api.recoverAnalysisVisuals(id);
|
||||
if(!current())return;
|
||||
const returnedPlan=object(value.plan);
|
||||
if(String(value.id||value.turnId||'')!==id||['attemptId','executionId','revision'].some(field=>returnedPlan[field]!==plan[field])
|
||||
||reportSnapshotDifferences(source,value).some(field=>field!=='visuals'))throw new Error('原分析已变化,请重新打开后再恢复图表。');
|
||||
setRecovered({key:capturedKey,turn:value});
|
||||
} catch(value) {
|
||||
if(current()&&!onUnauthorized(value))setError(value instanceof Error?value.message:'图表暂未恢复,原分析结果已保留。');
|
||||
} finally {
|
||||
if(current()){pending.current=false;setRecovering(false);}
|
||||
}
|
||||
},[source,key,onUnauthorized]);
|
||||
const turn=recovered?.key===key?recovered.turn:source;
|
||||
return {turn,recover,recovering,error,available:canRecoverAnalysisVisuals(turn)};
|
||||
}
|
||||
+215
-41
@@ -1,10 +1,14 @@
|
||||
import type { EChartsCoreOption } from 'echarts/core';
|
||||
import { analysisPeriodLabel, isValidAnalysisPeriodContext, parseAnalysisPeriod } from './analysisPeriodModel.ts';
|
||||
|
||||
export type AnalysisVisualUnit = 'ratio' | 'kg' | 'pp' | 'count';
|
||||
export type AnalysisVisualStage = 'black' | 'bright';
|
||||
export type AnalysisVisualSectionKey = 'overview' | 'stage' | 'department' | 'group' | 'product' | 'category_black' | 'category_bright' | 'defect_black' | 'defect_bright' | 'defect_combined' | 'trend' | 'composition';
|
||||
export type AnalysisVisualDimension = 'department' | 'group' | 'product' | 'category' | 'defect';
|
||||
export type AnalysisVisualContextValue = string | number | boolean | Array<string | number | boolean> | Record<string, string[]>;
|
||||
export type AnalysisExclusionDimension = 'department' | 'group' | 'product' | 'projectGroup';
|
||||
export type AnalysisExclusions = Partial<Record<AnalysisExclusionDimension, string[]>>;
|
||||
export interface SourceColumnFilter { field: string; stages: Array<'black' | 'bright'>; operator: 'in' | 'not_in' | 'is_empty' | 'not_empty'; values?: string[] }
|
||||
export type AnalysisVisualContextValue = string | number | boolean | Array<string | number | boolean> | Record<string, string[]> | Record<string, string> | SourceColumnFilter[] | AnalysisExclusions;
|
||||
export type AnalysisVisualContext = Record<string, AnalysisVisualContextValue>;
|
||||
|
||||
export interface AnalysisVisualSeries {
|
||||
@@ -33,6 +37,7 @@ export interface AnalysisVisual {
|
||||
returnedRows: number;
|
||||
truncated: boolean;
|
||||
shareBasis?: string;
|
||||
denominator?: number;
|
||||
};
|
||||
note?: string;
|
||||
originTurnId: string;
|
||||
@@ -68,14 +73,38 @@ const DIMENSIONS = new Set<AnalysisVisualDimension>(['department', 'group', 'pro
|
||||
const VISUAL_KEYS = new Set(['id', 'type', 'title', 'subtitle', 'unit', 'categories', 'series', 'evidenceRefs', 'requiredFields', 'scope', 'period', 'comparisonPeriod', 'stage', 'metric', 'coverage', 'note', 'originTurnId', 'sectionKey', 'dimension']);
|
||||
const CATEGORY_KEYS = new Set(['key', 'label']);
|
||||
const SERIES_KEYS = new Set(['key', 'label', 'values']);
|
||||
const COVERAGE_KEYS = new Set(['totalRows', 'returnedRows', 'truncated', 'shareBasis']);
|
||||
const COVERAGE_KEYS = new Set(['totalRows', 'returnedRows', 'truncated', 'shareBasis', 'denominator']);
|
||||
const PARSED_VISUALS = new WeakSet<object>();
|
||||
const DONUT_CATEGORY_KEYS: Record<AnalysisVisualStage, Set<string>> = {
|
||||
black: new Set(['black_responsibility_scrap', 'black_material_scrap', 'black_external_scrap']),
|
||||
bright: new Set(['bright_plating_scrap', 'bright_material_scrap', 'bright_processing_scrap', 'bright_diffusion_scrap']),
|
||||
};
|
||||
const SCRAP_RATE_REQUIRED_FIELDS: Record<string, { stage: AnalysisVisualStage; fields: string[] }> = {
|
||||
black_scrap_rate: { stage: 'black', fields: ['black_scrap_weight', 'black_total_weight'] },
|
||||
bright_scrap_rate: { stage: 'bright', fields: ['bright_scrap_weight', 'bright_total_weight'] },
|
||||
};
|
||||
const DEFAULT_COLORS = ['#607ae1', '#008f7d', '#d58c35', '#8b68c5'];
|
||||
|
||||
function isScrapRateMetric(metric: string): boolean {
|
||||
return Object.hasOwn(SCRAP_RATE_REQUIRED_FIELDS, metric);
|
||||
}
|
||||
|
||||
function ratioAxisMax(visual: AnalysisVisual): number | undefined {
|
||||
if (visual.unit !== 'ratio') return undefined;
|
||||
if (!isScrapRateMetric(visual.metric)) return 100;
|
||||
const highest = Math.max(0, ...visual.series.flatMap(series => series.values.filter((value): value is number => value !== null && Number.isFinite(value))));
|
||||
if (highest <= 1) {
|
||||
if (highest === 0) return 1;
|
||||
const targetPercent = highest * 100 * 1.15;
|
||||
const magnitude = 10 ** Math.floor(Math.log10(targetPercent));
|
||||
const factor = [1, 2, 5, 10].find(value => value * magnitude >= targetPercent) || 10;
|
||||
return Math.min(100, factor * magnitude);
|
||||
}
|
||||
const highestPercent = highest * 100;
|
||||
if (!Number.isFinite(highestPercent)) return undefined;
|
||||
return Math.ceil((highestPercent + Math.max(10, highestPercent * 0.08)) / 10) * 10;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -137,7 +166,7 @@ function copyJsonData(value: unknown, seen = new Set<object>(), budget = { nodes
|
||||
|
||||
function boundedText(value: unknown, maxLength = 200): string | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const text = value.trim();
|
||||
const text = value.trim().replace(/数学/g, '');
|
||||
if (!text || text.length > maxLength) return null;
|
||||
return text;
|
||||
}
|
||||
@@ -153,12 +182,50 @@ function safeTextList(value: unknown, maxItems = 40): string[] | null {
|
||||
return list;
|
||||
}
|
||||
|
||||
function safeExclusions(value: unknown): AnalysisExclusions | null {
|
||||
if (!isRecord(value) || Object.keys(value).length > 4) return null;
|
||||
const result: AnalysisExclusions = {};
|
||||
for (const [dimension, rawValues] of Object.entries(value)) {
|
||||
if (!['department', 'group', 'product', 'projectGroup'].includes(dimension)
|
||||
|| !Array.isArray(rawValues) || rawValues.length < 1 || rawValues.length > 50
|
||||
|| rawValues.some(item => typeof item !== 'string' || !item.trim() || item.length > 256)) return null;
|
||||
Object.defineProperty(result, dimension, { value: [...rawValues], enumerable: true, configurable: true, writable: true });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function isValidAnalysisExclusions(value: unknown): boolean {
|
||||
return safeExclusions(value) !== null;
|
||||
}
|
||||
|
||||
function safeContext(value: unknown): AnalysisVisualContext | null {
|
||||
if (!isRecord(value) || Object.keys(value).length > 32) return null;
|
||||
const result: AnalysisVisualContext = {};
|
||||
for (const [key, raw] of Object.entries(value)) {
|
||||
if (!/^[\w.-]{1,64}$/.test(key)) return null;
|
||||
if (key === 'extraFilters') {
|
||||
if (key === 'exclusions') {
|
||||
const exclusions = safeExclusions(raw);
|
||||
if (!exclusions) return null;
|
||||
Object.defineProperty(result, key, { value: exclusions, enumerable: true, configurable: true, writable: true });
|
||||
} else if (key === 'columnFilters') {
|
||||
if (!Array.isArray(raw) || raw.length > 20) return null;
|
||||
const filters: SourceColumnFilter[] = [];
|
||||
for (const rule of raw) {
|
||||
if (!isRecord(rule) || Object.keys(rule).some(key => !['field', 'stages', 'operator', 'values'].includes(key))
|
||||
|| typeof rule.field !== 'string' || !/^[A-Za-z0-9_]{1,64}$/.test(rule.field)
|
||||
|| !Array.isArray(rule.stages) || !rule.stages.length || rule.stages.length > 2 || new Set(rule.stages).size !== rule.stages.length
|
||||
|| rule.stages.some(stage => stage !== 'black' && stage !== 'bright')
|
||||
|| !['in', 'not_in', 'is_empty', 'not_empty'].includes(String(rule.operator))) return null;
|
||||
const needsValues = rule.operator === 'in' || rule.operator === 'not_in';
|
||||
if (needsValues && (!Array.isArray(rule.values) || !rule.values.length || rule.values.length > 50 || rule.values.some(value => typeof value !== 'string' || !value.trim() || value.length > 256))) return null;
|
||||
if (!needsValues && rule.values !== undefined) return null;
|
||||
filters.push({ field: rule.field, stages: [...rule.stages] as SourceColumnFilter['stages'], operator: rule.operator as SourceColumnFilter['operator'], ...(needsValues ? { values: [...rule.values as string[]] } : {}) });
|
||||
}
|
||||
result[key] = filters;
|
||||
} else if (key === 'columnLabels') {
|
||||
if (!isRecord(raw) || Object.keys(raw).length > 25 || Object.entries(raw).some(([name, label]) => !/^[A-Za-z0-9_]{1,64}$/.test(name) || typeof label !== 'string' || label.length > 160)) return null;
|
||||
result[key] = Object.fromEntries(Object.entries(raw)) as Record<string, string>;
|
||||
} else if (key === 'extraFilters') {
|
||||
if (!isRecord(raw) || Object.keys(raw).length > 20) return null;
|
||||
const filters: Record<string, string[]> = {};
|
||||
for (const [filterKey, filterValues] of Object.entries(raw)) {
|
||||
@@ -208,11 +275,13 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
|
||||
&& Number(coverage.returnedRows) <= Number(coverage.totalRows)
|
||||
&& typeof coverage.truncated === 'boolean'
|
||||
&& (coverage.shareBasis === undefined || boundedText(coverage.shareBasis, 128) !== null)
|
||||
&& (coverage.denominator === undefined || typeof coverage.denominator === 'number' && Number.isFinite(coverage.denominator) && coverage.denominator > 0 && coverage.shareBasis === 'all_scope_weight')
|
||||
? {
|
||||
totalRows: Number(coverage.totalRows),
|
||||
returnedRows: Number(coverage.returnedRows),
|
||||
truncated: coverage.truncated,
|
||||
...(coverage.shareBasis === undefined ? {} : { shareBasis: String(coverage.shareBasis) }),
|
||||
...(coverage.denominator === undefined ? {} : { denominator: Number(coverage.denominator) }),
|
||||
}
|
||||
: null;
|
||||
|
||||
@@ -247,7 +316,7 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
|
||||
invalidValueCells.push(`${seriesIndex}:${valueIndex}`);
|
||||
return null;
|
||||
}
|
||||
if (unit === 'ratio' && (item < 0 || item > 1)) invalidValueCells.push(`${seriesIndex}:${valueIndex}`);
|
||||
if (unit === 'ratio' && (item < 0 || (!isScrapRateMetric(metric || '') && item > 1))) invalidValueCells.push(`${seriesIndex}:${valueIndex}`);
|
||||
return item;
|
||||
});
|
||||
series.push({ key, label, values });
|
||||
@@ -256,7 +325,8 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
|
||||
const validSeries = !!rawSeries && !!validCategories && series.length === rawSeries.length;
|
||||
|
||||
const valid = !!id && !!type && !!title && subtitle !== null && UNIT_VALUES.has(unit as AnalysisVisualUnit)
|
||||
&& !!metric && !!originTurnId && !!scope && !!period && (value.comparisonPeriod === undefined || !!comparisonPeriod)
|
||||
&& !!metric && !!originTurnId && !!scope && isValidAnalysisPeriodContext(scope)
|
||||
&& !!period && isValidAnalysisPeriodContext(period) && (value.comparisonPeriod === undefined || !!comparisonPeriod && isValidAnalysisPeriodContext(comparisonPeriod))
|
||||
&& !!evidenceRefs && !!requiredFields && (value.note === undefined || note !== null)
|
||||
&& (stage === undefined || stage === 'black' || stage === 'bright')
|
||||
&& (sectionKey === undefined || SECTION_KEYS.has(sectionKey as AnalysisVisualSectionKey))
|
||||
@@ -297,12 +367,20 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
|
||||
}
|
||||
|
||||
function visualSemanticIssue(visual: AnalysisVisual): string | undefined {
|
||||
const scrapRate = SCRAP_RATE_REQUIRED_FIELDS[visual.metric];
|
||||
if (scrapRate) {
|
||||
if (visual.unit !== 'ratio') return '阶段报废率必须使用比例单位';
|
||||
if (visual.requiredFields.length !== scrapRate.fields.length || new Set(visual.requiredFields).size !== scrapRate.fields.length
|
||||
|| scrapRate.fields.some(field => !visual.requiredFields.includes(field))) return '阶段报废率缺少对应重量字段权限';
|
||||
if ((visual.stage !== undefined && visual.stage !== scrapRate.stage)
|
||||
|| (visual.scope.stage !== undefined && visual.scope.stage !== scrapRate.stage)) return '报废率阶段与查询范围不一致';
|
||||
}
|
||||
if (visual.type === 'area' && visual.series.length !== 1) return '面积趋势图仅支持单一序列';
|
||||
if (visual.type === 'area' && visual.series.some(series => series.values.some(value => value !== null && value < 0))) return '面积趋势图不支持负值';
|
||||
if (visual.type === 'waterfall') {
|
||||
const allowedFields = new Set(['black_good_weight', 'black_total_weight', 'bright_good_weight', 'bright_total_weight']);
|
||||
const actualFields = visual.requiredFields;
|
||||
if (visual.metric !== 'composite_impact_pp' || visual.unit !== 'pp') return '瀑布图仅支持综合率阶段数学影响(百分点)';
|
||||
if (visual.metric !== 'composite_impact_pp' || visual.unit !== 'pp') return '瀑布图仅支持综合率阶段影响(百分点)';
|
||||
if (visual.categories.length !== 3 || visual.categories.map(item => item.key).join('|') !== 'black|bright|total') return '瀑布图类别必须依次为黑片、亮片和综合变化';
|
||||
if (visual.series.length !== 1 || visual.series[0].key !== 'composite_impact_pp') return '瀑布图仅支持综合阶段影响序列';
|
||||
if (actualFields.length !== allowedFields.size || new Set(actualFields).size !== allowedFields.size || actualFields.some(field => !allowedFields.has(field))) {
|
||||
@@ -322,6 +400,18 @@ function visualSemanticIssue(visual: AnalysisVisual): string | undefined {
|
||||
}
|
||||
if (visual.type !== 'donut' && visual.type !== 'pareto') return undefined;
|
||||
const chartName = visual.type === 'donut' ? '环形图' : '柏拉图';
|
||||
if (visual.type === 'pareto' && visual.coverage.shareBasis === 'all_scope_weight') {
|
||||
const values = visual.series[0]?.values || [];
|
||||
const total = visual.coverage.denominator;
|
||||
if (visual.unit !== 'kg' || !/^(?:black|bright)_(?:total|scrap)_weight$/.test(visual.metric)
|
||||
|| !visual.stage || !visual.metric.startsWith(`${visual.stage}_`) || visual.comparisonPeriod
|
||||
|| !['product','department','group'].includes(visual.dimension || '')
|
||||
|| visual.categories.length < 1 || visual.categories.length > 10 || visual.series.length !== 1
|
||||
|| visual.coverage.returnedRows !== visual.categories.length || typeof total !== 'number' || !(total > 0)
|
||||
|| values.some((v,i) => v === null || !Number.isFinite(v) || v < 0 || i > 0 && v > (values[i-1] as number))) return '分组重量柏拉图缺少全范围总量或有效排名';
|
||||
if (values.reduce<number>((sum,v)=>sum+(v as number),0) > total + Math.max(0.00001,total*1e-10)) return 'Top重量不能大于全范围总量';
|
||||
return undefined;
|
||||
}
|
||||
if (visual.unit !== 'kg' || visual.metric !== 'source_defect_weight') return `${chartName}仅支持来源类别重量`;
|
||||
if (visual.stage !== 'black' && visual.stage !== 'bright') return `${chartName}必须明确黑片或亮片阶段`;
|
||||
if (visual.scope.stage !== undefined && visual.scope.stage !== visual.stage) return `${chartName}阶段与查询范围不一致`;
|
||||
@@ -479,6 +569,12 @@ function formatChartValue(value: number | null, unit: AnalysisVisualUnit, showPo
|
||||
return unit === 'kg' ? `${signed} kg` : unit === 'pp' ? `${signed} pp` : signed;
|
||||
}
|
||||
|
||||
|
||||
function paretoWeightLabel(value: number | null, allScopeWeight: boolean): string {
|
||||
const text = formatChartValue(value, 'kg');
|
||||
return allScopeWeight ? text.replace(/ kg$/, '') : text;
|
||||
}
|
||||
|
||||
export function visualCategoryLabel(visual: AnalysisVisual, categoryIndex: number): string {
|
||||
const category = visual.categories[categoryIndex];
|
||||
if (!category) return '';
|
||||
@@ -514,7 +610,8 @@ export function visualParetoPoints(visual: AnalysisVisual): AnalysisVisualPareto
|
||||
if (visual.type !== 'pareto' || visualSemanticIssue(visual)) return [];
|
||||
const values = visual.series[0]?.values;
|
||||
if (!values) return [];
|
||||
const total = values.reduce<number>((sum, value) => sum + (value as number), 0);
|
||||
const fullPopulation = visual.coverage.shareBasis === 'all_scope_weight';
|
||||
const total = fullPopulation ? visual.coverage.denominator! : values.reduce<number>((sum, value) => sum + (value as number), 0);
|
||||
let cumulative = 0;
|
||||
return values.map((value, categoryIndex) => {
|
||||
cumulative += value as number;
|
||||
@@ -522,7 +619,7 @@ export function visualParetoPoints(visual: AnalysisVisual): AnalysisVisualPareto
|
||||
categoryIndex,
|
||||
valueKg: value as number,
|
||||
share: (value as number) / total,
|
||||
cumulativeShare: categoryIndex === values.length - 1 ? 1 : cumulative / total,
|
||||
cumulativeShare: !fullPopulation && categoryIndex === values.length - 1 ? 1 : cumulative / total,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -582,8 +679,8 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
return [
|
||||
plainRichText(visualCategoryLabel(visual, dataIndex)),
|
||||
`${plainRichText(visual.series[0].label)}:${formatVisualValue(point.valueKg, 'kg')}`,
|
||||
`本图类别占比:${visualDonutShareText(point.share)}`,
|
||||
`累计占本图已列类别合计:${visualDonutShareText(point.cumulativeShare)}`,
|
||||
`${visual.coverage.shareBasis === 'all_scope_weight' ? '占全部重量' : '本图类别占比'}:${visualDonutShareText(point.share)}`,
|
||||
`${visual.coverage.shareBasis === 'all_scope_weight' ? '累计占全部重量' : '累计占本图已列类别合计'}:${visualDonutShareText(point.cumulativeShare)}`,
|
||||
].join('\n');
|
||||
}
|
||||
if (visual.type === 'waterfall') {
|
||||
@@ -592,7 +689,7 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
return [
|
||||
plainRichText(visualCategoryLabel(visual, dataIndex)),
|
||||
plainRichText(`期间:${plainPeriod(visual.comparisonPeriod || {})} → ${plainPeriod(visual.period)}`),
|
||||
`阶段数学影响:${formatVisualValue(value, 'pp')}`,
|
||||
`阶段影响:${formatVisualValue(value, 'pp')}`,
|
||||
...(dataIndex === 2 ? ['黑片与亮片影响之和构成综合率变化。'] : []),
|
||||
'该拆解不代表生产根因。',
|
||||
].join('\n');
|
||||
@@ -738,21 +835,22 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
|
||||
if (visual.type === 'pareto') {
|
||||
const points = visualParetoPoints(visual);
|
||||
const cumulativeName = '累计占本图已列类别合计';
|
||||
const allScopeWeight = visual.coverage.shareBasis === 'all_scope_weight';
|
||||
const cumulativeName = allScopeWeight ? '累计占全部重量' : '累计占本图已列类别合计';
|
||||
return {
|
||||
animation: false,
|
||||
color: [colors[0], '#435d7a'],
|
||||
tooltip: { trigger: 'axis', renderMode: 'richText', backgroundColor: theme.surface || '#ffffff', borderColor: line, textStyle: { color: ink }, axisPointer: { type: 'shadow' }, formatter },
|
||||
legend: { show: true, selectedMode: false, type: 'plain', top: 6, left: 12, data: [plainRichText(visual.series[0].label), cumulativeName], textStyle: { color: mutedInk, fontSize: 10 } },
|
||||
grid: { left: 56, right: 66, top: 36, bottom: 70, containLabel: true },
|
||||
xAxis: { type: 'category', data: categories, axisLabel: { color: ink, fontSize: 10, interval: 0, rotate: categories.length > 3 ? 34 : 0, width: 160, overflow: 'break', hideOverlap: false, lineHeight: 13 }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false } },
|
||||
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: '累计占比', 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) => `${chartNumber(value)}%` }, 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 }) => formatChartValue(points[params.dataIndex]?.valueKg ?? null, 'kg') }, emphasis: { disabled: true } },
|
||||
{ name: cumulativeName, type: 'line', yAxisIndex: 1, data: points.map(point => chartNumber(point.cumulativeShare * 100)), symbol: 'circle', symbolSize: 7, lineStyle: { width: 2.2, color: ink }, itemStyle: { color: ink }, label: { show: true, position: 'top', color: ink, fontSize: 10, formatter: (params: { data?: number }) => visualDonutShareText((params.data || 0) / 100) }, emphasis: { disabled: true } },
|
||||
{ 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 } },
|
||||
{ name: cumulativeName, type: 'line', yAxisIndex: 1, data: points.map(point => chartNumber(point.cumulativeShare * 100)), symbol: 'circle', symbolSize: 7, lineStyle: { width: 2.2, color: ink }, itemStyle: { color: ink }, label: { show: true, position: allScopeWeight ? 'bottom' : 'top', distance: 7, color: ink, fontSize: 10, formatter: (params: { data?: number; dataIndex?: number }) => allScopeWeight && params.dataIndex !== points.length - 1 ? '' : visualDonutShareText((params.data || 0) / 100) }, ...(allScopeWeight ? { labelLayout: { hideOverlap: true } } : {}), emphasis: { disabled: true } },
|
||||
],
|
||||
aria: { enabled: true, decal: { show: false } },
|
||||
};
|
||||
@@ -795,7 +893,7 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
|
||||
const valueAxis = {
|
||||
type: 'value' as const,
|
||||
min: visual.unit === 'ratio' ? 0 : undefined,
|
||||
max: visual.unit === 'ratio' ? 100 : undefined,
|
||||
max: ratioAxisMax(visual),
|
||||
scale: visual.unit !== 'ratio' ? false : undefined,
|
||||
splitNumber: 3,
|
||||
axisLabel: { color: mutedInk, formatter: numberAxisLabel, hideOverlap: true },
|
||||
@@ -848,8 +946,38 @@ function wrapLines(value: string, maxChars: number, maxLines = Number.POSITIVE_I
|
||||
return lines;
|
||||
}
|
||||
|
||||
function unitLabel(unit: AnalysisVisualUnit): string {
|
||||
if (unit === 'ratio') return '合格率(%)';
|
||||
/** Use the same font and column width as the axis so export height includes every rendered line. */
|
||||
function wrapAxisLabel(value: string, width: number, fontSize: number, maxLines = Number.POSITIVE_INFINITY): string[] {
|
||||
const text = plainRichText(value).replace(/\s+/g, ' ').trim();
|
||||
if (!text) return [];
|
||||
let context: CanvasRenderingContext2D | null = null;
|
||||
if (typeof document !== 'undefined') {
|
||||
try { context = document.createElement('canvas').getContext('2d'); } catch { /* Conservative SSR fallback below. */ }
|
||||
}
|
||||
if (context) context.font = `${fontSize}px sans-serif`;
|
||||
const measure = (line: string) => context ? context.measureText(line).width : Array.from(line).length * fontSize;
|
||||
const lines: string[] = [];
|
||||
let line = '';
|
||||
for (const char of Array.from(text)) {
|
||||
if (line && measure(line + char) > width - 2) {
|
||||
lines.push(line);
|
||||
line = '';
|
||||
if (lines.length >= maxLines) {
|
||||
let tail = lines[lines.length - 1];
|
||||
while (tail && measure(tail + '…') > width - 2) tail = Array.from(tail).slice(0, -1).join('');
|
||||
lines[lines.length - 1] = tail + '…';
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
line += char;
|
||||
}
|
||||
if (line) lines.push(line);
|
||||
return lines;
|
||||
}
|
||||
|
||||
export function visualUnitLabel(visual: AnalysisVisual): string {
|
||||
const unit = visual.unit;
|
||||
if (unit === 'ratio') return isScrapRateMetric(visual.metric) ? '报废率(%)' : '合格率(%)';
|
||||
if (unit === 'kg') return '重量(kg)';
|
||||
if (unit === 'pp') return '变化(百分点)';
|
||||
return '数量';
|
||||
@@ -871,14 +999,14 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
visual.subtitle,
|
||||
`期间:${visualPeriodSummary(visual)}`,
|
||||
`范围:${visualScopeSummary(visual.scope) || '按本轮查询条件'}`,
|
||||
`单位:${unitLabel(visual.unit)}`,
|
||||
`单位:${visualUnitLabel(visual)}`,
|
||||
...(visual.stage ? [`阶段:${visual.stage === 'black' ? '黑片' : '亮片'}`] : []),
|
||||
visual.coverage.truncated
|
||||
? `本图展示 ${visual.coverage.returnedRows} / 共 ${visual.coverage.totalRows} 项`
|
||||
: `覆盖:共 ${visual.coverage.totalRows} 项`,
|
||||
...(visual.type === 'donut'
|
||||
? ['占比口径:仅以本图已列类别重量合计为分母;不代表正式总报废占比']
|
||||
: visual.type === 'pareto' ? ['累计占比口径:仅以本图已列类别重量合计为分母;不代表正式总报废累计占比']
|
||||
: visual.type === 'pareto' ? [visual.coverage.shareBasis === 'all_scope_weight' ? '累计占比口径:以同范围全部重量为分母,Top末项可以低于100%' : '累计占比口径:仅以本图已列类别重量合计为分母;不代表正式总报废累计占比']
|
||||
: visual.coverage.shareBasis ? [`占比口径:${visual.coverage.shareBasis}`] : []),
|
||||
].filter(Boolean);
|
||||
const headerLines = headerParts.flatMap(part => wrapLines(part, 96, 4));
|
||||
@@ -886,24 +1014,37 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
const footerParts = [
|
||||
...(!reportMode && visual.type === 'donut' ? visualDonutShares(visual).map(({ categoryIndex, valueKg, share }) =>
|
||||
`${visualCategoryLabel(visual, categoryIndex)}:${formatChartValue(valueKg, 'kg')}(占本图已列类别重量合计 ${visualDonutShareText(share)})`) : []),
|
||||
...(visual.type === 'pareto' ? ['柏拉图累计占比=累计重量÷本图已列类别重量合计;不代表正式总报废累计占比'] : []),
|
||||
...(visual.type === 'waterfall' ? ['阶段影响是对综合合格率变化的数学拆解,不代表生产根因。'] : []),
|
||||
...(visual.type === 'pareto' ? [visual.coverage.shareBasis === 'all_scope_weight' ? '累计占比=所列累计重量÷同范围全部重量;Top未覆盖全量时不补足100%' : '柏拉图累计占比=累计重量÷本图已列类别重量合计;不代表正式总报废累计占比'] : []),
|
||||
...(visual.type === 'waterfall' ? ['阶段影响是对综合合格率变化的拆解,不代表生产根因。'] : []),
|
||||
...(!reportMode && visual.note ? [`说明:${visual.note}`] : []),
|
||||
...(!reportMode && visual.evidenceRefs.length ? [`证据引用:${visual.evidenceRefs.join(' · ')}`] : []),
|
||||
];
|
||||
const footerLines = footerParts.flatMap(part => wrapLines(part, 124));
|
||||
const chartBottom = footerLines.length ? footerLines.length * 15 + (reportMode ? 20 : 28) : (reportMode ? 10 : 24);
|
||||
|
||||
const wrappedCategories = visual.categories.map((_category, index) => wrapLines(visualCategoryLabel(visual, index), 14));
|
||||
const allScopeWeight = visual.type === 'pareto' && visual.coverage.shareBasis === 'all_scope_weight';
|
||||
const rankingLabelWidth = Math.max(16, (width - 174) / Math.max(1, visual.categories.length) - 8);
|
||||
const wrappedCategories = visual.categories.map((_category, index) => allScopeWeight
|
||||
? wrapAxisLabel(visualCategoryLabel(visual, index), rankingLabelWidth, reportMode ? 14 : 10)
|
||||
: wrapLines(visualCategoryLabel(visual, index), 14));
|
||||
const categoryLabelHeight = wrappedCategories.reduce((total, lines) => total + Math.max(28, lines.length * 14 + 8), 0);
|
||||
const maxCategoryLines = Math.max(1, ...wrappedCategories.map(lines => lines.length));
|
||||
const combinedDefects = visual.sectionKey === 'defect_combined' && visual.type === 'bar';
|
||||
const reportCartesian = reportMode && ['column', 'line', 'area'].includes(visual.type);
|
||||
const reportRotation = visual.type === 'column' ? (visual.categories.length > 5 ? 42 : 0)
|
||||
: (visual.categories.length > 12 ? 42 : 0);
|
||||
const reportLabelWidth = Math.min(160, Math.max(1, ...wrappedCategories.flatMap(lines => lines.map(line => Array.from(line).length * 14))));
|
||||
const reportLabelHeight = Math.ceil(Math.sin(reportRotation * Math.PI / 180) * reportLabelWidth
|
||||
+ Math.cos(reportRotation * Math.PI / 180) * maxCategoryLines * 18) + 22;
|
||||
const reportLegendHeight = visual.series.length > 1 ? 30 : 0;
|
||||
const reportPlotHeight = 230;
|
||||
const chartHeight = visual.type === 'donut' ? (reportMode ? Math.max(390, 290 + maxCategoryLines * 20) : Math.max(600, 300 + maxCategoryLines * 20))
|
||||
: visual.type === 'waterfall' ? (reportMode ? 300 : 480)
|
||||
: visual.type === 'heatmap' ? Math.max(reportMode ? 180 : 240, visual.series.length * (reportMode ? 62 : 90))
|
||||
: visual.type === 'pareto' ? (reportMode ? Math.max(300, 170 + maxCategoryLines * 18) : Math.max(480, categoryLabelHeight))
|
||||
: visual.type === 'pareto' ? (allScopeWeight ? 330 + maxCategoryLines * (reportMode ? 18 : 14) : reportMode ? Math.max(300, 170 + maxCategoryLines * 18) : Math.max(480, categoryLabelHeight))
|
||||
: combinedDefects ? Math.max(reportMode ? 350 : 410, visual.categories.length * (reportMode ? 42 : 46))
|
||||
: reportMode ? visual.type === 'bar' ? Math.max(230, categoryLabelHeight * 1.3) : Math.max(230, 165 + maxCategoryLines * 20) : Math.max(480, categoryLabelHeight);
|
||||
: reportCartesian ? reportPlotHeight + reportLabelHeight + reportLegendHeight
|
||||
: reportMode ? visual.type === 'bar' ? Math.max(230, categoryLabelHeight * 1.3) : Math.max(230, 165 + maxCategoryLines * 20) : Math.max(480, categoryLabelHeight);
|
||||
const height = chartTop + chartHeight + chartBottom;
|
||||
const base = buildAnalysisVisualOption(visual, { ink: '#263c5a', mutedInk: '#65748b', line: '#dfe5ef', surface: '#ffffff' });
|
||||
const categories = wrappedCategories.map(lines => lines.join('\n'));
|
||||
@@ -934,7 +1075,7 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
type: 'plain' as const,
|
||||
top: reportMode ? chartTop + 2 : chartTop - 26,
|
||||
left: 56,
|
||||
data: [plainRichText(visual.series[0].label), '累计占本图已列类别合计'],
|
||||
data: [plainRichText(visual.series[0].label), allScopeWeight ? '累计占全部重量' : '累计占本图已列类别合计'],
|
||||
textStyle: { color: '#65748b', fontSize: 11 },
|
||||
}
|
||||
: {
|
||||
@@ -1024,19 +1165,19 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
}
|
||||
: visual.type === 'pareto'
|
||||
? {
|
||||
grid: { left: 78, right: 78, top: chartTop, bottom: chartBottom + 96, containLabel: true },
|
||||
grid: allScopeWeight ? { left: 78, right: 96, top: chartTop + 48, height: 260, containLabel: false } : { left: 78, right: 78, top: chartTop, bottom: chartBottom + 96, containLabel: true },
|
||||
xAxis: {
|
||||
type: 'category', data: categories, boundaryGap: true,
|
||||
axisLabel: { color: '#263c5a', fontSize: 10, lineHeight: 12, rotate: categories.length > 3 ? 20 : 0, width: 190, overflow: 'break', interval: 0 },
|
||||
axisLabel: { color: '#263c5a', fontSize: 10, lineHeight: 12, rotate: allScopeWeight ? 0 : categories.length > 3 ? 20 : 0, width: allScopeWeight ? rankingLabelWidth : 190, overflow: 'break', interval: 0, ...(allScopeWeight ? { fontFamily: 'sans-serif' } : {}) },
|
||||
axisLine: { lineStyle: { color: '#dfe5ef' } }, axisTick: { show: false },
|
||||
},
|
||||
yAxis: [
|
||||
{ type: 'value', min: 0, name: '重量(kg)', nameTextStyle: { color: '#65748b', fontSize: 10 }, axisLabel: { color: '#65748b', formatter: (value: number) => formatChartValue(value, 'kg') }, axisLine: { show: false }, splitLine: { lineStyle: { color: '#dfe5ef', type: 'dashed' } } },
|
||||
{ type: 'value', min: 0, max: 100, position: 'right', name: '累计占比(本图已列类别)', nameTextStyle: { color: '#65748b', fontSize: 10 }, axisLabel: { color: '#65748b', formatter: (value: number) => `${chartNumber(value)}%` }, axisLine: { show: false }, splitLine: { show: false } },
|
||||
{ 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 } },
|
||||
],
|
||||
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 }) => formatChartValue(visualParetoPoints(visual)[params.dataIndex]?.valueKg ?? null, 'kg') } },
|
||||
{ name: '累计占本图已列类别合计', type: 'line', yAxisIndex: 1, data: visualParetoPoints(visual).map(point => chartNumber(point.cumulativeShare * 100)), symbol: 'circle', symbolSize: 7, lineStyle: { width: 2.2, color: '#435d7a' }, itemStyle: { color: '#435d7a' }, label: { show: true, position: 'top', color: '#435d7a', fontSize: 10, formatter: (params: { data?: number }) => visualDonutShareText((params.data || 0) / 100) } },
|
||||
{ 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 } } : {}) },
|
||||
{ name: visual.coverage.shareBasis === 'all_scope_weight' ? '累计占全部重量' : '累计占本图已列类别合计', type: 'line', yAxisIndex: 1, data: visualParetoPoints(visual).map(point => chartNumber(point.cumulativeShare * 100)), symbol: 'circle', symbolSize: 7, lineStyle: { width: 2.2, color: '#435d7a' }, itemStyle: { color: '#435d7a' }, label: { show: true, position: allScopeWeight ? 'bottom' : 'top', distance: 8, color: '#435d7a', fontSize: 10, formatter: (params: { data?: number; dataIndex?: number }) => allScopeWeight && params.dataIndex !== visual.categories.length - 1 ? '' : visualDonutShareText((params.data || 0) / 100) }, ...(allScopeWeight ? { labelLayout: { hideOverlap: true } } : {}) },
|
||||
],
|
||||
}
|
||||
: visual.type === 'waterfall'
|
||||
@@ -1061,7 +1202,7 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
xAxis: {
|
||||
type: 'value',
|
||||
min: visual.unit === 'ratio' ? 0 : undefined,
|
||||
max: visual.unit === 'ratio' ? 100 : undefined,
|
||||
max: ratioAxisMax(visual),
|
||||
scale: visual.unit !== 'ratio' ? false : undefined,
|
||||
axisLabel: { color: '#65748b', formatter: valueAxisLabel },
|
||||
axisLine: { show: false },
|
||||
@@ -1082,20 +1223,24 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
type: 'category',
|
||||
data: categories,
|
||||
boundaryGap: visual.type === 'column',
|
||||
axisLabel: { color: '#263c5a', fontSize: 10, lineHeight: 13, rotate: categories.length > 5 ? 42 : 0, width: 160, overflow: 'break', interval: 0, hideOverlap: false },
|
||||
axisLabel: { color: '#263c5a', fontSize: 10, lineHeight: 13, rotate: reportCartesian ? reportRotation : categories.length > 5 ? 42 : 0, width: 160, overflow: 'break', interval: 0, hideOverlap: false },
|
||||
axisLine: { lineStyle: { color: '#dfe5ef' } },
|
||||
axisTick: { show: false },
|
||||
},
|
||||
yAxis: {
|
||||
type: 'value',
|
||||
min: visual.unit === 'ratio' ? 0 : undefined,
|
||||
max: visual.unit === 'ratio' ? 100 : undefined,
|
||||
max: ratioAxisMax(visual),
|
||||
scale: visual.unit !== 'ratio' ? false : undefined,
|
||||
axisLabel: { color: '#65748b', formatter: valueAxisLabel },
|
||||
axisLine: { show: false },
|
||||
splitLine: { lineStyle: { color: '#dfe5ef', type: 'dashed' } },
|
||||
},
|
||||
grid: { left: 64, right: 42, top: chartTop, bottom: chartBottom + (visual.type === 'column' ? 80 : reportMode ? 110 : 68), containLabel: true },
|
||||
// Keep a real plot rectangle; containLabel may otherwise subtract all available
|
||||
// height for the fixed-width rotated category labels and flatten the series.
|
||||
grid: reportCartesian
|
||||
? { left: 64, right: 42, top: chartTop + reportLegendHeight, height: reportPlotHeight, containLabel: false }
|
||||
: { left: 64, right: 42, top: chartTop, bottom: chartBottom + (visual.type === 'column' ? 80 : 68), containLabel: true },
|
||||
}),
|
||||
};
|
||||
if (reportMode) {
|
||||
@@ -1115,6 +1260,11 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
|
||||
}
|
||||
|
||||
function plainPeriod(period: Record<string, unknown>): string {
|
||||
const numeric = parseAnalysisPeriod(period);
|
||||
if (numeric?.monthStart !== undefined && numeric.monthEnd !== undefined) return analysisPeriodLabel(period);
|
||||
if (numeric?.year && numeric.month !== undefined) return `${numeric.year}-${String(numeric.month).padStart(2, '0')}`;
|
||||
if (numeric?.year && numeric.quarter !== undefined) return `${numeric.year}年第${numeric.quarter}季度`;
|
||||
if (numeric?.year) return `${numeric.year} 年`;
|
||||
const label = typeof period.label === 'string' ? period.label : null;
|
||||
if (label) return label;
|
||||
const start = ['start', 'from', 'startMonth', 'begin'].map(key => period[key]).find(value => typeof value === 'string');
|
||||
@@ -1122,10 +1272,6 @@ function plainPeriod(period: Record<string, unknown>): string {
|
||||
if (typeof start === 'string' && typeof end === 'string') return start === end ? start : `${start} 至 ${end}`;
|
||||
if (typeof start === 'string') return start;
|
||||
if (typeof end === 'string') return end;
|
||||
const year = period.year;
|
||||
const month = period.month;
|
||||
if (typeof year === 'number' && typeof month === 'number') return `${year}-${String(month).padStart(2, '0')}`;
|
||||
if (typeof year === 'number') return `${year} 年`;
|
||||
return '当前期间';
|
||||
}
|
||||
|
||||
@@ -1141,9 +1287,37 @@ export function visualScopeSummary(scope: AnalysisVisual['scope']): string {
|
||||
: value === true ? '是' : Array.isArray(value) ? value.join('、') : String(value)}`);
|
||||
const filters = scope.extraFilters;
|
||||
if (filters && typeof filters === 'object' && !Array.isArray(filters) && Object.keys(filters).length > 0) parts.push(`额外筛选 ${Object.keys(filters).length} 项`);
|
||||
parts.push(...analysisExclusionSummary(scope.exclusions));
|
||||
parts.push(...columnFilterSummary(scope.columnFilters, scope.columnLabels));
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
export function analysisExclusionSummary(value: unknown): string[] {
|
||||
const exclusions = safeExclusions(value);
|
||||
if (!exclusions) return [];
|
||||
const labels: Record<AnalysisExclusionDimension, string> = {
|
||||
department: '产业部', group: '业务分组', product: '产品', projectGroup: '项目组',
|
||||
};
|
||||
return (['department', 'group', 'product', 'projectGroup'] as const).flatMap(dimension => {
|
||||
const values = exclusions[dimension];
|
||||
return values?.length ? [`排除${labels[dimension]}:${values.join('、')}`] : [];
|
||||
});
|
||||
}
|
||||
|
||||
export function columnFilterSummary(value: unknown, labelValue: unknown): string[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const labels = isRecord(labelValue) ? labelValue : {};
|
||||
return value.flatMap(rule => {
|
||||
if (!isRecord(rule) || typeof rule.field !== 'string' || !Array.isArray(rule.stages)) return [];
|
||||
const stage = rule.stages.map(item => item === 'black' ? '黑片' : item === 'bright' ? '亮片' : '').filter(Boolean).join('、');
|
||||
const label = typeof labels[rule.field] === 'string' ? labels[rule.field] : '来源字段';
|
||||
const operation = ({ in: '为', not_in: '排除', is_empty: '为空', not_empty: '不为空' } as Record<string, string>)[String(rule.operator)];
|
||||
if (!operation) return [];
|
||||
const values = Array.isArray(rule.values) ? rule.values.filter(item => typeof item === 'string').join('、') : '';
|
||||
return [`${stage} ${label}${operation}${values}`.trim()];
|
||||
});
|
||||
}
|
||||
|
||||
export function visualPeriodSummary(visual: AnalysisVisual): string {
|
||||
return visual.comparisonPeriod
|
||||
? `${plainPeriod(visual.comparisonPeriod)} → ${plainPeriod(visual.period)}`
|
||||
|
||||
+17
-4
@@ -5,6 +5,7 @@ import { RequestTimeoutError, withRequestDeadline } from './requestDeadline';
|
||||
import type {
|
||||
AuthUser,
|
||||
FilterField,
|
||||
SourceColumnField,
|
||||
Collection,
|
||||
FineDefectTopResponse,
|
||||
MetricsResponse,
|
||||
@@ -122,14 +123,14 @@ export async function refreshCsrf(): Promise<string> {
|
||||
return csrfToken;
|
||||
}
|
||||
|
||||
async function mutate<T>(path: string, body?: unknown, method = 'POST'): Promise<T> {
|
||||
async function mutate<T>(path: string, body?: unknown, method = 'POST', timeoutMs?: number): Promise<T> {
|
||||
const token = csrfToken ?? await refreshCsrf();
|
||||
const headers = new Headers({ 'X-XSRF-TOKEN': token });
|
||||
const result = await request<T>(path, {
|
||||
method,
|
||||
headers,
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
}, timeoutMs);
|
||||
if (!/^\/api\/(?:analysis|auth)(?:\/|$)/.test(path)) window.dispatchEvent(new Event(WORKSPACE_INVALIDATED));
|
||||
return result;
|
||||
}
|
||||
@@ -147,6 +148,8 @@ async function mutateForm<T>(path: string, body: FormData): Promise<T> {
|
||||
}
|
||||
|
||||
export const api = {
|
||||
sourceColumnCatalog(releaseId?: string) { return request<{releaseId:string;sourceFields:SourceColumnField[]}>(`/api/analysis/source/catalog?${toQuery({releaseId})}`); },
|
||||
sourceColumnValues(body: Record<string,unknown>, signal?: AbortSignal) { return queryPost<{values:Array<string|null>;hasMore?:boolean;total?:number;limit?:number}>('/api/analysis/source/values',body,signal); },
|
||||
workspaceState() { return request<{ authRevision: string; dataRevision: string }>('/api/workspace/state', {}, 8000); },
|
||||
filterFields(manage = false) { return request<FilterField[]>(`/api/filter-fields?manage=${manage}`); },
|
||||
filterFieldOptions(key: string, search = '') { return request<{ values: string[]; hasMore: boolean }>(`/api/filter-fields/options?${toQuery({key, search})}`); },
|
||||
@@ -251,6 +254,12 @@ export const api = {
|
||||
revalidateMappingIssue(id: string, body: { decisionId: string; expectedCurrentReleaseId: string | null; idempotencyKey: string }) {
|
||||
return mutate<Record<string, unknown>>(`/api/governance/mapping-issues/${encodeURIComponent(id)}/revalidate`, body);
|
||||
},
|
||||
taskOverview() {
|
||||
return request<Collection>('/api/tasks/overview');
|
||||
},
|
||||
latestBackup() {
|
||||
return request<Record<string, unknown>>('/api/governance/backups/latest');
|
||||
},
|
||||
tasks() {
|
||||
return request<Collection>('/api/tasks');
|
||||
},
|
||||
@@ -409,7 +418,7 @@ export const api = {
|
||||
return request<Record<string, unknown>>(`/api/analysis/turns/${encodeURIComponent(id)}`);
|
||||
},
|
||||
analysisTurnSnapshot(id: string) {
|
||||
return request<Record<string, unknown>>(`/api/analysis/turns/${encodeURIComponent(id)}/snapshot`, {}, 8000);
|
||||
return request<Record<string, unknown>>(`/api/analysis/turns/${encodeURIComponent(id)}/snapshot`, {}, 30000);
|
||||
},
|
||||
analysisSettings() {
|
||||
return request<import('./AnalysisApiSettings').AnalysisModelSettings>('/api/analysis/settings');
|
||||
@@ -423,6 +432,9 @@ export const api = {
|
||||
retryAnalysisTurn(id: string) {
|
||||
return mutate<{ turn: Record<string, unknown> }>(`/api/analysis/turns/${encodeURIComponent(id)}/retry`);
|
||||
},
|
||||
recoverAnalysisVisuals(id: string) {
|
||||
return mutate<Record<string, unknown>>(`/api/analysis/turns/${encodeURIComponent(id)}/visual-recovery`, undefined, 'POST', 60000);
|
||||
},
|
||||
analysisTurnEvents(id: string, options: { signal?: AbortSignal; lastEventId?: string; onEvent: (event: StreamEvent) => void }) {
|
||||
return readEventStream(`/api/analysis/turns/${encodeURIComponent(id)}/events`, options);
|
||||
},
|
||||
@@ -668,7 +680,8 @@ function toQuery(values: object): string {
|
||||
const query = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
if (value === undefined || value === null || value === '') continue;
|
||||
if (Array.isArray(value)) value.forEach(item => {
|
||||
if (key === 'columnFilters') query.set(key, JSON.stringify(value));
|
||||
else if (Array.isArray(value)) value.forEach(item => {
|
||||
if (item !== undefined && item !== null && item !== '') query.append(key, String(item));
|
||||
});
|
||||
else query.set(key, typeof value === 'object' ? JSON.stringify(value) : String(value));
|
||||
|
||||
+25
-25
@@ -44,7 +44,7 @@
|
||||
|
||||
.completion-panel-heading strong {
|
||||
color: var(--ink);
|
||||
font-size: 13px;
|
||||
font-size: var(--font-section);
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@
|
||||
.completion-note,
|
||||
.completion-placeholder {
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@
|
||||
|
||||
.completion-focus-panel .completion-section-heading span {
|
||||
color: #4d5b6e;
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
}
|
||||
|
||||
.completion-insight-card {
|
||||
@@ -113,7 +113,7 @@
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
color: var(--ink);
|
||||
font-size: 12px;
|
||||
font-size: var(--font-control);
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
@@ -127,7 +127,7 @@
|
||||
|
||||
.completion-target-value small {
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
font-weight: 450;
|
||||
}
|
||||
|
||||
@@ -173,7 +173,7 @@
|
||||
|
||||
.completion-snapshot > strong {
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
}
|
||||
|
||||
.completion-snapshot dl {
|
||||
@@ -181,7 +181,7 @@
|
||||
grid-template-columns: minmax(90px, 0.8fr) minmax(80px, 1fr);
|
||||
gap: 4px 8px;
|
||||
margin: 8px 0 0;
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
}
|
||||
|
||||
.completion-snapshot dt {
|
||||
@@ -216,12 +216,12 @@
|
||||
|
||||
.completion-delta-grid small {
|
||||
color: var(--ink);
|
||||
font-size: 10px;
|
||||
font-size: var(--font-note);
|
||||
}
|
||||
|
||||
.completion-delta-grid strong {
|
||||
color: var(--ink);
|
||||
font-size: 13px;
|
||||
font-size: var(--font-body);
|
||||
font-variant-numeric: tabular-nums;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
@@ -234,7 +234,7 @@
|
||||
gap: 7px 12px;
|
||||
margin-top: 10px;
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
@@ -258,7 +258,7 @@
|
||||
.completion-insights .ant-table-cell,
|
||||
.completion-tools .ant-table-cell {
|
||||
padding: 8px 10px !important;
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
}
|
||||
|
||||
.completion-actions {
|
||||
@@ -282,7 +282,7 @@
|
||||
justify-content: center;
|
||||
gap: 10px;
|
||||
color: var(--ink);
|
||||
font-size: 12px;
|
||||
font-size: var(--font-control);
|
||||
}
|
||||
|
||||
.completion-scrap-stack {
|
||||
@@ -317,7 +317,7 @@
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
}
|
||||
|
||||
.target-current-summary {
|
||||
@@ -355,7 +355,7 @@
|
||||
.target-admin details {
|
||||
margin-top: 8px;
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
}
|
||||
|
||||
.target-admin details pre {
|
||||
@@ -402,7 +402,7 @@
|
||||
|
||||
.target-rule-row .ant-form-item-label > label {
|
||||
color: var(--ink);
|
||||
font-size: 10px;
|
||||
font-size: var(--font-note);
|
||||
}
|
||||
|
||||
.target-rule-row > .ant-btn {
|
||||
@@ -438,12 +438,12 @@
|
||||
|
||||
.target-editor-heading strong {
|
||||
color: var(--ink);
|
||||
font-size: 12px;
|
||||
font-size: var(--font-control);
|
||||
}
|
||||
|
||||
.target-editor-heading span {
|
||||
color: var(--muted-ink, #68778b);
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
@@ -547,7 +547,7 @@
|
||||
gap: 10px;
|
||||
padding: 0 2px 7px;
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
}
|
||||
|
||||
.governance-status-strip strong {
|
||||
@@ -564,7 +564,7 @@
|
||||
.governance-monitor .ant-table-cell,
|
||||
.governance-service-identities .ant-table-cell {
|
||||
padding: 8px 10px !important;
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
}
|
||||
|
||||
.governance-form-grid {
|
||||
@@ -603,13 +603,13 @@
|
||||
border: 1px solid #dce3ee;
|
||||
background: #f8fafc;
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.governance-evidence-summary strong {
|
||||
grid-column: 1 / -1;
|
||||
font-size: 13px;
|
||||
font-size: var(--font-body);
|
||||
}
|
||||
|
||||
.governance-evidence-summary span {
|
||||
@@ -641,13 +641,13 @@
|
||||
|
||||
.governance-monitor-grid small {
|
||||
color: var(--ink);
|
||||
font-size: 10px;
|
||||
font-size: var(--font-note);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.governance-monitor-grid strong {
|
||||
color: var(--ink);
|
||||
font-size: 14px;
|
||||
font-size: var(--font-section);
|
||||
font-variant-numeric: tabular-nums;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
@@ -672,7 +672,7 @@
|
||||
padding: 9px;
|
||||
border: 1px solid #dce3ee;
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
}
|
||||
|
||||
.governance-binding-list > div > * {
|
||||
@@ -731,7 +731,7 @@
|
||||
.analysis-evidence-list li { margin: 5px 0; overflow-wrap: anywhere; }
|
||||
.analysis-result-ref-notice { margin: 10px 12px 0; }
|
||||
.completion-technical-detail { margin: 14px 0 4px; border-top: 1px solid #dce3ee; padding-top: 10px; }
|
||||
.completion-technical-detail > summary { cursor: pointer; color: #4b5563; font-size: 12px; }
|
||||
.completion-technical-detail > summary { cursor: pointer; color: #4b5563; font-size: var(--font-control); }
|
||||
.completion-technical-detail > .json-result { max-height: 360px; overflow: auto; margin-top: 10px; }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
const dateNamePattern = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/;
|
||||
|
||||
export function configurationDateTime(value: unknown): string {
|
||||
if (!(value instanceof Date) && typeof value !== 'string' && typeof value !== 'number') return '';
|
||||
const date = value instanceof Date ? value : new Date(value);
|
||||
if (!Number.isFinite(date.getTime())) return '';
|
||||
const parts = Object.fromEntries(new Intl.DateTimeFormat('en-CA', {
|
||||
timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit',
|
||||
hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23',
|
||||
}).formatToParts(date).map(part => [part.type, part.value]));
|
||||
return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}:${parts.second}`;
|
||||
}
|
||||
|
||||
export function currentConfigurationName(name: unknown, createdAt: unknown): string {
|
||||
return typeof name === 'string' && dateNamePattern.test(name) ? name : configurationDateTime(createdAt);
|
||||
}
|
||||
+4
-11
@@ -1,13 +1,6 @@
|
||||
:root[data-workspace-theme='dark'] {
|
||||
color-scheme: dark;
|
||||
background: #0e1420;
|
||||
--ink: #eaf0fa;
|
||||
--muted-ink: #adbdd1;
|
||||
--surface: #172234;
|
||||
--surface-subtle: #1d2a3d;
|
||||
--sidebar-surface: #111b2a;
|
||||
--line: #35445a;
|
||||
--blue-dark: #a9bdff;
|
||||
background: var(--background);
|
||||
}
|
||||
|
||||
:root[data-workspace-theme='dark'] body,
|
||||
@@ -48,9 +41,9 @@
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll .ant-table-tbody > tr > td.ant-table-cell-fix-left { background: var(--surface); }
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll .combined-column,
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll .combined-column.ant-table-cell-fix-left,
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll th.combined-column,
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.black) { background: #253457 !important; }
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.bright) { background: #183f3d !important; }
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll th.combined-column { background: var(--table-combined, var(--blue-soft)) !important; }
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.black) { background: var(--blue-soft) !important; }
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.bright) { background: var(--table-bright-head) !important; }
|
||||
:root[data-workspace-theme='dark'] .metric-table-scroll .ant-table-thead > tr > th { color: var(--ink); }
|
||||
:root[data-workspace-theme='dark'] .stage-heading.black,
|
||||
:root[data-workspace-theme='dark'] .rate-cell.black .table-value { color: var(--blue-dark); }
|
||||
|
||||
+35
-23
@@ -7,6 +7,7 @@ import { getStoredWorkspaceThemeId, getWorkspaceTheme, workspaceThemeStorageKey,
|
||||
import './styles.css';
|
||||
import './dark-theme.css';
|
||||
import './quality-table.css';
|
||||
import './workspace-finish.css';
|
||||
|
||||
function QualityCenterApp() {
|
||||
const [themeId, setThemeId] = useState<WorkspaceThemeId>(getStoredWorkspaceThemeId);
|
||||
@@ -16,20 +17,22 @@ function QualityCenterApp() {
|
||||
useLayoutEffect(() => {
|
||||
const root = document.documentElement;
|
||||
root.dataset.workspaceTheme = appearance.id;
|
||||
root.style.setProperty('--ink', dark ? '#EAF0FA' : '#111111');
|
||||
root.style.setProperty('--muted-ink', dark ? '#ADBDD1' : '#63758b');
|
||||
root.style.setProperty('--ink', appearance.ink);
|
||||
root.style.setProperty('--muted-ink', appearance.secondaryInk);
|
||||
root.style.setProperty('--blue', appearance.primary);
|
||||
root.style.setProperty('--blue-dark', dark ? '#A9BDFF' : appearance.primary);
|
||||
root.style.setProperty('--blue-dark', appearance.primary);
|
||||
root.style.setProperty('--blue-soft', appearance.soft);
|
||||
root.style.setProperty('--blue-muted', appearance.muted);
|
||||
root.style.setProperty('--background', appearance.background);
|
||||
root.style.setProperty('--hover', appearance.hover);
|
||||
root.style.setProperty('--metric-grid', appearance.metricGrid);
|
||||
root.style.setProperty('--metric-grid-head', appearance.metricGridHead);
|
||||
root.style.setProperty('--sidebar-surface', dark ? '#111B2A' : 'color-mix(in srgb, var(--background) 48%, white)');
|
||||
root.style.setProperty('--surface', dark ? '#172234' : '#ffffff');
|
||||
root.style.setProperty('--line', dark ? '#35445A' : '#dfe5ef');
|
||||
root.style.setProperty('--teal', dark ? '#54D5BF' : '#008f7d');
|
||||
root.style.setProperty('--sidebar-surface', dark ? '#111829' : 'color-mix(in srgb, var(--background) 48%, var(--surface))');
|
||||
root.style.setProperty('--surface', appearance.surface);
|
||||
root.style.setProperty('--surface-subtle', appearance.subtle);
|
||||
root.style.setProperty('--surface-elevated', appearance.elevated);
|
||||
root.style.setProperty('--line', appearance.line);
|
||||
root.style.setProperty('--teal', appearance.teal);
|
||||
try { window.localStorage.setItem(workspaceThemeStorageKey, appearance.id); } catch { /* local preference is optional */ }
|
||||
}, [appearance]);
|
||||
|
||||
@@ -41,28 +44,37 @@ function QualityCenterApp() {
|
||||
token: {
|
||||
colorPrimary: appearance.primary,
|
||||
colorInfo: appearance.primary,
|
||||
colorBgBase: dark ? '#101928' : '#ffffff',
|
||||
colorBgContainer: dark ? '#172234' : '#ffffff',
|
||||
colorBgBase: appearance.background,
|
||||
colorBgLayout: appearance.background,
|
||||
colorBgContainer: appearance.surface,
|
||||
// Ant Design 6 renders modal panels on `.ant-modal-container` and
|
||||
// derives their background from this token. Keep it explicit in
|
||||
// light themes so overlays never inherit a transparent default.
|
||||
colorBgElevated: dark ? '#1A2638' : '#ffffff',
|
||||
colorText: dark ? '#EAF0FA' : '#111111',
|
||||
colorTextSecondary: dark ? '#ADBDD1' : '#111111',
|
||||
colorTextPlaceholder: dark ? '#98ABC5' : undefined,
|
||||
colorBorder: dark ? '#35445A' : '#dfe5ef',
|
||||
colorBorderSecondary: dark ? '#35445A' : undefined,
|
||||
borderRadius: 0,
|
||||
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif',
|
||||
colorBgElevated: appearance.elevated,
|
||||
colorText: appearance.ink,
|
||||
colorTextSecondary: appearance.secondaryInk,
|
||||
colorTextPlaceholder: appearance.placeholder,
|
||||
colorBorder: appearance.line,
|
||||
colorBorderSecondary: appearance.line,
|
||||
borderRadius: 4,
|
||||
fontFamily: '"PingFang SC", "Microsoft YaHei", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
|
||||
controlHeight: 32,
|
||||
fontSize: 14,
|
||||
fontSize: 13,
|
||||
fontSizeSM: 12,
|
||||
fontSizeLG: 14,
|
||||
},
|
||||
components: {
|
||||
Button: { borderRadius: 0 },
|
||||
Input: { borderRadius: 0 },
|
||||
Select: { borderRadius: 0 },
|
||||
Table: { headerBg: dark ? '#202D40' : '#f6f8fd', rowHoverBg: appearance.hover },
|
||||
Modal: { borderRadiusLG: 0 },
|
||||
Button: {
|
||||
borderRadius: 4, contentFontSize: 12, contentFontSizeSM: 12, contentFontSizeLG: 13,
|
||||
primaryColor: dark ? '#080F1E' : '#FFFFFF',
|
||||
...(appearance.id === 'bright' ? { colorPrimary: '#0078D4', colorPrimaryHover: '#006ABD', colorPrimaryActive: '#005EA8' } : {}),
|
||||
},
|
||||
Input: { borderRadius: 4, inputFontSize: 12, inputFontSizeSM: 12, inputFontSizeLG: 13 },
|
||||
Select: { borderRadius: 4, fontSize: 12 },
|
||||
Form: { labelFontSize: 12 },
|
||||
Segmented: { fontSize: 12 },
|
||||
Table: { cellFontSize: 12, cellFontSizeMD: 12, cellFontSizeSM: 12, headerBg: appearance.subtle, rowHoverBg: appearance.hover },
|
||||
Modal: { borderRadiusLG: 6 },
|
||||
Drawer: { borderRadiusLG: 0 },
|
||||
},
|
||||
}}
|
||||
|
||||
@@ -45,7 +45,7 @@
|
||||
|
||||
.management-page .page-heading h1 {
|
||||
color: var(--management-ink);
|
||||
font-size: 20px;
|
||||
font-size: var(--font-page-title);
|
||||
font-weight: 650;
|
||||
line-height: 1.35;
|
||||
}
|
||||
@@ -54,7 +54,7 @@
|
||||
max-width: 980px;
|
||||
margin-top: 5px;
|
||||
color: var(--management-muted);
|
||||
font-size: 12px;
|
||||
font-size: var(--font-control);
|
||||
line-height: 1.6;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
@@ -82,14 +82,14 @@
|
||||
|
||||
.management-page .resource-toolbar strong {
|
||||
color: var(--management-ink);
|
||||
font-size: 13px;
|
||||
font-size: var(--font-section);
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.management-page .resource-toolbar span {
|
||||
min-width: 0;
|
||||
color: var(--management-muted);
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
@@ -104,13 +104,13 @@
|
||||
|
||||
.management-page .resource-table .ant-table-cell {
|
||||
padding: 9px 11px !important;
|
||||
font-size: 12px;
|
||||
font-size: var(--font-control);
|
||||
}
|
||||
|
||||
.management-page .ant-table-thead > tr > th {
|
||||
background: var(--management-blue-wash) !important;
|
||||
color: var(--management-ink);
|
||||
font-size: 12px;
|
||||
font-size: var(--font-control);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@
|
||||
.management-page .table-caption {
|
||||
margin: 8px 15px 11px;
|
||||
color: var(--management-muted);
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
@@ -162,13 +162,13 @@
|
||||
.management-page .access-summary span,
|
||||
.management-page .access-summary small {
|
||||
color: var(--management-muted);
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.management-page .access-summary strong {
|
||||
color: var(--management-ink);
|
||||
font-size: 13px;
|
||||
font-size: var(--font-body);
|
||||
font-weight: 600;
|
||||
line-height: 1.55;
|
||||
overflow-wrap: anywhere;
|
||||
@@ -229,7 +229,7 @@
|
||||
|
||||
.management-page .analysis-session-heading strong {
|
||||
color: var(--management-ink);
|
||||
font-size: 13px;
|
||||
font-size: var(--font-body);
|
||||
}
|
||||
|
||||
.management-page .analysis-session-item {
|
||||
@@ -353,7 +353,7 @@
|
||||
border-radius: 0;
|
||||
background: #f7f9fc;
|
||||
color: #253044;
|
||||
font-size: 11px;
|
||||
font-size: var(--font-note);
|
||||
line-height: 1.6;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
@@ -386,7 +386,7 @@
|
||||
border-radius: 0;
|
||||
background: #f7f9fc;
|
||||
color: #253044;
|
||||
font: 11px/1.6 var(--mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace);
|
||||
font: var(--font-note)/1.6 var(--mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
@@ -475,7 +475,7 @@
|
||||
.management-drawer .ant-drawer-title,
|
||||
.management-modal .ant-modal-title {
|
||||
color: var(--management-ink);
|
||||
font-size: 15px;
|
||||
font-size: var(--font-dialog-title);
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
@@ -520,7 +520,7 @@
|
||||
}
|
||||
|
||||
.management-page .page-heading h1 {
|
||||
font-size: 18px;
|
||||
font-size: var(--font-page-title);
|
||||
}
|
||||
|
||||
.management-page .page-heading-actions {
|
||||
@@ -599,7 +599,7 @@
|
||||
|
||||
.management-page .json-result {
|
||||
padding: 10px;
|
||||
font-size: 10px;
|
||||
font-size: var(--font-note);
|
||||
}
|
||||
|
||||
.management-drawer .ant-drawer-header {
|
||||
@@ -644,3 +644,17 @@
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Shared card insets for the Rules and Management pages. */
|
||||
.page-view:is([data-page="rules"],[data-page="mappings"],[data-page="masterData"],[data-page="tasks"],[data-page="access"]) .panel {
|
||||
padding-inline: 20px;
|
||||
}
|
||||
.page-view:is([data-page="rules"],[data-page="mappings"],[data-page="masterData"],[data-page="tasks"],[data-page="access"]) .section-panel {
|
||||
padding-block: 14px;
|
||||
}
|
||||
.page-view:is([data-page="rules"],[data-page="mappings"],[data-page="masterData"],[data-page="tasks"],[data-page="access"]) .panel > :is(.resource-toolbar,.section-heading-row,.completion-panel-heading) {
|
||||
padding-inline: 0;
|
||||
}
|
||||
@media(max-width:760px) {
|
||||
.page-view:is([data-page="rules"],[data-page="mappings"],[data-page="masterData"],[data-page="tasks"],[data-page="access"]) .panel { padding-inline: 12px; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { isValidElement, type Key } from 'react';
|
||||
|
||||
type ExportColumn = { exportRate?: boolean; key?: Key; title?: unknown; children?: readonly ExportColumn[] };
|
||||
type ExportValue = string | number | null;
|
||||
|
||||
function nodeText(node: unknown): string {
|
||||
if (typeof node === 'string' || typeof node === 'number') return String(node);
|
||||
if (Array.isArray(node)) return node.map(nodeText).join('');
|
||||
if (isValidElement<{ children?: unknown }>(node)) return nodeText(node.props.children);
|
||||
return '';
|
||||
}
|
||||
|
||||
// Use the table's actual column tree, so key/full mode and dynamic defect fields stay aligned.
|
||||
export function workbookColumns(columns: readonly ExportColumn[], parents: string[] = []): { key: string; header: string; rate: boolean }[] {
|
||||
return columns.flatMap(column => {
|
||||
const path = [...parents, nodeText(column.title).trim()].filter(Boolean);
|
||||
if (column.children) return workbookColumns(column.children, path);
|
||||
const key = String(column.key ?? '');
|
||||
if (!key || key === 'actions') return [];
|
||||
const rate = column.exportRate === true || key === 'compositeRate' || /^(black|bright)-rate$/.test(key);
|
||||
return [{ key, header: `${path.join(' / ')}${key === 'object' || rate ? '' : ' / kg'}`, rate }];
|
||||
});
|
||||
}
|
||||
|
||||
export async function createMetricWorkbook<T>(columns: readonly ExportColumn[], rows: readonly T[], value: (key: string, row: T) => ExportValue) {
|
||||
const { default: ExcelJS } = await import('exceljs');
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const sheet = workbook.addWorksheet('质量汇总', { views: [{ state: 'frozen', xSplit: 1, ySplit: 1 }] });
|
||||
const fields = workbookColumns(columns);
|
||||
sheet.columns = fields.map(field => ({ header: field.header, key: field.key, width: field.key === 'object' ? 38 : Math.max(18, Math.min(field.header.length * 2, 48)) }));
|
||||
for (const row of rows) sheet.addRow(fields.map(field => {
|
||||
const result = value(field.key, row);
|
||||
return typeof result === 'number' && !Number.isFinite(result) ? null : result;
|
||||
}));
|
||||
fields.forEach((field, index) => {
|
||||
if (field.key !== 'object') sheet.getColumn(index + 1).numFmt = field.rate ? '0.00%' : '#,##0.0';
|
||||
});
|
||||
sheet.getRow(1).font = { bold: true, color: { argb: 'FFFFFFFF' } };
|
||||
sheet.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF6379DF' } };
|
||||
sheet.getRow(1).alignment = { vertical: 'middle', wrapText: true };
|
||||
sheet.getRow(1).height = 36;
|
||||
sheet.autoFilter = { from: { row: 1, column: 1 }, to: { row: Math.max(1, rows.length + 1), column: fields.length } };
|
||||
return workbook;
|
||||
}
|
||||
|
||||
export async function downloadMetricWorkbook<T>(filename: string, columns: readonly ExportColumn[], rows: readonly T[], value: (key: string, row: T) => ExportValue) {
|
||||
const workbook = await createMetricWorkbook(columns, rows, value);
|
||||
const buffer = await workbook.xlsx.writeBuffer();
|
||||
const url = URL.createObjectURL(new Blob([new Uint8Array(buffer)], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }));
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `${filename.replace(/[\\/:*?"<>|]/g, '_')}.xlsx`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 30_000);
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import { buildAnalysisNarrative, classifyAnalysisSection } from './analysisReportModel';
|
||||
import { reportVisualHtml, type ReportVisualImage } from './AnalysisReportVisuals';
|
||||
import { buildAnalysisReadingModel } from './analysisReadingModel';
|
||||
import { sanitizeAnalysisDisplayText } from './analysisDisplayText';
|
||||
import { analysisEvidenceParts, isQueryEvidenceRef, nativeReadingEvidenceTargets } from './analysisEvidenceRefs';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
const normalized = (value: string) => value.replace(/^\s*(?:[一二三四五六七八九十]+[、..]|\d+(?:\.\d+)*[、..)\s]+)\s*/, '').replace(/[\s·//::、,,()().]+/g, '').toLowerCase();
|
||||
@@ -34,7 +37,11 @@ export function integrateNativeReportNarrative(source: string, turn: Row, images
|
||||
if (!heading) continue;
|
||||
const figure = doc.createElement('div');
|
||||
figure.className = 'platform-chapter-figures';
|
||||
figure.innerHTML = reportVisualHtml({ ...turn, result: { ...result, visuals: section.visuals, visualSchemaVersion: 1 } }, images);
|
||||
for (const visual of section.visuals) {
|
||||
const item = doc.createElement('div'); item.setAttribute('data-analysis-visual-id', visual.id);
|
||||
item.innerHTML = reportVisualHtml({ ...turn, result: { ...result, visuals: [visual], visualSchemaVersion: 1 } }, images);
|
||||
figure.append(item);
|
||||
}
|
||||
// 解读保留在图前,原有表格保留在图后。
|
||||
let anchor: Element = heading;
|
||||
let sibling = heading.nextElementSibling;
|
||||
@@ -45,11 +52,76 @@ export function integrateNativeReportNarrative(source: string, turn: Row, images
|
||||
const remaining = model.sections.flatMap(section => section.visuals).filter(visual => !assigned.has(visual.id));
|
||||
if (remaining.length) {
|
||||
const appendix = doc.createElement('section');
|
||||
appendix.className = 'platform-chapter-figures';
|
||||
appendix.className = 'platform-chapter-figures'; appendix.setAttribute('data-analysis-generated-visual-section', '');
|
||||
const heading = doc.createElement('h2'); heading.textContent = '补充分析图表'; appendix.append(heading);
|
||||
const content = doc.createElement('div');
|
||||
content.innerHTML = reportVisualHtml({ ...turn, result: { ...result, visuals: remaining, visualSchemaVersion: 1 } }, images);
|
||||
for (const visual of remaining) {
|
||||
const item = doc.createElement('div'); item.setAttribute('data-analysis-visual-id', visual.id);
|
||||
item.innerHTML = reportVisualHtml({ ...turn, result: { ...result, visuals: [visual], visualSchemaVersion: 1 } }, images);
|
||||
content.append(item);
|
||||
}
|
||||
appendix.append(content); doc.body.append(appendix);
|
||||
}
|
||||
return '<!doctype html>\n' + doc.documentElement.outerHTML;
|
||||
}
|
||||
|
||||
/** Move, rather than recreate, the complete native document so rows/provenance/figures survive. */
|
||||
export function compactNativeReportReading(source: string, turn: Row): string {
|
||||
const doc = new DOMParser().parseFromString(source, 'text/html');
|
||||
if (doc.querySelector('[data-analysis-reading-layout]')) return source;
|
||||
const result = turn.result && typeof turn.result === 'object' ? turn.result as Row : turn;
|
||||
const answer = String(result.reportMarkdown || turn.reportMarkdown || result.answer || turn.answer || '');
|
||||
const { model, reading, primaryVisuals } = buildAnalysisReadingModel(answer, result.visuals || turn.visuals, String(turn.question || ''), turn);
|
||||
if (!reading.hasAppendix) return source;
|
||||
const evidenceTargets = nativeReadingEvidenceTargets(doc, model.evidence.map(entry => entry.ref));
|
||||
const summary = doc.createElement('section'); summary.className = 'platform-reading-summary';
|
||||
summary.setAttribute('data-analysis-reading-layout', '');
|
||||
const title = doc.createElement('h1'); title.textContent = doc.title || '质量分析报告'; summary.append(title);
|
||||
const heading = doc.createElement('h2'); heading.textContent = '核心结论'; summary.append(heading);
|
||||
const paragraph = (value: string) => {
|
||||
const p = doc.createElement('p');
|
||||
const references = (target: HTMLElement, content: string) => {
|
||||
for (const { text, ref } of analysisEvidenceParts(content)) {
|
||||
if (ref && Object.hasOwn(model.evidenceLabels, ref) && Object.hasOwn(evidenceTargets, ref)) {
|
||||
const link = doc.createElement('a'); link.href = evidenceTargets[ref];
|
||||
link.textContent = model.evidenceLabels[ref]; target.append(link);
|
||||
} else target.append(doc.createTextNode(text));
|
||||
}
|
||||
};
|
||||
const lines = sanitizeAnalysisDisplayText(value).replaceAll('\r\n', '\n').replaceAll('\r', '\n').split('\n');
|
||||
lines.forEach((line, index) => {
|
||||
if (index) p.append(doc.createElement('br'));
|
||||
for (const part of line.split(/(\*\*.+?\*\*|`[^`]+`)/g)) {
|
||||
if (part.startsWith('**') && part.endsWith('**') && part.length >= 4) {
|
||||
const strong = doc.createElement('strong'); references(strong, part.slice(2, -2)); p.append(strong);
|
||||
} else if (part.startsWith('`') && part.endsWith('`') && part.length >= 2) {
|
||||
const code = doc.createElement('code'); code.textContent = part.slice(1, -1); p.append(code);
|
||||
} else references(p, part);
|
||||
}
|
||||
});
|
||||
return p;
|
||||
};
|
||||
summary.append(paragraph(reading.lead));
|
||||
if (reading.evidence.length) {
|
||||
const h = doc.createElement('h3'); h.textContent = '关键依据'; summary.append(h);
|
||||
const list = doc.createElement('ul');
|
||||
for (const value of reading.evidence) { const li = doc.createElement('li'); li.append(paragraph(value)); list.append(li); }
|
||||
summary.append(list);
|
||||
}
|
||||
for (const notice of reading.notices) summary.append(paragraph(notice));
|
||||
const primary = doc.createElement('div'); primary.className = 'platform-reading-summary platform-chapter-figures';
|
||||
for (const visual of primaryVisuals) {
|
||||
const nodes = [...doc.querySelectorAll('[data-analysis-visual-id]')].filter(element => element.getAttribute('data-analysis-visual-id') === visual.id);
|
||||
if (nodes.length === 1) primary.append(nodes[0]);
|
||||
}
|
||||
doc.querySelectorAll('[data-analysis-generated-visual-section]').forEach(element => { if (!element.querySelector('[data-analysis-visual-id]')) element.remove(); });
|
||||
const appendix = doc.createElement('details'); appendix.className = 'platform-full-appendix';
|
||||
const label = doc.createElement('summary'); label.textContent = '附录:完整分析、数据与图表'; appendix.append(label);
|
||||
const content = doc.createElement('div'); content.className = 'platform-full-content';
|
||||
for (const entry of model.evidence.filter(entry => isQueryEvidenceRef(entry.ref))) { const anchor = doc.createElement('span'); anchor.id = 'platform-evidence-' + entry.ref; content.append(anchor); }
|
||||
while (doc.body.firstChild) content.append(doc.body.firstChild);
|
||||
appendix.append(content); doc.body.append(summary); if (primary.children.length) doc.body.append(primary); doc.body.append(appendix);
|
||||
const style = doc.createElement('style'); style.textContent = '.platform-reading-summary{box-sizing:border-box;max-width:900px;margin:0 auto;padding:32px 42px;background:#fff;color:#202b3c;font:15px/1.85 -apple-system,BlinkMacSystemFont,"PingFang SC",sans-serif}.platform-reading-summary h1{font-size:25px}.platform-reading-summary h2{font-size:18px}.platform-reading-summary h3{font-size:14px}.platform-reading-summary a{font-size:12px;color:#65748b;margin-left:5px}.platform-full-appendix{box-sizing:border-box;max-width:900px;margin:0 auto;background:#fff}.platform-full-appendix>summary{padding:16px 42px;cursor:pointer;border-top:1px solid #dfe5ef;color:#65748b;font-size:14px}.platform-full-content{display:flow-root}';
|
||||
doc.head.append(style);
|
||||
return '<!doctype html>\n' + doc.documentElement.outerHTML;
|
||||
}
|
||||
|
||||
@@ -1,90 +1,90 @@
|
||||
.nc-intake-start { padding: 26px 28px 0; display: grid; grid-template-columns: minmax(320px, 1fr) auto; column-gap: 28px; }
|
||||
.nc-eyebrow { display: block; font-size: 11px; font-weight: 650; letter-spacing: .08em; margin-bottom: 7px; }
|
||||
.nc-intake-intro h2 { margin: 0 0 8px; font-size: 25px; line-height: 1.3; letter-spacing: -.025em; color: var(--ink); }
|
||||
.nc-intake-intro p { margin: 0; line-height: 1.7; font-size: 13px; color: var(--ink); }
|
||||
.nc-eyebrow { display: block; font-size: var(--font-note); font-weight: 650; letter-spacing: .08em; margin-bottom: 7px; }
|
||||
.nc-intake-intro h2 { margin: 0 0 8px; font-size: var(--font-page-title); line-height: 1.3; letter-spacing: -.025em; color: var(--ink); }
|
||||
.nc-intake-intro p { margin: 0; line-height: 1.7; font-size: var(--font-body); color: var(--ink); }
|
||||
.nc-primary-actions { display: flex; gap: 10px; align-items: center; }
|
||||
.nc-primary-actions .ant-btn { height: 44px; padding: 0 21px; border-radius: 0; font-size: 14px; }
|
||||
.nc-primary-actions .ant-btn { height: 44px; padding: 0 21px; border-radius: 0; font-size: var(--font-section); }
|
||||
.nc-intake-links { grid-column: 1 / -1; display: flex; align-items: center; gap: 14px; border-top: 1px solid #e0e4e9; margin-top: 24px; min-height: 51px; }
|
||||
.nc-intake-links .ant-btn { padding-left: 0; padding-right: 0; font-size: 12px; color: var(--ink); }
|
||||
.nc-intake-links > span { margin-left: auto; font-size: 11px; color: var(--ink); }
|
||||
.nc-intake-links .ant-btn { padding-left: 0; padding-right: 0; font-size: var(--font-control); color: var(--ink); }
|
||||
.nc-intake-links > span { margin-left: auto; font-size: var(--font-note); color: var(--ink); }
|
||||
.nc-pending-strip { padding: 15px 19px; display: flex; gap: 20px; align-items: center; justify-content: space-between; }
|
||||
.nc-pending-strip > div:first-child { display: flex; gap: 15px; align-items: center; font-size: 12px; }
|
||||
.nc-pending-strip > div:first-child { display: flex; gap: 15px; align-items: center; font-size: var(--font-control); }
|
||||
.nc-pending-strip .ant-select { min-width: 350px; }
|
||||
.nc-advanced-records { border-top: 1px solid #dce3ee; padding-top: 13px; }
|
||||
.nc-advanced-records > summary { cursor: pointer; font-size: 12px; padding: 6px 0; color: var(--ink); }
|
||||
.nc-advanced-records > summary { cursor: pointer; font-size: var(--font-control); padding: 6px 0; color: var(--ink); }
|
||||
.nc-advanced-records[open] > summary { margin-bottom: 12px; }
|
||||
.nc-workflow-modal { top: 24px; padding-bottom: 24px; }
|
||||
.nc-workflow-modal .ant-modal-container, .nc-workflow-modal .ant-modal-content, .nc-workflow-modal .ant-input, .nc-workflow-modal .ant-input-number, .nc-workflow-modal .ant-select-selector, .nc-workflow-modal .ant-btn, .nc-workflow-modal .ant-alert { border-radius: 0 !important; }
|
||||
.nc-workflow-modal .ant-modal-body { display: flex; flex-direction: column; gap: 18px; max-height: calc(var(--viewport-height) - 240px); overflow-y: auto; overflow-x: hidden; padding-right: 4px; color: var(--ink); }
|
||||
.nc-workflow-modal .ant-modal-title { font-size: 20px; color: var(--ink); }
|
||||
.nc-workflow-modal h3 { font-size: 14px; margin: 4px 0 12px; color: var(--ink); }
|
||||
.nc-workflow-modal .ant-modal-title { font-size: var(--font-dialog-title); color: var(--ink); }
|
||||
.nc-workflow-modal h3 { font-size: var(--font-section); margin: 4px 0 12px; color: var(--ink); }
|
||||
.nc-workflow-modal .ant-form-item { margin-bottom: 16px; }
|
||||
.nc-workflow-modal .ant-form-item-label > label { color: var(--ink); font-size: 12px; }
|
||||
.nc-workflow-modal .ant-form-item-label > label { color: var(--ink); font-size: var(--font-control); }
|
||||
.nc-steps { margin: 8px 0 10px; padding-bottom: 18px; border-bottom: 1px solid #e0e4e9; }
|
||||
.nc-modal-footer { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding-top: 8px; text-align: left; }
|
||||
.nc-modal-footer > span { font-size: 11px; color: var(--ink); }
|
||||
.nc-modal-footer > span { font-size: var(--font-note); color: var(--ink); }
|
||||
.nc-modal-footer > div { display: flex; flex-shrink: 0; gap: 8px; }
|
||||
.nc-file-drop { border: 1px dashed #bfc9d6; background: #f8faff; min-height: 260px; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 30px; }
|
||||
.nc-file-drop > .anticon { font-size: 40px; margin-bottom: 16px; color: var(--ink); }
|
||||
.nc-file-drop h3 { font-size: 18px; margin: 0 0 10px; }
|
||||
.nc-file-drop p { font-size: 12px; margin-bottom: 22px; }
|
||||
.nc-file-summary { display: flex; align-items: center; gap: 12px; background: #f6f8fd; padding: 12px 16px; border: 1px solid #dce3ee; font-size: 12px; }
|
||||
.nc-file-drop h3 { font-size: var(--font-section); margin: 0 0 10px; }
|
||||
.nc-file-drop p { font-size: var(--font-control); margin-bottom: 22px; }
|
||||
.nc-file-summary { display: flex; align-items: center; gap: 12px; background: #f6f8fd; padding: 12px 16px; border: 1px solid #dce3ee; font-size: var(--font-control); }
|
||||
.nc-file-summary > .anticon { font-size: 22px; }
|
||||
.nc-file-summary strong { overflow-wrap: anywhere; }
|
||||
.nc-file-summary > span:last-child { margin-left: auto; white-space: nowrap; }
|
||||
.nc-form-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0 16px; }
|
||||
.nc-form-grid .ant-select, .nc-form-grid .ant-input-number { width: 100%; }
|
||||
.nc-full-width { grid-column: 1 / -1; }
|
||||
.nc-replacement { display: flex; align-items: center; gap: 9px 14px; flex-wrap: wrap; background: #fffaf0; border: 1px solid #e9d8af; padding: 14px 16px; margin-bottom: 18px; font-size: 12px; }
|
||||
.nc-replacement { display: flex; align-items: center; gap: 9px 14px; flex-wrap: wrap; background: #fffaf0; border: 1px solid #e9d8af; padding: 14px 16px; margin-bottom: 18px; font-size: var(--font-control); }
|
||||
.nc-replacement > span { color: var(--ink); }
|
||||
.nc-replacement > strong { max-width: 380px; overflow-wrap: anywhere; }
|
||||
.nc-section-title { display: flex; justify-content: space-between; align-items: center; gap: 16px; margin-top: 2px; }
|
||||
.nc-section-title h3 { margin: 0 0 10px; }
|
||||
.nc-section-title > span { font-size: 11px; color: var(--ink); }
|
||||
.nc-section-title h3 { font-size: var(--font-section); margin: 0 0 10px; }
|
||||
.nc-section-title > span { font-size: var(--font-note); color: var(--ink); }
|
||||
.nc-column-matching { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 24px; border-top: 1px solid #dce3ee; margin-bottom: 16px; }
|
||||
.nc-field-match { display: grid; grid-template-columns: minmax(125px, 1fr) minmax(145px, 1.3fr); align-items: center; gap: 12px; padding: 9px 0; border-bottom: 1px solid #e4e8ef; font-size: 12px; }
|
||||
.nc-field-match { display: grid; grid-template-columns: minmax(125px, 1fr) minmax(145px, 1.3fr); align-items: center; gap: 12px; padding: 9px 0; border-bottom: 1px solid #e4e8ef; font-size: var(--font-control); }
|
||||
.nc-field-match > span { display: flex; gap: 7px; align-items: center; flex-wrap: wrap; }
|
||||
.nc-field-match b { font-size: 10px; font-weight: 500; padding: 1px 4px; background: #edf2fb; }
|
||||
.nc-field-match small { font-size: 10px; }
|
||||
.nc-field-match b { font-size: var(--font-note); font-weight: 500; padding: 1px 4px; background: #edf2fb; }
|
||||
.nc-field-match small { font-size: var(--font-note); }
|
||||
.nc-field-match .ant-select { min-width: 0; width: 100%; }
|
||||
.nc-workbook-upload-intro { display: flex; justify-content: space-between; gap: 20px; align-items: center; padding: 16px; background: #f6f8fd; border: 1px solid #dce3ee; margin-bottom: 16px; }
|
||||
.nc-workbook-upload-intro strong { font-size: 13px; }
|
||||
.nc-workbook-upload-intro p { font-size: 12px; margin: 6px 0 0; line-height: 1.6; }
|
||||
.nc-workbook-upload-intro strong { font-size: var(--font-body); }
|
||||
.nc-workbook-upload-intro p { font-size: var(--font-control); margin: 6px 0 0; line-height: 1.6; }
|
||||
.nc-workbook-upload-intro .ant-btn { flex-shrink: 0; }
|
||||
.nc-review-facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); border: 1px solid #dce3ee; margin-bottom: 16px; }
|
||||
.nc-review-facts > div { padding: 14px 16px; border-right: 1px solid #dce3ee; display: flex; flex-direction: column; gap: 8px; }
|
||||
.nc-review-facts > div:last-child { border-right: 0; }
|
||||
.nc-review-facts small { color: var(--ink); font-size: 11px; }
|
||||
.nc-review-facts strong { color: var(--ink); font-size: 14px; overflow-wrap: anywhere; }
|
||||
.nc-note { font-size: 12px; line-height: 1.65; margin: 12px 0 0; color: var(--ink); }
|
||||
.nc-review-facts small { color: var(--ink); font-size: var(--font-note); }
|
||||
.nc-review-facts strong { color: var(--ink); font-size: var(--font-section); overflow-wrap: anywhere; }
|
||||
.nc-note { font-size: var(--font-control); line-height: 1.65; margin: 12px 0 0; color: var(--ink); }
|
||||
.nc-processing { padding: 22px; text-align: center; background: #f6f8fd; border: 1px solid #dce3ee; }
|
||||
.nc-processing .ant-progress { max-width: 600px; }
|
||||
.nc-processing h3 { margin-top: 16px; }
|
||||
.nc-issue-list { margin: 0; padding-left: 18px; font-size: 12px; line-height: 1.7; }
|
||||
.nc-processing h3 { font-size: var(--font-section); margin-top: 16px; }
|
||||
.nc-issue-list { margin: 0; padding-left: 18px; font-size: var(--font-control); line-height: 1.7; }
|
||||
.nc-difference-confirm { display: flex; flex-direction: column; gap: 14px; margin-top: 18px; padding-top: 18px; border-top: 1px solid #dce3ee; }
|
||||
.nc-difference-confirm .ant-btn { align-self: flex-end; }
|
||||
.nc-publish-confirm { display: flex; gap: 16px; align-items: center; flex-wrap: wrap; padding: 20px 0 0; margin-top: 20px; border-top: 1px solid #dce3ee; }
|
||||
.nc-publish-confirm > .ant-btn { margin-left: auto; }
|
||||
.nc-publish-confirm > span { width: 100%; font-size: 11px; }
|
||||
.nc-publish-confirm > span { width: 100%; font-size: var(--font-note); }
|
||||
.nc-success { text-align: center; padding: 55px 20px; color: var(--ink); }
|
||||
.nc-success > .anticon { font-size: 40px; margin-bottom: 14px; }
|
||||
.nc-success h2 { font-size: 22px; }
|
||||
.nc-success p { font-size: 13px; }
|
||||
.nc-success h2 { font-size: var(--font-page-title); }
|
||||
.nc-success p { font-size: var(--font-body); }
|
||||
.nc-target-list { max-height: 240px; overflow: auto; border: 1px solid #dce3ee; margin: 18px 0; }
|
||||
.nc-target-list > div { display: flex; gap: 14px; align-items: center; border-bottom: 1px solid #e4e8ef; padding: 10px 12px; font-size: 12px; }
|
||||
.nc-target-list > div { display: flex; gap: 14px; align-items: center; border-bottom: 1px solid #e4e8ef; padding: 10px 12px; font-size: var(--font-control); }
|
||||
.nc-target-list > div:last-child { border-bottom: 0; }
|
||||
.nc-target-list > div > span:last-child { overflow-wrap: anywhere; }
|
||||
.nc-rebuild-confirm p { font-size: 13px; line-height: 1.7; }
|
||||
.nc-source-files .resource-toolbar > .ant-checkbox-wrapper { margin-left: auto; font-size: 12px; flex: 0 0 auto; white-space: nowrap; }
|
||||
.nc-rebuild-confirm p { font-size: var(--font-body); line-height: 1.7; }
|
||||
.nc-source-files .resource-toolbar > .ant-checkbox-wrapper { margin-left: auto; font-size: var(--font-control); flex: 0 0 auto; white-space: nowrap; }
|
||||
.management-page .nc-source-files .resource-toolbar > .ant-checkbox-wrapper > span { flex: 0 0 auto; order: initial; text-align: left; overflow-wrap: normal; white-space: nowrap; }
|
||||
.nc-source-files .ant-table-cell .ant-btn { font-size: 12px; }
|
||||
.nc-source-files .ant-table-cell .ant-btn { font-size: var(--font-control); }
|
||||
.nc-source-delete-modal .nc-file-summary { margin-bottom: 20px; }
|
||||
.nc-source-delete-modal .ant-spin-container { display: flex; flex-direction: column; gap: 17px; }
|
||||
.nc-source-delete-modal .nc-review-facts, .nc-source-delete-modal .nc-file-summary { margin-bottom: 0; }
|
||||
.nc-delete-steps { padding: 3px 0 16px; border-bottom: 1px solid #dce3ee; }
|
||||
.nc-delete-request { border: 1px solid #dce3ee; padding: 14px 16px; background: #f6f8fd; }
|
||||
.nc-delete-request > div { display: flex; gap: 14px; align-items: center; font-size: 13px; }
|
||||
.nc-delete-request p { display: grid; grid-template-columns: 70px minmax(0, 1fr); gap: 14px; margin: 10px 0 0; font-size: 12px; line-height: 1.7; overflow-wrap: anywhere; }
|
||||
.nc-delete-request > div { display: flex; gap: 14px; align-items: center; font-size: var(--font-body); }
|
||||
.nc-delete-request p { display: grid; grid-template-columns: 70px minmax(0, 1fr); gap: 14px; margin: 10px 0 0; font-size: var(--font-control); line-height: 1.7; overflow-wrap: anywhere; }
|
||||
.nc-delete-request p > span { font-weight: 600; }
|
||||
.nc-source-delete-modal .nc-deletion-impact { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||
.nc-source-delete-modal .ant-alert p { margin: 0 0 7px; }
|
||||
@@ -92,35 +92,35 @@
|
||||
.nc-simplified-intake, .nc-simplified-config-page, .nc-simplified-releases { color: var(--ink); }
|
||||
.nc-simple-upload-panel { padding: 20px 22px; display: flex; flex-direction: column; gap: 16px; }
|
||||
.nc-simple-upload-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 24px; padding-bottom: 14px; border-bottom: 1px solid #dce3ee; }
|
||||
.nc-simple-upload-heading h2 { margin: 0 0 5px; color: var(--ink); font-size: 21px; line-height: 1.35; }
|
||||
.nc-simple-upload-heading p { margin: 0; color: var(--ink); font-size: 12px; line-height: 1.6; }
|
||||
.nc-simple-upload-heading h2 { margin: 0 0 5px; color: var(--ink); font-size: var(--font-page-title); line-height: 1.35; }
|
||||
.nc-simple-upload-heading p { margin: 0; color: var(--ink); font-size: var(--font-control); line-height: 1.6; }
|
||||
.nc-simple-upload-actions { display: flex; gap: 8px; align-items: center; flex: 0 0 auto; }
|
||||
.nc-simple-upload-actions .ant-btn, .nc-simplified-intake .ant-btn, .nc-simplified-config-page .ant-btn, .nc-simplified-releases .ant-btn { border-radius: 0; }
|
||||
.nc-simple-file-drop { min-height: 190px; padding: 22px; }
|
||||
.nc-simple-file-drop > .anticon { font-size: 30px; margin-bottom: 8px; }
|
||||
.nc-simple-file-drop h3 { font-size: 15px; margin: 0 0 5px; }
|
||||
.nc-simple-file-drop p { margin: 0 0 13px; font-size: 12px; }
|
||||
.nc-simple-file-line { display: flex; gap: 10px; align-items: center; min-width: 0; padding: 10px 12px; border: 1px solid #dce3ee; background: #f6f8fd; font-size: 12px; }
|
||||
.nc-simple-file-line > .anticon { flex: 0 0 auto; font-size: 19px; }
|
||||
.nc-simple-file-drop h3 { font-size: var(--font-section); margin: 0 0 5px; }
|
||||
.nc-simple-file-drop p { margin: 0 0 13px; font-size: var(--font-control); }
|
||||
.nc-simple-file-line { display: flex; gap: 10px; align-items: center; min-width: 0; padding: 10px 12px; border: 1px solid #dce3ee; background: #f6f8fd; font-size: var(--font-control); }
|
||||
.nc-simple-file-line > .anticon { flex: 0 0 auto; font-size: var(--font-page-title); }
|
||||
.nc-simple-file-line strong { min-width: 0; overflow-wrap: anywhere; }
|
||||
.nc-simple-file-line .ant-btn { margin-left: auto; flex: 0 0 auto; }
|
||||
.nc-simple-upload-fields { display: grid; grid-template-columns: repeat(4, minmax(130px, 1fr)); gap: 12px; }
|
||||
.nc-simple-upload-fields > label { display: flex; flex-direction: column; gap: 6px; color: var(--ink); font-size: 12px; }
|
||||
.nc-simple-upload-fields > label { display: flex; flex-direction: column; gap: 6px; color: var(--ink); font-size: var(--font-control); }
|
||||
.nc-simple-upload-fields .ant-select, .nc-simple-upload-fields .ant-input-number { width: 100%; }
|
||||
.nc-simple-replace-target { grid-column: span 2; }
|
||||
.nc-simple-upload-panel .ant-input-number, .nc-simple-upload-panel .ant-select-selector, .nc-simple-upload-panel .ant-input, .nc-simple-upload-panel .ant-alert { border-radius: 0 !important; }
|
||||
.nc-advanced-import-settings { border-top: 1px solid #dce3ee; padding-top: 10px; }
|
||||
.nc-advanced-import-settings > summary { color: var(--ink); cursor: pointer; font-size: 12px; padding: 2px 0 7px; }
|
||||
.nc-advanced-import-settings > summary { color: var(--ink); cursor: pointer; font-size: var(--font-control); padding: 2px 0 7px; }
|
||||
.nc-advanced-import-settings[open] > summary { margin-bottom: 10px; }
|
||||
.nc-simple-submit-row { display: flex; gap: 18px; align-items: center; justify-content: space-between; border-top: 1px solid #dce3ee; padding-top: 14px; }
|
||||
.nc-simple-submit-row > span { color: var(--ink); font-size: 12px; line-height: 1.55; }
|
||||
.nc-simple-submit-row > span { color: var(--ink); font-size: var(--font-control); line-height: 1.55; }
|
||||
.nc-simple-submit-row .ant-btn { min-width: 176px; height: 40px; }
|
||||
.nc-operation-status { display: grid; grid-template-columns: minmax(180px, 1fr) minmax(180px, 2fr); gap: 4px 18px; align-items: center; padding: 12px 16px; }
|
||||
.nc-operation-status > div:not(.ant-alert) { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
|
||||
.nc-operation-status > div:not(.ant-alert) > strong { color: var(--ink); font-size: 13px; }
|
||||
.nc-operation-status > div:not(.ant-alert) > span { overflow-wrap: anywhere; color: var(--ink); font-size: 11px; }
|
||||
.nc-operation-status > div:not(.ant-alert) > strong { color: var(--ink); font-size: var(--font-body); }
|
||||
.nc-operation-status > div:not(.ant-alert) > span { overflow-wrap: anywhere; color: var(--ink); font-size: var(--font-note); }
|
||||
.nc-operation-status .ant-alert { grid-column: 1 / -1; border-radius: 0; }
|
||||
.nc-source-maintenance-note { margin: 0; padding: 0 18px 12px; color: var(--ink); font-size: 12px; line-height: 1.6; }
|
||||
.nc-source-maintenance-note { margin: 0; padding: 0 18px 12px; color: var(--ink); font-size: var(--font-control); line-height: 1.6; }
|
||||
.nc-simple-current-config { padding: 18px 20px; }
|
||||
.nc-simple-current-config > .ant-form { max-width: 850px; }
|
||||
.nc-simple-config-tabs { margin-top: 12px; }
|
||||
@@ -129,15 +129,15 @@
|
||||
.nc-simple-config-intro > .ant-alert { flex: 1; border-radius: 0; }
|
||||
.nc-simple-config-intro .ant-alert-message, .nc-simple-config-intro .ant-alert-description { color: var(--ink); }
|
||||
.nc-simple-save-row { display: flex; gap: 18px; align-items: center; justify-content: space-between; border-top: 1px solid #dce3ee; margin-top: 18px; padding-top: 16px; }
|
||||
.nc-simple-save-row > span { color: var(--ink); font-size: 12px; line-height: 1.6; }
|
||||
.nc-simple-save-row > span { color: var(--ink); font-size: var(--font-control); line-height: 1.6; }
|
||||
.nc-simple-save-row .ant-btn { min-width: 200px; height: 42px; }
|
||||
.nc-simple-history { padding-bottom: 4px; }
|
||||
.nc-simple-config-intro + .structured-config-editor, .nc-simple-config-tabs .structured-config-editor { margin-top: 10px; }
|
||||
.nc-simple-config-tabs .ant-table-thead > tr > th, .nc-simple-history .ant-table-thead > tr > th, .nc-simplified-releases .ant-table-thead > tr > th { background: #edf2fb; color: var(--ink); }
|
||||
.nc-simple-config-page .ant-form-item-label > label { color: var(--ink); font-size: 12px; }
|
||||
.nc-simple-config-page .ant-form-item-label > label { color: var(--ink); font-size: var(--font-control); }
|
||||
.nc-simple-config-page .ant-input, .nc-simple-config-page .ant-select-selector, .nc-simple-config-page .ant-input-number, .nc-simple-config-page .ant-alert { border-radius: 0 !important; }
|
||||
.nc-simple-config-page .ant-table-cell, .nc-simplified-releases .ant-table-cell { font-size: 12px; color: var(--ink); }
|
||||
.nc-simple-config-page .json-result { max-height: 320px; overflow: auto; background: #f6f8fd; border: 1px solid #dce3ee; padding: 12px; font-size: 11px; }
|
||||
.nc-simple-config-page .ant-table-cell, .nc-simplified-releases .ant-table-cell { font-size: var(--font-control); color: var(--ink); }
|
||||
.nc-simple-config-page .json-result { max-height: 320px; overflow: auto; background: #f6f8fd; border: 1px solid #dce3ee; padding: 12px; font-size: var(--font-note); }
|
||||
.nc-simplified-releases .resource-table { padding: 0 16px 16px; }
|
||||
.nc-simplified-releases .resource-toolbar { margin-bottom: 8px; }
|
||||
@media (max-width: 850px) {
|
||||
@@ -154,5 +154,5 @@
|
||||
.nc-simple-submit-row .ant-btn, .nc-simple-save-row .ant-btn { width: 100%; }
|
||||
}
|
||||
@media (max-width: 1050px) { .nc-intake-start { grid-template-columns: 1fr; } .nc-primary-actions { margin-top: 20px; } .nc-intake-links { flex-wrap: wrap; gap: 0 16px; padding: 8px 0; } .nc-intake-links > span { margin-left: 0; width: 100%; padding: 5px 0; } .nc-column-matching { grid-template-columns: 1fr; } .nc-pending-strip { align-items: flex-start; flex-direction: column; } .nc-pending-strip .ant-select { min-width: 0; width: 100%; } }
|
||||
@media (max-width: 680px) { .nc-intake-start { padding: 20px 18px 0; } .nc-intake-intro h2 { font-size: 22px; } .nc-primary-actions { flex-wrap: wrap; } .nc-form-grid { grid-template-columns: 1fr; } .nc-modal-footer { flex-direction: column; align-items: stretch; } .nc-modal-footer > div { justify-content: flex-end; flex-wrap: wrap; } .nc-file-summary { flex-wrap: wrap; } .nc-file-summary > span:last-child { margin-left: 0; } .nc-workbook-upload-intro { flex-direction: column; align-items: flex-start; } .nc-pending-strip > div:first-child { align-items: flex-start; flex-direction: column; gap: 6px; } .nc-review-facts { grid-template-columns: 1fr 1fr; } }
|
||||
@media (max-width: 680px) { .nc-intake-start { padding: 20px 18px 0; } .nc-intake-intro h2 { font-size: var(--font-page-title); } .nc-primary-actions { flex-wrap: wrap; } .nc-form-grid { grid-template-columns: 1fr; } .nc-modal-footer { flex-direction: column; align-items: stretch; } .nc-modal-footer > div { justify-content: flex-end; flex-wrap: wrap; } .nc-file-summary { flex-wrap: wrap; } .nc-file-summary > span:last-child { margin-left: 0; } .nc-workbook-upload-intro { flex-direction: column; align-items: flex-start; } .nc-pending-strip > div:first-child { align-items: flex-start; flex-direction: column; gap: 6px; } .nc-review-facts { grid-template-columns: 1fr 1fr; } }
|
||||
@media (max-width: 680px) { .nc-source-delete-modal .nc-deletion-impact { grid-template-columns: 1fr 1fr; } }
|
||||
|
||||
@@ -21,14 +21,33 @@ export function readableMetricFormula(description: unknown): string {
|
||||
const names: Record<string, string> = {
|
||||
blackRate: '黑片合格率', brightRate: '亮片合格率', brightRateWithoutHeadquartersScrap: '亮片调整率(去本部报废)',
|
||||
compositeRate: '综合合格率', compositeRateWithoutHeadquartersScrap: '综合调整率',
|
||||
blackGood: '黑片合格重量', blackScrap: '黑片报废重量', blackTotal: '黑片适用总重量',
|
||||
brightGood: '亮片合格重量', brightScrap: '亮片报废重量', brightTotal: '亮片适用总重量', headquartersScrap: '亮片本部报废重量',
|
||||
platingWeight: '送电镀重量', shipmentWeight: '黑片出货重量', responsibilityScrap: '责废总重量', materialScrap: '材料报废重量', externalScrap: '外废重量', issueLocation: '发料地点', inspectionNote: '检验备注', applicability: '来料标志', goodWeight: '合格重量', platingScrap: '镀废重量', processingScrap: '加工废重量', diffusionScrap: '扩散报废重量', SUM: '求和',
|
||||
black_good_weight: '黑片合格重量', black_scrap_weight: '黑片报废重量', black_total_weight: '黑片总重量', black_responsibility_scrap: '黑片责废重量', black_material_scrap: '黑片料废重量', black_external_scrap: '黑片外废重量', black_reuse_scrap: '利用料及废品库报废扣减', black_reuse_good: '利用料及废品库合格扣减', bright_good_weight: '亮片合格重量', bright_scrap_weight: '亮片报废重量', bright_total_weight: '亮片总重量', bright_headquarters_scrap: '亮片本部报废重量', bright_plating_scrap: '亮片镀废重量', bright_material_scrap: '亮片材料废重量', bright_processing_scrap: '亮片加工废重量', bright_diffusion_scrap: '亮片扩散废重量',
|
||||
blackGood: '黑片合格重量', blackScrap: '黑片报废重量', blackTotal: '黑片总重量',
|
||||
brightGood: '亮片合格重量', brightScrap: '亮片报废重量', brightTotal: '亮片总重量', headquartersScrap: '亮片本部报废重量',
|
||||
};
|
||||
const outcomes: Record<string, string> = { ONE: '取1(率值100%)', ZERO: '取0', NULL: '保留空值', ERROR: '报错' };
|
||||
const nulls: Record<string, string> = { PROPAGATE: '运算结果保持空值', ZERO: '按0处理', IGNORE: '忽略空值' };
|
||||
return description.replace(/\b[A-Za-z][A-Za-z0-9]*\b/g, token => names[token] || token)
|
||||
return description.replace(/\b[A-Za-z][A-Za-z0-9_]*\b/g, token => names[token] || token)
|
||||
.replace(/\*/g, '×').replace(/\//g, '÷')
|
||||
.replace(/运算空值=(PROPAGATE|ZERO|IGNORE)/g, (_, policy: string) => `运算中遇到空值:${nulls[policy]}`)
|
||||
.replace(/零分母=(ONE|ZERO|NULL|ERROR)/g, (_, policy: string) => `分母为0:${outcomes[policy]}`)
|
||||
.replace(/空结果=(ONE|ZERO|NULL|ERROR)/g, (_, policy: string) => `计算结果为空:${outcomes[policy]}`);
|
||||
.replace(/空结果=(ONE|ZERO|NULL|ERROR)/g, (_, policy: string) => `计算结果为空:${outcomes[policy]}`)
|
||||
.replace(/适[用应]总重量/g, '总重量');
|
||||
}
|
||||
|
||||
/** Translate legacy seeded descriptions for display; stored business metadata is retained. */
|
||||
export function readableRuleDescription(value: unknown): string {
|
||||
const text = typeof value === 'string' ? value : '';
|
||||
const defaults: Record<string, string> = {
|
||||
'保留原 PQ / PP 计算口径,后续可直接维护字段、逐行公式和指标公式。': '可维护来源字段、逐行计算和指标公式。',
|
||||
'保留原黑片扣除、调整及空分母语义;原合法结果允许超过100%。': '按黑片合格重量和适用总重量计算,保留扣减与空值处理,结果允许超过100%。',
|
||||
'按原亮片合格重量及适用总重量计算,缺来源展示与公式默认值分开。': '按适用亮片合格重量与总重量计算;缺少来源和公式默认值分别处理。',
|
||||
'保留原模型本部报废调整版本,不改变默认正式亮片率。': '将本部报废重量计入亮片合格重量,适用总重量不变。',
|
||||
'保留原模型总部报废调整版本,不改变默认正式亮片率。': '将本部报废重量计入亮片合格重量,适用总重量不变。',
|
||||
'黑片率乘原模型不含本部报废的亮片率;与默认综合率分别保留。': '黑片合格率 × 去本部报废后的亮片合格率。',
|
||||
'黑片率乘原模型不含总部报废的亮片率;与默认综合率分别保留。': '黑片合格率 × 去本部报废后的亮片合格率。',
|
||||
'同一筛选范围的黑片合格率乘亮片合格率。月季年按原分量重算,不平均月率。': '同一筛选范围的黑片合格率 × 亮片合格率;月、季、年先汇总重量再计算,不平均月度合格率。',
|
||||
};
|
||||
return (defaults[text] || text).replace(/适[用应]总重量/g, '总重量');
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--metric-grid-head, #aebccc);
|
||||
border-inline-color: var(--line, #dfe5ef);
|
||||
border-radius: 6px;
|
||||
border-radius: var(--panel-radius, 5px);
|
||||
background: var(--surface, #fff);
|
||||
}
|
||||
|
||||
@@ -18,8 +18,9 @@
|
||||
.quality-table-frame .ant-table {
|
||||
color: var(--ink, #202a3b);
|
||||
background: transparent;
|
||||
font-size: 12px;
|
||||
font-size: var(--font-control);
|
||||
}
|
||||
.quality-table-frame .quality-table .ant-table.ant-table-small { font-size: var(--font-table); }
|
||||
|
||||
.quality-table-frame .ant-table-container {
|
||||
border: 0 !important;
|
||||
@@ -29,7 +30,7 @@
|
||||
padding: 10px 12px !important;
|
||||
background: color-mix(in srgb, var(--surface, #fff) 84%, var(--blue-soft, #eef1ff)) !important;
|
||||
color: var(--ink, #202a3b);
|
||||
font-size: 12px;
|
||||
font-size: var(--font-control);
|
||||
font-weight: 650;
|
||||
line-height: 1.45;
|
||||
text-align: center;
|
||||
@@ -129,3 +130,92 @@
|
||||
padding: 8px 9px !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Data intake and management use the complaint ledger's compact, single-line cells. */
|
||||
.quality-table-frame.quality-table-compact .ant-table.ant-table-small .ant-table-thead > tr > th {
|
||||
height: 34px;
|
||||
padding: 4px 8px !important;
|
||||
line-height: 22px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.quality-table-frame.quality-table-compact .ant-table.ant-table-small .ant-table-tbody > tr:not(.ant-table-measure-row) > td {
|
||||
height: 36px;
|
||||
padding: 4px 8px !important;
|
||||
line-height: 22px;
|
||||
white-space: nowrap;
|
||||
overflow-wrap: normal;
|
||||
}
|
||||
.quality-cell-preview {
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-height: 22px;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
line-height: 22px;
|
||||
}
|
||||
.quality-table-compact .quality-cell-preview:not(.quality-cell-interactive) :is(div,p,dl,dt,dd,ul,li,span,code,strong,small) {
|
||||
display: inline !important;
|
||||
margin: 0 !important;
|
||||
white-space: inherit !important;
|
||||
line-height: inherit !important;
|
||||
}
|
||||
.quality-cell-preview.quality-cell-interactive {
|
||||
max-height: none;
|
||||
overflow: visible;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.quality-cell-overflow { cursor: help; }
|
||||
.quality-cell-preview:focus-visible { outline: 2px solid var(--blue, #6379df); outline-offset: 1px; }
|
||||
.quality-cell-fulltext {
|
||||
max-width: 430px;
|
||||
max-height: min(320px, 55vh);
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
font-size: var(--font-control);
|
||||
line-height: 1.65;
|
||||
user-select: text;
|
||||
}
|
||||
.quality-table-compact .quality-cell-interactive .task-actions,
|
||||
.quality-table-compact .quality-cell-interactive .ant-space {
|
||||
display: inline-flex;
|
||||
flex-wrap: nowrap;
|
||||
align-items: center;
|
||||
gap: 6px !important;
|
||||
}
|
||||
.quality-table-compact .quality-cell-interactive .ant-btn-link {
|
||||
height: 24px;
|
||||
padding: 0;
|
||||
line-height: 24px;
|
||||
font-size: var(--font-control);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.quality-table-compact .quality-cell-interactive > .ant-btn-link,
|
||||
.quality-table-compact .quality-cell-interactive > a { max-width: 100%; }
|
||||
.quality-table-compact .quality-cell-interactive > .ant-btn-link > span:not(.ant-btn-icon),
|
||||
.quality-table-compact .quality-cell-interactive > a { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.quality-table-compact .quality-cell-interactive :is(.ant-input,.ant-input-number,.ant-input-affix-wrapper,.ant-select) {
|
||||
min-height: 26px !important;
|
||||
height: 26px !important;
|
||||
font-size: var(--font-control);
|
||||
}
|
||||
.quality-table-compact .quality-cell-interactive .ant-input {
|
||||
padding-block: 2px;
|
||||
line-height: 20px;
|
||||
}
|
||||
.quality-table-compact .quality-cell-interactive .ant-input-number-input {
|
||||
height: 24px;
|
||||
}
|
||||
.quality-table-compact .quality-cell-interactive .ant-tag { margin-block: 0; }
|
||||
.quality-table-compact .compact-task-progress {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 26px;
|
||||
}
|
||||
.quality-table-compact .compact-task-progress .ant-progress { flex: 1; min-width: 70px; margin: 0; }
|
||||
.quality-table-compact .ant-table-placeholder .ant-empty { margin: 0 !important; }
|
||||
.quality-table-compact .ant-table-placeholder .ant-empty-image { display: none; }
|
||||
.quality-table-compact .ant-table-placeholder .ant-table-expanded-row-fixed { padding: 0 !important; margin: 0 !important; max-width: 100%; }
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { MetricRow, QueryParams, ViewKind } from './types';
|
||||
|
||||
/** Freeze the clicked metric's filters and release together for every detail/export request. */
|
||||
export function freezeSourceRecordsQuery(query: QueryParams, releaseId: string, view: ViewKind, row: MetricRow | null, month?: number): QueryParams {
|
||||
if (!releaseId) throw new Error('指标数据尚未就绪,请重新查询后打开来源明细。');
|
||||
const frozen = JSON.parse(JSON.stringify(query)) as QueryParams;
|
||||
frozen.releaseId = releaseId;
|
||||
if (month) { frozen.month = month; delete frozen.quarter; }
|
||||
if (row && view !== 'overall') {
|
||||
const dimension = view === 'projectGroup' ? 'projectGroup' : view;
|
||||
frozen[dimension] = row.key === '__UNASSIGNED__' ? '__UNASSIGNED__' : row[dimension] || row.key;
|
||||
}
|
||||
return frozen;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
.stage-product-page .query-toolbar { gap: 10px; }
|
||||
.stage-source-filters { display: contents; }
|
||||
.stage-source-filters > .ant-select { width: 220px; }
|
||||
.stage-source-filter-row { flex: 1 0 100%; display: grid; grid-template-columns: minmax(120px,180px) 150px minmax(240px,1fr) 32px; align-items: center; gap: 10px; }
|
||||
.stage-source-filter-row > strong { overflow-wrap: anywhere; font-size: var(--font-body); }
|
||||
.stage-source-filter-row > .ant-select { width: 100%; min-width: 0; }
|
||||
.stage-query-pending { flex-basis: 100%; color: var(--muted-ink); font-size: var(--font-control); }
|
||||
.stage-product-page .query-field > .ant-select { min-width: 110px; }
|
||||
.stage-product-page .query-primary-field > .ant-select { min-width: 0; }
|
||||
@media(max-width:760px) {
|
||||
.stage-source-filter-row { grid-template-columns: minmax(0,1fr) 140px 32px; }
|
||||
.stage-source-filter-row > .ant-select:nth-of-type(2) { grid-column: 1 / 3; grid-row: 2; }
|
||||
.stage-source-filter-row > .ant-btn { grid-column: 3; grid-row: 1; }
|
||||
.stage-metric-strip { grid-template-columns: repeat(2,minmax(0,1fr)); }
|
||||
}
|
||||
|
||||
.stage-product-page .defects-panel > .defect-stage-column { padding: 14px; }
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { MetricRow, QueryParams, SourceColumnFilter, Stage } from './types';
|
||||
export function activeStageFilters(filters:SourceColumnFilter[],stage:Stage):SourceColumnFilter[] {
|
||||
return filters.filter(rule=>rule.operator==='is_empty'||rule.operator==='not_empty'||!!rule.values?.length).map(rule=>({...rule,stages:[stage],values:rule.values?[...rule.values]:[]}));
|
||||
}
|
||||
export function stageProductQuery(base:QueryParams,stage:Stage,filters:SourceColumnFilter[]):QueryParams {
|
||||
return {...base,view:'product',stage,columnFilters:activeStageFilters(filters,stage)};
|
||||
}
|
||||
|
||||
/** Sort product summaries only; leave the source rows and chronological trends unchanged. */
|
||||
export function sortStageRowsByTotalWeight(rows:MetricRow[],stage:Stage):MetricRow[] {
|
||||
const total=(row:MetricRow)=>typeof row[stage].totalWeight==='number'&&Number.isFinite(row[stage].totalWeight)?row[stage].totalWeight!:Number.NEGATIVE_INFINITY;
|
||||
return [...rows].sort((left,right)=>{
|
||||
const a=total(left),b=total(right);
|
||||
return a===b?0:a>b?-1:1;
|
||||
});
|
||||
}
|
||||
@@ -3,34 +3,34 @@
|
||||
.structured-config-toolbar, .structured-config-intro { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-bottom: 14px; }
|
||||
.structured-config-toolbar > .ant-input-search { width: 230px; }
|
||||
.structured-config-toolbar > .ant-select { min-width: 115px; }
|
||||
.structured-config-toolbar > span { font-size: 12px; }
|
||||
.structured-config-toolbar > span { font-size: var(--font-control); }
|
||||
.structured-config-actions { display: flex; flex-wrap: wrap; gap: 7px; margin-left: auto; }
|
||||
.structured-config-intro { justify-content: space-between; background: #f6f8fd; border: 1px solid #dce3ee; padding: 12px 14px; }
|
||||
.structured-config-intro p, .structured-config-note { color: var(--ink); font-size: 12px; line-height: 1.65; margin: 0; }
|
||||
.structured-config-intro p, .structured-config-note { color: var(--ink); font-size: var(--font-control); line-height: 1.65; margin: 0; }
|
||||
.structured-config-note { margin-top: 10px; }
|
||||
.structured-config-muted { color: #657185; }
|
||||
.structured-config-editor .ant-table-thead > tr > th { background: #f6f8fd; color: var(--ink); }
|
||||
.structured-config-editor .ant-table-cell { font-size: 12px; overflow-wrap: anywhere; }
|
||||
.structured-config-editor .ant-table-cell { font-size: var(--font-control); overflow-wrap: anywhere; }
|
||||
.structured-config-editor .ant-table-container, .structured-config-editor .ant-btn, .structured-config-editor .ant-input, .structured-config-editor .ant-select-selector, .structured-config-modal .ant-btn, .structured-config-modal .ant-input, .structured-config-modal .ant-select-selector { border-radius: 0 !important; }
|
||||
.structured-config-modal .ant-modal-body { max-height: calc(var(--viewport-height) * .72); overflow-y: auto; padding-top: 16px; }
|
||||
.structured-config-modal p { color: var(--ink); font-size: 12px; line-height: 1.65; }
|
||||
.structured-config-modal p { color: var(--ink); font-size: var(--font-control); line-height: 1.65; }
|
||||
.structured-config-modal .ant-checkbox-wrapper { margin: 12px 0; }
|
||||
.structured-config-form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
|
||||
.structured-config-select-hint { padding: 8px 12px; color: #667085; font-size: 12px; border-top: 1px solid #dce3ee; }
|
||||
.structured-config-select-hint { padding: 8px 12px; color: #667085; font-size: var(--font-control); border-top: 1px solid #dce3ee; }
|
||||
.structured-config-technical { margin-top: 18px; padding-top: 14px; border-top: 1px solid #dce3ee; }
|
||||
.structured-config-technical summary { cursor: pointer; font-size: 12px; margin-bottom: 12px; }
|
||||
.structured-config-technical summary { cursor: pointer; font-size: var(--font-control); margin-bottom: 12px; }
|
||||
.structured-config-technical > .ant-btn { margin-top: 8px; }
|
||||
.structured-config-rule-list { display: flex; flex-direction: column; gap: 14px; }
|
||||
.structured-config-rule-card { border: 1px solid #dce3ee; padding: 14px; background: #fff; }
|
||||
.structured-config-rule-card h4 { margin: 0 0 12px; color: var(--ink); }
|
||||
.structured-config-rule-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
|
||||
.structured-config-rule-grid > div:first-child { grid-column: 1 / -1; }
|
||||
.structured-config-rule-grid label { display: block; margin-bottom: 6px; font-size: 12px; }
|
||||
.structured-config-rule-grid label { display: block; margin-bottom: 6px; font-size: var(--font-control); }
|
||||
.structured-config-rule-grid .ant-form-item { margin-bottom: 10px; }
|
||||
.structured-config-error-list { margin: 8px 0 0; padding-left: 20px; max-height: 180px; overflow: auto; }
|
||||
.structured-match-editor .structured-config-toolbar { align-items: flex-start; }
|
||||
.structured-match-editor .structured-config-toolbar > span { max-width: 780px; line-height: 1.6; }
|
||||
.structured-match-editor .structured-match-readable { display: block; color: var(--ink); font-size: 12px; line-height: 1.6; white-space: normal; }
|
||||
.structured-match-editor .structured-match-readable { display: block; color: var(--ink); font-size: var(--font-control); line-height: 1.6; white-space: normal; }
|
||||
.structured-match-editor .ant-table-cell { vertical-align: top; }
|
||||
.structured-match-editor .ant-table-cell .ant-select-selector, .structured-match-editor .ant-table-cell .ant-input { border-radius: 0 !important; }
|
||||
.structured-match-editor .ant-table-thead > tr > th { background: #edf2fb; color: var(--ink); }
|
||||
|
||||
+150
-132
@@ -1,5 +1,7 @@
|
||||
@import './typography.css';
|
||||
|
||||
:root {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
font-family: var(--font-ui);
|
||||
color: #111111;
|
||||
background: #f4f6fb;
|
||||
font-synthesis: none;
|
||||
@@ -23,22 +25,22 @@
|
||||
html { zoom: var(--ui-scale); }
|
||||
@media (max-width: 760px) { :root { --ui-scale: 1; } }
|
||||
html, body, #root { min-width: 320px; min-height: 100%; margin: 0; }
|
||||
body { color: var(--ink); background: #f4f6fb; font-size: 14px; }
|
||||
body { color: var(--ink); background: #f4f6fb; font-size: var(--font-body); }
|
||||
button, input, textarea, select { font: inherit; }
|
||||
button { color: inherit; }
|
||||
.app-shell { min-height: var(--viewport-height); }
|
||||
.sidebar { position: fixed; inset: 0 auto 0 0; z-index: 15; display: flex; width: var(--sidebar); flex-direction: column; padding: 16px 12px 10px; background: #f8f9fc; border-right: 1px solid var(--line); }
|
||||
.brand { display: flex; align-items: center; gap: 8px; min-height: 34px; padding: 0 7px; border: 0; background: transparent; text-align: left; font-size: 16px; font-weight: 700; cursor: pointer; white-space: nowrap; }
|
||||
.brand { display: flex; align-items: center; gap: 8px; min-height: 34px; padding: 0 7px; border: 0; background: transparent; text-align: left; font-size: var(--font-dialog-title); font-weight: 700; cursor: pointer; white-space: nowrap; }
|
||||
.brand-mark { display: inline-flex; align-items: center; gap: 2px; width: 22px; height: 23px; transform: skew(-17deg); }
|
||||
.brand-mark i { display: block; width: 4px; height: 17px; background: var(--blue); }
|
||||
.brand-mark i:nth-child(2) { height: 21px; opacity: .76; }
|
||||
.brand-mark i:nth-child(3) { height: 13px; opacity: .52; }
|
||||
.workspace-caption { padding: 5px 7px 17px; font-size: 12px; font-weight: 600; }
|
||||
.workspace-caption { padding: 5px 7px 17px; font-size: var(--font-control); font-weight: 600; }
|
||||
.side-navigation { flex: 1; overflow: auto; scrollbar-width: thin; }
|
||||
.nav-group { margin-top: 12px; }
|
||||
.nav-group-label { padding: 7px 9px 6px; color: var(--ink); font-size: 12px; font-weight: 650; }
|
||||
.nav-item { display: flex; width: 100%; min-height: 36px; align-items: center; gap: 10px; padding: 7px 9px; border: 0; background: transparent; text-align: left; cursor: pointer; font-size: 13px; }
|
||||
.nav-item .anticon { width: 16px; color: var(--ink); font-size: 15px; }
|
||||
.nav-group-label { padding: 7px 9px 6px; color: var(--ink); font-size: var(--font-control); font-weight: 650; }
|
||||
.nav-item { display: flex; width: 100%; min-height: 36px; align-items: center; gap: 10px; padding: 7px 9px; border: 0; background: transparent; text-align: left; cursor: pointer; font-size: var(--font-body); }
|
||||
.nav-item .anticon { width: 16px; color: var(--ink); font-size: var(--font-dialog-title); }
|
||||
.nav-item:hover { background: #eef2fb; }
|
||||
.nav-item.active { color: var(--blue-dark); background: #e3ebff; font-weight: 650; }
|
||||
.nav-item.active .anticon { color: var(--blue); }
|
||||
@@ -47,32 +49,46 @@ button { color: inherit; }
|
||||
.user-profile-trigger { display: flex; min-width: 0; flex: 1; align-items: center; gap: 9px; padding: 0; border: 0; background: transparent; text-align: left; cursor: pointer; }
|
||||
.user-profile-trigger:focus-visible { outline: 2px solid var(--blue); outline-offset: 3px; }
|
||||
.personal-account-modal :is(.ant-modal-container,.ant-modal-content,.ant-modal-header) { background: var(--surface); color: var(--ink); }
|
||||
.avatar { display: inline-flex; width: 31px; height: 31px; flex: 0 0 31px; align-items: center; justify-content: center; background: #e7edf5; font-size: 13px; }
|
||||
.avatar { display: inline-flex; width: 31px; height: 31px; flex: 0 0 31px; align-items: center; justify-content: center; background: #e7edf5; font-size: var(--font-body); }
|
||||
.user-copy { display: flex; min-width: 0; flex: 1; flex-direction: column; gap: 3px; }
|
||||
.user-copy strong { overflow: hidden; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.user-copy small { overflow: hidden; font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.user-copy strong { overflow: hidden; font-size: var(--font-control); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.user-copy small { overflow: hidden; font-size: var(--font-note); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.user-block .ant-btn { width: 28px; padding: 0; }
|
||||
.main-column { min-height: var(--viewport-height); margin-left: var(--sidebar); }
|
||||
.topbar { position: sticky; top: 0; z-index: 40; display: flex; height: 44px; align-items: center; justify-content: space-between; padding: 0 22px; background: #ffffff; border-bottom: 1px solid var(--line); }
|
||||
.breadcrumb { display: flex; align-items: center; gap: 10px; font-size: 12px; }
|
||||
.workspace-heading { display: flex; align-items: center; gap: 8px; min-width: 0; }
|
||||
.sidebar-toggle.ant-btn { width: 28px; height: 28px; padding: 0; }
|
||||
@media (min-width: 761px) {
|
||||
.app-shell.sidebar-collapsed { --sidebar: 60px; }
|
||||
.sidebar-collapsed .sidebar { padding-inline: 8px; }
|
||||
.sidebar-collapsed :is(.brand-copy,.workspace-caption,.nav-group-label,.nav-item-label,.user-copy) { display: none; }
|
||||
.sidebar-collapsed .brand { justify-content: center; padding-inline: 0; margin-bottom: 12px; }
|
||||
.sidebar-collapsed .nav-item { justify-content: center; padding-inline: 0; }
|
||||
.sidebar-collapsed .nav-group { margin-top: 8px; padding-top: 8px; border-top: 1px solid var(--line); }
|
||||
.sidebar-collapsed .nav-group:first-child { margin-top: 0; padding-top: 0; border-top: 0; }
|
||||
.sidebar-collapsed .user-block { flex-direction: column; gap: 8px; padding-top: 10px; }
|
||||
.sidebar-collapsed .user-profile-trigger { flex: 0; }
|
||||
}
|
||||
@media (max-width: 760px) { .sidebar-toggle.ant-btn { display: none; } }
|
||||
.topbar { position: sticky; top: 0; z-index: 40; display: flex; height: 44px; align-items: center; justify-content: space-between; padding: 0 22px; background: var(--surface); border-bottom: 1px solid var(--line); }
|
||||
.breadcrumb { display: flex; align-items: center; gap: 10px; font-size: var(--font-control); }
|
||||
.breadcrumb strong { font-weight: 650; }
|
||||
.breadcrumb-slash { color: #63738a; }
|
||||
.top-organization { display: inline-flex; align-items: center; gap: 7px; font-size: 12px; }
|
||||
.top-organization { display: inline-flex; align-items: center; gap: 7px; font-size: var(--font-control); }
|
||||
.mobile-brand { display: none; }
|
||||
.page-content { width: 100%; min-width: 0; margin: 0; padding: 15px 20px 20px; }
|
||||
.panel { background: var(--surface); border: 1px solid var(--line); border-radius: 0 !important; }
|
||||
.panel { background: var(--surface); border: 1px solid var(--line); border-radius: var(--panel-radius, 5px) !important; }
|
||||
.query-page { display: flex; min-width: 0; flex-direction: column; gap: 11px; }
|
||||
.query-toolbar { position: sticky; top: 53px; z-index: 35; display: flex; min-height: 48px; flex-wrap: wrap; align-items: center; gap: 10px 13px; padding: 7px 11px; }
|
||||
.query-toolbar::before { content: ''; position: absolute; right: -20px; bottom: 100%; left: -20px; height: 18px; background: var(--background); pointer-events: none; }
|
||||
.query-field { display: inline-flex; min-width: 0; align-items: center; gap: 7px; }
|
||||
.query-field > span { flex: 0 0 auto; white-space: nowrap; font-size: 12px; }
|
||||
.query-field > span { flex: 0 0 auto; white-space: nowrap; font-size: var(--font-control); }
|
||||
.query-field .ant-select { min-width: 108px; }
|
||||
.query-field .ant-select-selector { border-radius: 0 !important; }
|
||||
.query-field .ant-select-selector { border-radius: var(--control-radius, 4px) !important; }
|
||||
.query-field.release-field .ant-select { min-width: 180px; }
|
||||
.readable-select-popup { max-width: calc(100vw - 24px); }
|
||||
.readable-select-popup .ant-select-item-option-content { overflow: visible; text-overflow: clip; white-space: normal; overflow-wrap: anywhere; }
|
||||
.query-toolbar-tail { display: flex; min-width: max-content; flex: 1; align-items: center; justify-content: flex-end; gap: 8px; margin-left: auto; }
|
||||
.query-status { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; white-space: nowrap; }
|
||||
.query-status { display: inline-flex; align-items: center; gap: 6px; font-size: var(--font-control); white-space: nowrap; }
|
||||
.query-status i { width: 7px; height: 7px; background: var(--teal); }
|
||||
.query-status.busy i { background: #d18a2e; }
|
||||
.query-status.failed i { background: #bd342e; }
|
||||
@@ -81,78 +97,78 @@ button { color: inherit; }
|
||||
.metric-card:last-child { border-right: 0; }
|
||||
.metric-card:hover { background: #f8faff; }
|
||||
.metric-card.primary { background: #e8efff; }
|
||||
.metric-label { display: inline-flex; align-items: center; gap: 7px; font-size: 13px; font-weight: 650; }
|
||||
.metric-card.primary .metric-label { font-size: clamp(15px, 1.5vw, 18px); font-weight: 700; }
|
||||
.metric-value { overflow: hidden; max-width: 100%; font: 600 clamp(22px, 2.15vw, 31px)/1.15 var(--mono); letter-spacing: -1.2px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.metric-card.primary .metric-value { font-size: clamp(26px, 2.5vw, 36px); }
|
||||
.metric-label { display: inline-flex; align-items: center; gap: 7px; font-size: var(--font-body); font-weight: 650; }
|
||||
.metric-card.primary .metric-label { font-size: var(--font-section); font-weight: 700; }
|
||||
.metric-value { overflow: hidden; max-width: 100%; font: 700 var(--font-metric)/1.15 var(--font-numeric); letter-spacing: -.6px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.metric-card.primary .metric-value { font-size: var(--font-metric-primary); }
|
||||
.metric-card.black .metric-value { color: var(--blue-dark); }
|
||||
.metric-card.bright .metric-value { color: var(--teal); }
|
||||
.metric-card small { font-size: 11px; line-height: 1.4; }
|
||||
.metric-card small { font-size: var(--font-note); line-height: 1.4; }
|
||||
.stage-dot { width: 7px; height: 7px; background: var(--blue); }
|
||||
.stage-dot.bright { background: var(--teal); }
|
||||
.section-panel { min-width: 0; overflow: hidden; }
|
||||
.section-heading-row { display: flex; min-height: 45px; align-items: center; justify-content: space-between; gap: 12px; padding: 8px 13px; }
|
||||
.section-heading { display: flex; min-width: 0; align-items: baseline; gap: 12px; }
|
||||
.section-heading h2 { margin: 0; font-size: 14px; font-weight: 650; }
|
||||
.section-heading > span { font-size: 12px; }
|
||||
.table-tools { display: flex; min-width: 0; align-items: center; justify-content: flex-end; gap: 7px; }
|
||||
.table-tools .ant-input-affix-wrapper { width: 205px; border-radius: 0; }
|
||||
.table-tools .ant-segmented { flex: 0 0 auto; border-radius: 0; }
|
||||
.section-heading h2 { margin: 0; font-size: var(--font-section); font-weight: 650; }
|
||||
.section-heading > span { font-size: var(--font-control); }
|
||||
.table-tools { display: flex; flex-wrap: wrap; min-width: 0; align-items: center; justify-content: flex-end; gap: 7px; }
|
||||
.table-tools .ant-input-affix-wrapper { width: 205px; border-radius: var(--control-radius, 4px); }
|
||||
.table-tools .ant-segmented { flex: 0 0 auto; border-radius: var(--control-radius, 4px); }
|
||||
.metric-table-scroll { min-width: 0; }
|
||||
.metric-table-scroll .ant-table-wrapper { min-width: 0; }
|
||||
.metric-table-scroll .ant-table { font-size: 13px; }
|
||||
.metric-table-scroll .ant-table { font-size: var(--font-table); }
|
||||
.metric-table-scroll .ant-table-container { border-color: var(--metric-grid-head) !important; }
|
||||
.metric-table-scroll .ant-table-cell { padding: 5px 9px !important; border-inline-end: 1px solid var(--metric-grid) !important; border-bottom: 1px solid var(--metric-grid) !important; text-align: center !important; white-space: normal; }
|
||||
.metric-table-scroll .ant-table-thead > tr > th { min-height: 36px; border-inline-end: 1px solid var(--metric-grid-head) !important; border-bottom: 1px solid var(--metric-grid-head) !important; text-align: center; font-size: 12px; font-weight: 650; line-height: 1.4; }
|
||||
.metric-table-scroll .ant-table-thead > tr > th { min-height: 36px; border-inline-end: 1px solid var(--metric-grid-head) !important; border-bottom: 1px solid var(--metric-grid-head) !important; text-align: center; font-size: var(--font-control); font-weight: 650; line-height: 1.4; }
|
||||
.metric-table-scroll .ant-table-tbody > tr > td { height: 32px; }
|
||||
.metric-table-scroll .ant-table-tbody > tr > td.ant-table-cell-fix-left { background: #fff; }
|
||||
.metric-table-scroll .combined-column, .metric-table-scroll .combined-column.ant-table-cell-fix-left { background: #ebf0ff !important; }
|
||||
.metric-table-scroll th.combined-column { background: #ebf0ff !important; }
|
||||
.metric-table-scroll .ant-table-tbody > tr > td.ant-table-cell-fix-left { background: var(--surface); }
|
||||
.metric-table-scroll .combined-column, .metric-table-scroll .combined-column.ant-table-cell-fix-left { background: var(--table-combined, var(--blue-soft)) !important; }
|
||||
.metric-table-scroll th.combined-column { background: var(--table-combined, var(--blue-soft)) !important; }
|
||||
.object-drilldown.ant-btn { height: auto; min-height: 22px; padding: 0; color: var(--ink); font-weight: 600; white-space: normal; }
|
||||
.object-drilldown.ant-btn:hover { color: var(--blue-dark); }
|
||||
.metric-table-pagination { display: flex; justify-content: flex-end; padding: 10px 13px; border-top: 1px solid var(--metric-grid); }
|
||||
.object-cell { display: flex; min-width: 0; flex-direction: column; align-items: center; gap: 3px; overflow-wrap: anywhere; text-align: center; white-space: normal; }
|
||||
.object-cell strong { color: var(--ink); font-weight: 600; }
|
||||
.object-cell small { font-size: 11px; }
|
||||
.month-state { width: fit-content; padding: 1px 3px; border: 1px solid #dce3ee; font-size: 10px !important; }
|
||||
.combined-value, .header-link { padding: 0; border: 0; background: transparent; color: var(--ink); font: 650 13px var(--mono); cursor: pointer; }
|
||||
.object-cell small { font-size: var(--font-note); }
|
||||
.month-state { width: fit-content; padding: 1px 3px; border: 1px solid #dce3ee; font-size: var(--font-note) !important; }
|
||||
.combined-value, .header-link { padding: 0; border: 0; background: transparent; color: var(--ink); font: 600 var(--font-table) var(--font-numeric); cursor: pointer; }
|
||||
.combined-value:hover, .header-link:hover { color: var(--blue-dark); text-decoration: underline; text-underline-offset: 3px; }
|
||||
.combined-value.static { cursor: default; }
|
||||
.table-value.ant-btn { height: auto; min-height: 20px; padding: 0; color: var(--ink); font: 13px var(--mono); }
|
||||
.rate-cell.black .table-value { color: var(--blue-dark); font-weight: 650; }
|
||||
.rate-cell.bright .table-value { color: var(--teal); font-weight: 650; }
|
||||
.table-value.ant-btn { height: auto; min-height: 20px; padding: 0; color: var(--ink); font: 500 var(--font-table) var(--font-numeric); font-variant-numeric: tabular-nums lining-nums; }
|
||||
.rate-cell.black .table-value { color: var(--blue-dark); font-weight: 600; }
|
||||
.rate-cell.bright .table-value { color: var(--teal); font-weight: 600; }
|
||||
.stage-heading { display: inline-flex; align-items: center; gap: 6px; font-weight: 650; }
|
||||
.stage-heading i { display: inline-block; width: 7px; height: 7px; background: var(--blue); }
|
||||
.stage-heading.bright i { background: var(--teal); }
|
||||
.stage-heading.black { color: var(--blue-dark); }
|
||||
.stage-heading.bright { color: var(--teal); }
|
||||
.metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.black) { background: #e8edff; }
|
||||
.metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.bright) { background: #def4ee; }
|
||||
.table-footer { display: flex; min-height: 34px; align-items: center; justify-content: space-between; gap: 12px; padding: 6px 13px; border-top: 1px solid var(--line); font-size: 11px; }
|
||||
.mobile-scroll-hint { display: none; padding: 0 12px 8px; font-size: 11px; }
|
||||
.metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.black) { background: var(--blue-soft); }
|
||||
.metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.bright) { background: var(--table-bright-head); }
|
||||
.table-footer { display: flex; min-height: 34px; align-items: center; justify-content: space-between; gap: 12px; padding: 6px 13px; border-top: 1px solid var(--line); font-size: var(--font-note); }
|
||||
.mobile-scroll-hint { display: none; padding: 0 12px 8px; font-size: var(--font-note); }
|
||||
.analysis-stack { display: grid; min-width: 0; grid-template-columns: minmax(0, 1fr); gap: 12px; }
|
||||
.trend-heading-row { flex-wrap: wrap; }
|
||||
.trend-controls { display: flex; min-height: 38px; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 9px; padding: 0 13px 9px; }
|
||||
.trend-chart-shell { position: relative; min-height: 380px; }
|
||||
.trend-refresh-indicator { position: absolute; top: 8px; right: 13px; z-index: 1; display: inline-flex; align-items: center; gap: 7px; padding: 5px 8px; border: 1px solid var(--line); background: var(--surface); font-size: 11px; pointer-events: none; }
|
||||
.trend-refresh-indicator { position: absolute; top: 8px; right: 13px; z-index: 1; display: inline-flex; align-items: center; gap: 7px; padding: 5px 8px; border: 1px solid var(--line); background: var(--surface); font-size: var(--font-note); pointer-events: none; }
|
||||
.trend-object { flex: 1 1 250px; }
|
||||
.trend-object .ant-select { width: min(420px, 100%); }
|
||||
.chart-viewport { width: 100%; overflow-x: auto; }
|
||||
.chart-surface { position: relative; width: 100%; min-width: 0; }
|
||||
/* Keep SVG chart coordinates aligned with pointer events under the app's global UI zoom. */
|
||||
.chart-container { width: 100%; height: calc(380px * var(--ui-scale)); min-width: 0; zoom: calc(1 / var(--ui-scale)); }
|
||||
.chart-footnote { display: flex; justify-content: space-between; gap: 12px; padding: 0 13px 10px; font-size: 11px; }
|
||||
.chart-footnote { display: flex; justify-content: space-between; gap: 12px; padding: 0 13px 10px; font-size: var(--font-note); }
|
||||
.defects-panel { min-height: 120px; }
|
||||
.defect-stage-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); border-top: 1px solid var(--line); }
|
||||
.defect-pareto-section { padding: 0 12px 10px; border-top: 1px solid var(--line); }
|
||||
.defect-pareto-heading { display: flex; min-height: 38px; flex-wrap: wrap; align-items: baseline; gap: 5px 12px; padding: 8px 1px 0; }
|
||||
.defect-pareto-heading strong { font-size: 13px; font-weight: 650; }
|
||||
.defect-pareto-heading span { color: var(--ink); font-size: 11px; }
|
||||
.defect-pareto-heading strong { font-size: var(--font-body); font-weight: 650; }
|
||||
.defect-pareto-heading span { color: var(--ink); font-size: var(--font-note); }
|
||||
.defect-pareto-chart { width: 100%; height: calc(470px * var(--ui-scale)); min-width: 0; zoom: calc(1 / var(--ui-scale)); }
|
||||
.defect-pareto-status { display: flex; min-height: 52px; align-items: center; justify-content: center; gap: 8px; font-size: 12px; }
|
||||
.defect-pareto-status { display: flex; min-height: 52px; align-items: center; justify-content: center; gap: 8px; font-size: var(--font-control); }
|
||||
.defect-stage-column { min-width: 0; padding: 0 12px 10px; }
|
||||
.defect-stage-column + .defect-stage-column { border-left: 1px solid var(--line); }
|
||||
.defect-stage-title { display: flex; align-items: center; gap: 7px; margin: 0; padding: 11px 1px 4px; font-size: 13px; font-weight: 650; }
|
||||
.defect-stage-title { display: flex; align-items: center; gap: 7px; margin: 0; padding: 11px 1px 4px; font-size: var(--font-body); font-weight: 650; }
|
||||
.defect-stage-title i { width: 7px; height: 7px; background: var(--blue); }
|
||||
.defect-stage-title.bright i { background: var(--teal); }
|
||||
.defect-stage-title.black { color: var(--blue-dark); }
|
||||
@@ -160,7 +176,7 @@ button { color: inherit; }
|
||||
.defect-stage-column .ant-empty { margin: 13px 0 10px; }
|
||||
.defect-list { padding: 2px 0 0; }
|
||||
.defect-header, .defect-row { display: grid; grid-template-columns: minmax(72px, 95px) minmax(32px, 1fr) minmax(78px, 100px) 57px 57px; align-items: center; gap: 7px; }
|
||||
.defect-header { min-height: 27px; font-size: 11px; text-align: right; }
|
||||
.defect-header { min-height: 27px; font-size: var(--font-note); text-align: right; }
|
||||
.defect-header span:first-child { text-align: left; }
|
||||
.defect-row { width: 100%; min-height: 31px; padding: 4px 0; border: 0; background: transparent; text-align: left; cursor: pointer; }
|
||||
.defect-row:hover .defect-name { color: var(--blue-dark); text-decoration: underline; }
|
||||
@@ -168,19 +184,19 @@ button { color: inherit; }
|
||||
.defect-track { height: 8px; background: #eef1f6; }
|
||||
.defect-track i { display: block; height: 100%; background: var(--blue); transition: width 460ms cubic-bezier(.2,.7,.2,1); }
|
||||
.defect-track i.bright { background: var(--teal); }
|
||||
.defect-weight, .defect-rate { text-align: right; font: 12px var(--mono); }
|
||||
.query-footer { display: flex; align-items: center; justify-content: space-between; gap: 10px; font-size: 11px; }
|
||||
.defect-weight, .defect-rate { text-align: right; font: var(--font-control) var(--font-numeric); font-variant-numeric: tabular-nums; }
|
||||
.query-footer { display: flex; align-items: center; justify-content: space-between; gap: 10px; font-size: var(--font-note); }
|
||||
.query-footer .ant-btn { padding: 0; }
|
||||
.basis-card { display: flex; flex-direction: column; align-items: center; gap: 8px; margin: 5px 0 14px; padding: 17px; background: #eef2fc; border: 1px solid var(--line); text-align: center; }
|
||||
.basis-card strong { font: 650 35px var(--mono); }
|
||||
.basis-card strong { font: 700 35px var(--font-numeric); }
|
||||
.basis-copy { line-height: 1.7; }
|
||||
.basis-details { display: grid; grid-template-columns: 110px minmax(0, 1fr); gap: 9px 12px; margin: 16px 0 0; font-size: 12px; }
|
||||
.basis-details { display: grid; grid-template-columns: 110px minmax(0, 1fr); gap: 9px 12px; margin: 16px 0 0; font-size: var(--font-control); }
|
||||
.basis-details dt { font-weight: 650; }
|
||||
.basis-details dd { margin: 0; overflow-wrap: anywhere; }
|
||||
.drawer-title { display: flex; flex-direction: column; gap: 3px; }
|
||||
.drawer-title small { font-weight: 400; font-size: 12px; }
|
||||
.drawer-controls { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 12px; font-size: 12px; }
|
||||
.json-cell { max-width: 360px; max-height: 140px; overflow: auto; margin: 0; font: 11px/1.45 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.drawer-title small { font-weight: 400; font-size: var(--font-control); }
|
||||
.drawer-controls { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 12px; font-size: var(--font-control); }
|
||||
.json-cell { max-width: 360px; max-height: 140px; overflow: auto; margin: 0; font: var(--font-note)/1.45 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.records-pagination { display: flex; justify-content: flex-end; margin-top: 14px; }
|
||||
.loading-panel { display: flex; min-height: 170px; align-items: center; justify-content: center; gap: 11px; }
|
||||
.loading-panel.compact { min-height: 240px; }
|
||||
@@ -188,16 +204,16 @@ button { color: inherit; }
|
||||
.chart-footnote span:first-child { overflow-wrap: anywhere; }
|
||||
.management-page { display: flex; flex-direction: column; gap: 12px; }
|
||||
.page-heading { display: flex; min-height: 52px; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.page-heading h1 { margin: 0; font-size: 19px; font-weight: 650; }
|
||||
.page-heading p { margin: 5px 0 0; font-size: 12px; line-height: 1.55; }
|
||||
.page-heading h1 { margin: 0; font-size: var(--font-page-title); font-weight: 650; }
|
||||
.page-heading p { margin: 5px 0 0; font-size: var(--font-control); line-height: 1.55; }
|
||||
.page-heading-actions { display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 8px; }
|
||||
.resource-toolbar { display: flex; min-height: 42px; align-items: center; gap: 12px; padding: 6px 12px; }
|
||||
.resource-toolbar strong { font-size: 13px; }
|
||||
.resource-toolbar span { flex: 1; font-size: 11px; text-align: right; }
|
||||
.resource-toolbar strong { font-size: var(--font-section); }
|
||||
.resource-toolbar span { flex: 1; font-size: var(--font-note); text-align: right; }
|
||||
.resource-table { min-width: 0; }
|
||||
.resource-table .ant-table-cell { padding: 7px 9px !important; font-size: 12px; }
|
||||
.resource-table .ant-table-cell { padding: 7px 9px !important; font-size: var(--font-control); }
|
||||
.resource-table .ant-table-thead > tr > th { text-align: center; }
|
||||
.table-caption { margin: 6px 12px 9px; font-size: 11px; }
|
||||
.table-caption { margin: 6px 12px 9px; font-size: var(--font-note); }
|
||||
.task-error { color: #a12a24; }
|
||||
.task-detail-summary { display: flex; flex-direction: column; gap: 8px; margin-bottom: 14px; }
|
||||
.task-actions { display: inline-flex; flex-wrap: wrap; align-items: center; justify-content: center; }
|
||||
@@ -206,21 +222,21 @@ button { color: inherit; }
|
||||
.import-validation { display: flex; flex-direction: column; gap: 10px; padding: 0 8px; }
|
||||
.import-validation-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(135px, 1fr)); gap: 8px; }
|
||||
.import-validation-grid > span { display: flex; min-height: 52px; flex-direction: column; justify-content: center; gap: 4px; padding: 7px 9px; border: 1px solid var(--line); }
|
||||
.import-validation-grid small { font-size: 11px; }
|
||||
.import-validation-grid strong { font: 600 14px var(--mono); overflow-wrap: anywhere; }
|
||||
.import-validation-grid small { font-size: var(--font-note); }
|
||||
.import-validation-grid strong { font: 600 var(--font-section) var(--font-numeric); overflow-wrap: anywhere; }
|
||||
.import-validation-grid .positive { color: #08745e; }
|
||||
.import-validation-grid .negative { color: #a12a24; }
|
||||
.muted-dash { font-size: 12px; }
|
||||
.muted-dash { font-size: var(--font-control); }
|
||||
.visually-hidden-file { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
|
||||
.ai-panel { display: flex; flex-direction: column; gap: 9px; padding: 14px; }
|
||||
.ai-panel > label { font-weight: 650; }
|
||||
.ai-actions { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.ai-actions span { font-size: 11px; }
|
||||
.ai-actions span { font-size: var(--font-note); }
|
||||
.ai-result { padding: 12px 14px; }
|
||||
.ai-answer { padding: 12px 0; line-height: 1.75; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.ai-result details { margin-top: 10px; border-top: 1px solid var(--line); padding-top: 10px; }
|
||||
.ai-result summary { cursor: pointer; font-size: 12px; }
|
||||
.analysis-engine-status { display: inline-flex; align-items: center; gap: 7px; font-size: 12px; }
|
||||
.ai-result summary { cursor: pointer; font-size: var(--font-control); }
|
||||
.analysis-engine-status { display: inline-flex; align-items: center; gap: 7px; font-size: var(--font-control); }
|
||||
.analysis-engine-status i, .analysis-steps i { width: 7px; height: 7px; background: #c18a33; }
|
||||
.analysis-engine-status i.ready { background: var(--teal); }
|
||||
.analysis-workspace { display: grid; min-height: 650px; grid-template-columns: 225px minmax(0, 1fr); gap: 12px; }
|
||||
@@ -231,57 +247,56 @@ button { color: inherit; }
|
||||
.analysis-session-item { display: flex; flex: 1; min-width: 0; flex-direction: column; gap: 6px; padding: 11px; border: 0; background: transparent; color: var(--ink); text-align: left; cursor: pointer; }
|
||||
.analysis-session-row:hover, .analysis-session-row.active { background: var(--blue-soft); }
|
||||
.analysis-session-delete { flex: none; margin-right: 7px; }
|
||||
.analysis-session-item strong { overflow: hidden; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.analysis-session-item small { overflow: hidden; color: var(--muted-ink); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.analysis-session-item strong { overflow: hidden; font-size: var(--font-control); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.analysis-session-item small { overflow: hidden; color: var(--muted-ink); font-size: var(--font-note); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.analysis-chat-panel { display: flex; min-width: 0; min-height: 650px; flex-direction: column; }
|
||||
.analysis-context-bar { display: flex; align-items: center; flex-wrap: wrap; gap: 7px; padding: 9px; border-bottom: 1px solid var(--line); }
|
||||
.analysis-context-bar .ant-select { min-width: 112px; max-width: 190px; }
|
||||
.analysis-conversation { display: flex; min-height: 280px; flex: 1; flex-direction: column; gap: 15px; overflow: auto; padding: 15px; }
|
||||
.analysis-empty { display: flex; flex: 1; flex-direction: column; align-items: center; justify-content: center; gap: 11px; color: #4e5d72; text-align: center; }
|
||||
.analysis-empty .anticon { color: var(--blue); font-size: 24px; }
|
||||
.analysis-empty span { max-width: 440px; font-size: 12px; line-height: 1.6; }
|
||||
.analysis-empty span { max-width: 440px; font-size: var(--font-control); line-height: 1.6; }
|
||||
.analysis-turn { display: flex; flex-direction: column; gap: 9px; }
|
||||
.analysis-question { align-self: flex-end; width: min(720px, 92%); padding: 10px 12px; background: #edf1fb; border: 1px solid var(--line); }
|
||||
.analysis-question small { font-size: 10px; }
|
||||
.analysis-question small { font-size: var(--font-note); }
|
||||
.analysis-question p { margin: 5px 0 0; line-height: 1.6; white-space: pre-wrap; }
|
||||
.analysis-answer { width: 100%; padding: 11px 13px; background: #fff; border: 1px solid var(--line); }
|
||||
.analysis-answer-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; font-size: 11px; }
|
||||
.analysis-answer-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; font-size: var(--font-note); }
|
||||
.analysis-answer .ai-answer { padding-bottom: 4px; }
|
||||
.analysis-steps { display: flex; flex-wrap: wrap; align-items: center; gap: 7px 13px; margin-top: 8px; font-size: 11px; }
|
||||
.analysis-steps { display: flex; flex-wrap: wrap; align-items: center; gap: 7px 13px; margin-top: 8px; font-size: var(--font-note); }
|
||||
.analysis-steps strong { flex-basis: 100%; }
|
||||
.analysis-steps span { display: inline-flex; align-items: center; gap: 5px; padding: 4px 6px; background: #f4f6fa; }
|
||||
.analysis-steps i { background: var(--teal); }
|
||||
.analysis-privacy-note { display: block; margin-top: 9px; font-size: 10px; }
|
||||
.analysis-progress { display: flex; align-items: center; gap: 8px; padding: 12px; background: #f6f8fc; font-size: 12px; }
|
||||
.analysis-privacy-note { display: block; margin-top: 9px; font-size: var(--font-note); }
|
||||
.analysis-composer { display: flex; flex-direction: column; gap: 8px; padding: 12px; border-top: 1px solid var(--line); }
|
||||
.analysis-composer > label { font-size: 12px; font-weight: 650; }
|
||||
.analysis-composer > label { font-size: var(--font-control); font-weight: 650; }
|
||||
.analysis-snapshots { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 9px; margin-top: 11px; }
|
||||
.snapshot-card { min-width: 0; padding: 10px; background: #f8f9fc; border: 1px solid var(--line); }
|
||||
.snapshot-heading { display: flex; justify-content: space-between; gap: 9px; font-size: 11px; }
|
||||
.snapshot-heading { display: flex; justify-content: space-between; gap: 9px; font-size: var(--font-note); }
|
||||
.snapshot-heading span { text-align: right; }
|
||||
.snapshot-kpis { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 7px; margin: 9px 0; }
|
||||
.snapshot-kpis > span { display: flex; min-width: 0; flex-direction: column; gap: 4px; padding: 7px; background: #fff; border: 1px solid var(--line); }
|
||||
.snapshot-kpis small { font-size: 10px; }
|
||||
.snapshot-kpis strong { overflow: hidden; font: 600 14px var(--mono); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.snapshot-details { display: flex; flex-direction: column; gap: 4px; padding-top: 7px; font-size: 11px; }
|
||||
.snapshot-kpis small { font-size: var(--font-note); }
|
||||
.snapshot-kpis strong { overflow: hidden; font: 600 var(--font-section) var(--font-numeric); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.snapshot-details { display: flex; flex-direction: column; gap: 4px; padding-top: 7px; font-size: var(--font-note); }
|
||||
.snapshot-defects { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 9px; margin-top: 7px; }
|
||||
.snapshot-defects > div { display: flex; flex-direction: column; gap: 4px; padding: 7px; background: #fff; border: 1px solid var(--line); }
|
||||
.snapshot-defects strong { font-size: 10px; }
|
||||
.snapshot-defects span { font-size: 10px; overflow-wrap: anywhere; }
|
||||
.snapshot-card details { margin-top: 8px; font-size: 11px; }
|
||||
.snapshot-defects strong { font-size: var(--font-note); }
|
||||
.snapshot-defects span { font-size: var(--font-note); overflow-wrap: anywhere; }
|
||||
.snapshot-card details { margin-top: 8px; font-size: var(--font-note); }
|
||||
.snapshot-card summary { cursor: pointer; }
|
||||
.json-result { max-height: 560px; overflow: auto; margin: 10px 0 0; padding: 12px; background: #f5f7fb; font: 12px/1.5 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.json-result { max-height: 560px; overflow: auto; margin: 10px 0 0; padding: 12px; background: #f5f7fb; font: var(--font-control)/1.5 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.empty-note { padding: 25px 16px; text-align: center; }
|
||||
.access-summary { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||
.access-summary > div { display: flex; min-height: 86px; flex-direction: column; justify-content: center; gap: 5px; padding: 12px 14px; border-right: 1px solid var(--line); }
|
||||
.access-summary > div:last-child { border-right: 0; }
|
||||
.access-summary span, .access-summary small { font-size: 11px; }
|
||||
.access-summary strong { overflow-wrap: anywhere; font-size: 13px; }
|
||||
.access-summary span, .access-summary small { font-size: var(--font-note); }
|
||||
.access-summary strong { overflow-wrap: anywhere; font-size: var(--font-body); }
|
||||
.resource-tab { padding: 8px 0 0; }
|
||||
.basis-grid { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 12px; }
|
||||
.screen-state { display: flex; min-height: var(--viewport-height); align-items: center; justify-content: center; gap: 12px; background: #f3f5f9; }
|
||||
.state-card { width: min(390px, calc(100vw - 28px)); padding: 24px; background: #fff; border: 1px solid var(--line); }
|
||||
.state-card strong { font-size: 18px; }
|
||||
.state-card strong { font-size: var(--font-page-title); }
|
||||
.state-card p { margin: 10px 0 16px; overflow-wrap: anywhere; }
|
||||
.login-screen { display: grid; min-height: var(--small-viewport-height); grid-template-columns: minmax(0, 1.13fr) minmax(410px, .87fr); overflow: hidden; background: #fff; }
|
||||
.login-art { position: relative; isolation: isolate; min-width: 0; min-height: 640px; overflow: hidden; padding: 36px clamp(30px, 5vw, 76px) 25px; color: #fff; background: linear-gradient(148deg, #4d65ca, #253454 60%, #30456c); }
|
||||
@@ -293,36 +308,36 @@ button { color: inherit; }
|
||||
.login-brand-lockup { position: relative; z-index: 2; display: flex; align-items: center; gap: 17px; }
|
||||
.login-brand-lockup img { display: block; width: 168px; max-width: 48%; height: auto; }
|
||||
.login-brand-divider { width: 1px; height: 29px; background: rgba(255,255,255,.38); }
|
||||
.login-brand-lockup strong { color: #f7fbff; font-size: 15px; font-weight: 550; letter-spacing: .04em; white-space: nowrap; }
|
||||
.login-brand-lockup strong { color: #f7fbff; font-size: var(--font-dialog-title); font-weight: 550; letter-spacing: .04em; white-space: nowrap; }
|
||||
.login-art-copy { position: relative; z-index: 2; max-width: 520px; margin-top: clamp(104px, 14vh, 150px); }
|
||||
.login-eyebrow { color: #91d6d0; font: 500 11px/1.4 var(--mono); letter-spacing: .16em; }
|
||||
.login-eyebrow { color: #91d6d0; font: 500 var(--font-note)/1.4 var(--mono); letter-spacing: .16em; }
|
||||
.login-art-copy h1 { margin: 18px 0 17px; color: #fff; font-size: clamp(38px, 4.1vw, 56px); font-weight: 570; letter-spacing: -.045em; line-height: 1.22; }
|
||||
.login-art-copy p { max-width: 400px; margin: 0; color: #d1dfeb; font-size: 15px; line-height: 1.75; letter-spacing: .015em; }
|
||||
.login-art-copy p { max-width: 400px; margin: 0; color: #d1dfeb; font-size: var(--font-dialog-title); line-height: 1.75; letter-spacing: .015em; }
|
||||
.login-panel { position: relative; display: flex; min-width: 0; min-height: 640px; flex-direction: column; align-items: center; justify-content: center; padding: 76px clamp(30px, 5vw, 78px) 98px; background: #fff; }
|
||||
.login-panel-top { position: absolute; top: 31px; right: clamp(28px, 4vw, 58px); display: inline-flex; align-items: center; gap: 9px; color: #42546a; font-size: 13px; font-weight: 600; }
|
||||
.login-panel-top { position: absolute; top: 31px; right: clamp(28px, 4vw, 58px); display: inline-flex; align-items: center; gap: 9px; color: #42546a; font-size: var(--font-body); font-weight: 600; }
|
||||
.login-panel-mark { display: inline-flex; height: 19px; align-items: center; gap: 2px; transform: skew(-17deg); }
|
||||
.login-panel-mark i { width: 3px; height: 13px; background: var(--blue); }
|
||||
.login-panel-mark i:nth-child(2) { height: 18px; opacity: .8; }
|
||||
.login-panel-mark i:nth-child(3) { height: 10px; background: var(--teal); }
|
||||
.login-card { width: min(100%, 390px); padding: 0; border: 0; background: transparent; }
|
||||
.login-card-kicker { color: var(--blue-dark); font-size: 13px; font-weight: 650; letter-spacing: .03em; }
|
||||
.login-card-kicker { color: var(--blue-dark); font-size: var(--font-body); font-weight: 650; letter-spacing: .03em; }
|
||||
.login-card h2 { margin: 0 0 30px; color: #111111; font-size: 30px; font-weight: 650; letter-spacing: -.04em; line-height: 1.3; }
|
||||
.login-card-subtitle { margin: 0 0 30px; color: #526174; font-size: 14px; line-height: 1.6; }
|
||||
.login-card-subtitle { margin: 0 0 30px; color: #526174; font-size: var(--font-section); line-height: 1.6; }
|
||||
.login-card .ant-form-item { margin-bottom: 20px; }
|
||||
.login-card .ant-form-item-label { padding-bottom: 7px; }
|
||||
.login-card .ant-form-item-label > label { color: #111111; font-size: 14px; font-weight: 550; }
|
||||
.login-card .ant-form-item-control-input-content > .ant-input { height: 44px; padding: 0 11px; border-radius: 0; border-color: #bcc9d8; box-shadow: none; font-size: 14px; }
|
||||
.login-card .ant-form-item-label > label { color: #111111; font-size: var(--font-section); font-weight: 550; }
|
||||
.login-card .ant-form-item-control-input-content > .ant-input { height: 44px; padding: 0 11px; border-radius: var(--control-radius, 4px); border-color: #bcc9d8; box-shadow: none; font-size: var(--font-section); }
|
||||
.login-card .ant-form-item-control-input-content > .ant-input:hover { border-color: #3559dc; }
|
||||
.login-card .ant-form-item-control-input-content > .ant-input:focus { border-color: #3559dc; box-shadow: 0 0 0 2px rgba(53,89,220,.12); }
|
||||
.login-card .ant-input-affix-wrapper { min-height: 44px; padding: 0 11px; border-radius: 0; border-color: #bcc9d8; box-shadow: none; }
|
||||
.login-card .ant-input-affix-wrapper { min-height: 44px; padding: 0 11px; border-radius: var(--control-radius, 4px); border-color: #bcc9d8; box-shadow: none; }
|
||||
.login-card .ant-input-affix-wrapper:hover { border-color: #3559dc; }
|
||||
.login-card .ant-input-affix-wrapper-focused { border-color: #3559dc; box-shadow: 0 0 0 2px rgba(53,89,220,.12); }
|
||||
.login-card .ant-input-affix-wrapper .ant-input { height: 40px; font-size: 14px; }
|
||||
.login-card .ant-input-affix-wrapper .ant-input { height: 40px; font-size: var(--font-section); }
|
||||
.login-card .ant-input::placeholder { color: #8794a3; }
|
||||
.login-card .login-submit { min-height: 44px; margin-top: 4px; font-size: 14px; font-weight: 650; }
|
||||
.login-error { margin: -1px 0 17px; border-radius: 0; font-size: 13px; }
|
||||
.login-card .login-submit { min-height: 44px; margin-top: 4px; font-size: var(--font-section); font-weight: 650; }
|
||||
.login-error { margin: -1px 0 17px; border-radius: var(--control-radius, 4px); font-size: var(--font-body); }
|
||||
.login-error .ant-alert-message { overflow-wrap: anywhere; }
|
||||
.login-footer { position: absolute; right: 24px; bottom: 25px; left: 24px; color: #677789; font-size: 12px; text-align: center; }
|
||||
.login-footer { position: absolute; right: 24px; bottom: 25px; left: 24px; color: #677789; font-size: var(--font-control); text-align: center; }
|
||||
.login-footer span { margin: 0 5px; color: #91a0ae; }
|
||||
|
||||
@media (max-width: 1140px) {
|
||||
@@ -341,27 +356,27 @@ button { color: inherit; }
|
||||
.login-art { min-height: 270px; padding: 23px 22px 20px; }
|
||||
.login-brand-lockup { gap: 12px; }
|
||||
.login-brand-lockup img { width: 146px; }
|
||||
.login-brand-lockup strong { font-size: 13px; }
|
||||
.login-brand-lockup strong { font-size: var(--font-body); }
|
||||
.login-art-copy { margin-top: 41px; }
|
||||
.login-eyebrow { font-size: 9px; }
|
||||
.login-art-copy h1 { margin: 10px 0 8px; font-size: 30px; line-height: 1.16; }
|
||||
.login-art-copy p { max-width: 330px; font-size: 12px; line-height: 1.55; }
|
||||
.login-art-copy p { max-width: 330px; font-size: var(--font-control); line-height: 1.55; }
|
||||
.login-art::before { width: 340px; height: 340px; right: -170px; top: 30px; box-shadow: 0 0 0 40px rgba(189,204,255,.03), 0 0 0 85px rgba(189,204,255,.024); }
|
||||
.login-orbit-one { width: 220px; height: 100px; right: 4px; top: 142px; }
|
||||
.login-orbit-two { width: 175px; height: 76px; right: -24px; top: 155px; }
|
||||
.login-panel { min-height: 430px; align-items: stretch; justify-content: flex-start; padding: 36px 24px 71px; }
|
||||
.login-panel-top { top: 18px; right: 23px; font-size: 11px; }
|
||||
.login-panel-top { top: 18px; right: 23px; font-size: var(--font-note); }
|
||||
.login-card { width: min(100%, 390px); margin: 0 auto; }
|
||||
.login-card h2 { margin-top: 8px; font-size: 26px; }
|
||||
.login-card-subtitle { margin-bottom: 22px; }
|
||||
.login-card .ant-form-item { margin-bottom: 16px; }
|
||||
.login-footer { bottom: 20px; font-size: 11px; }
|
||||
.login-footer { bottom: 20px; font-size: var(--font-note); }
|
||||
:root { --sidebar: 0px; }
|
||||
.sidebar { display: none; }
|
||||
.main-column { margin-left: 0; }
|
||||
.topbar { height: 40px; padding: 0 12px; }
|
||||
.top-organization { display: none; }
|
||||
.mobile-brand { display: flex; min-height: 44px; align-items: center; gap: 7px; padding: 4px 10px; background: #f8f9fc; border-bottom: 1px solid var(--line); font-size: 14px; }
|
||||
.mobile-brand { display: flex; min-height: 44px; align-items: center; gap: 7px; padding: 4px 10px; background: #f8f9fc; border-bottom: 1px solid var(--line); font-size: var(--font-section); }
|
||||
.mobile-brand > strong { white-space: nowrap; }
|
||||
.mobile-brand > .ant-select { flex: 1; min-width: 0; margin-left: 3px; }
|
||||
.mobile-brand .brand-mark { transform: scale(.83) skew(-17deg); transform-origin: left center; width: 18px; }
|
||||
@@ -387,12 +402,12 @@ button { color: inherit; }
|
||||
.query-field.release-field { flex-basis: 100%; }
|
||||
.query-toolbar-tail { width: 100%; min-width: 0; }
|
||||
.metric-card { min-height: 80px; padding: 9px 10px; }
|
||||
.metric-label { gap: 5px; font-size: 11px; }
|
||||
.metric-value, .metric-card.primary .metric-value { font-size: clamp(19px, 6vw, 27px); letter-spacing: -.7px; }
|
||||
.metric-card small { font-size: 10px; }
|
||||
.metric-label { gap: 5px; font-size: var(--font-note); }
|
||||
.metric-value, .metric-card.primary .metric-value { font-size: var(--font-metric-mobile); letter-spacing: -.7px; }
|
||||
.metric-card small { font-size: var(--font-note); }
|
||||
.section-heading-row { align-items: flex-start; flex-direction: column; gap: 8px; padding: 10px; }
|
||||
.section-heading { flex-wrap: wrap; gap: 5px 9px; }
|
||||
.section-heading h2 { font-size: 13px; }
|
||||
.section-heading h2 { font-size: var(--font-section); }
|
||||
.table-tools { width: 100%; flex-wrap: wrap; justify-content: space-between; }
|
||||
.table-tools .ant-input-affix-wrapper { width: min(100%, 220px); flex: 1 1 145px; }
|
||||
.table-tools .ant-segmented { max-width: 100%; }
|
||||
@@ -413,11 +428,11 @@ button { color: inherit; }
|
||||
.defect-stage-column { padding: 0 10px 10px; }
|
||||
.defect-stage-column + .defect-stage-column { border-left: 0; border-top: 1px solid var(--line); }
|
||||
.defect-header, .defect-row { grid-template-columns: minmax(68px, 90px) minmax(28px, 1fr) 80px 52px 52px; gap: 6px; }
|
||||
.defect-name { font-size: 12px; }
|
||||
.defect-weight, .defect-rate { font-size: 10px; }
|
||||
.defect-name { font-size: var(--font-control); }
|
||||
.defect-weight, .defect-rate { font-size: var(--font-note); }
|
||||
.query-footer { align-items: flex-start; flex-direction: column; gap: 2px; }
|
||||
.page-heading { align-items: flex-start; flex-direction: column; }
|
||||
.page-heading h1 { font-size: 17px; }
|
||||
.page-heading h1 { font-size: var(--font-page-title); }
|
||||
.page-heading-actions { width: 100%; justify-content: flex-start; }
|
||||
.page-heading-actions .ant-btn { flex: 1; }
|
||||
.resource-toolbar { flex-wrap: wrap; gap: 5px 10px; padding: 8px 10px; }
|
||||
@@ -472,7 +487,7 @@ body { background: var(--background); }
|
||||
gap: 7px;
|
||||
padding: 0 8px;
|
||||
color: #111;
|
||||
font-size: 12px;
|
||||
font-size: var(--font-control);
|
||||
}
|
||||
.topbar-search .anticon, .topbar-help .anticon { color: #667386; }
|
||||
.topbar-search kbd, .navigation-result kbd {
|
||||
@@ -483,14 +498,14 @@ body { background: var(--background); }
|
||||
border: 1px solid var(--line);
|
||||
background: #fafbfe;
|
||||
color: #58667b;
|
||||
font: 11px/1.2 var(--mono);
|
||||
font: var(--font-note)/1.2 var(--mono);
|
||||
}
|
||||
.topbar-help.ant-btn { width: 30px; height: 30px; padding: 0; }
|
||||
.topbar-theme.ant-btn { height: 30px; gap: 6px; padding: 0 7px; color: #111; font-size: 12px; }
|
||||
.topbar-theme.ant-btn { height: 30px; gap: 6px; padding: 0 7px; color: #111; font-size: var(--font-control); }
|
||||
.topbar-theme .anticon { color: #667386; }
|
||||
.theme-choice { display: flex; min-width: 104px; align-items: center; gap: 9px; font-size: 13px; }
|
||||
.theme-choice { display: flex; min-width: 104px; align-items: center; gap: 9px; font-size: var(--font-body); }
|
||||
.theme-choice > i { display: inline-block; width: 10px; height: 10px; flex: 0 0 10px; border: 1px solid #11111114; }
|
||||
.theme-choice > .anticon { margin-left: auto; font-size: 11px; }
|
||||
.theme-choice > .anticon { margin-left: auto; font-size: var(--font-note); }
|
||||
.workspace-theme-dropdown.ant-dropdown { z-index: 1250 !important; isolation: isolate; }
|
||||
.workspace-theme-dropdown .ant-dropdown-menu { border: 1px solid var(--line); background-color: var(--surface, #fff) !important; color: var(--ink); opacity: 1 !important; box-shadow: 0 8px 24px rgba(18, 30, 52, .2); }
|
||||
.workspace-theme-dropdown .ant-dropdown-menu-item { color: var(--ink) !important; }
|
||||
@@ -504,13 +519,13 @@ body { background: var(--background); }
|
||||
.panel { border-color: var(--line); }
|
||||
.metric-table-scroll .ant-table-tbody > tr > td { height: 35px; }
|
||||
.metric-table-scroll .ant-table-cell { padding-top: 6px !important; padding-bottom: 6px !important; }
|
||||
.metric-table-scroll .ant-btn-link:not(.table-value) { min-height: 0; height: 22px; padding: 0; font-size: 12px; }
|
||||
.metric-table-scroll .ant-btn-link:not(.table-value) { min-height: 0; height: 22px; padding: 0; font-size: var(--font-control); }
|
||||
.query-page > .ant-alert { padding: 10px 14px; }
|
||||
.coverage-details { margin-top: 3px; font-size: 12px; line-height: 1.6; }
|
||||
.coverage-details { margin-top: 3px; font-size: var(--font-control); line-height: 1.6; }
|
||||
.coverage-details summary { width: fit-content; cursor: pointer; }
|
||||
.coverage-details p { margin: 7px 0 0; }
|
||||
.ant-btn, .ant-input, .ant-select-selector, .ant-segmented, .ant-tag, .ant-alert,
|
||||
.ant-modal-container, .ant-modal-content, .ant-drawer-content, .ant-input-affix-wrapper { border-radius: 0 !important; }
|
||||
.ant-modal-container, .ant-modal-content, .ant-drawer-content, .ant-input-affix-wrapper { border-radius: var(--control-radius, 4px) !important; }
|
||||
.ant-modal { max-width: calc(100vw - 24px); }
|
||||
.ant-btn { transition: background-color 140ms cubic-bezier(.2,.7,.2,1), color 140ms cubic-bezier(.2,.7,.2,1), border-color 140ms cubic-bezier(.2,.7,.2,1), box-shadow 140ms cubic-bezier(.2,.7,.2,1); }
|
||||
.ant-segmented, .ant-segmented .ant-segmented-item, .ant-segmented .ant-segmented-thumb {
|
||||
@@ -518,7 +533,7 @@ body { background: var(--background); }
|
||||
}
|
||||
.ant-drawer .ant-drawer-content-wrapper { transition-duration: 200ms !important; transition-timing-function: cubic-bezier(.2,.7,.2,1) !important; }
|
||||
.navigation-search-modal .ant-modal-header { margin-bottom: 12px; }
|
||||
.navigation-search-modal .ant-modal-title { color: #111; font-size: 15px; font-weight: 650; }
|
||||
.navigation-search-modal .ant-modal-title { color: #111; font-size: var(--font-dialog-title); font-weight: 650; }
|
||||
.navigation-search-modal .ant-modal-body > .ant-input-affix-wrapper { min-height: 40px; }
|
||||
.navigation-search-results { display: flex; max-height: min(48vh, 360px); flex-direction: column; gap: 2px; overflow-y: auto; margin: 9px -5px 0; padding: 0 5px; }
|
||||
.navigation-result {
|
||||
@@ -536,8 +551,8 @@ body { background: var(--background); }
|
||||
transition: background-color 140ms cubic-bezier(.2,.7,.2,1), color 140ms cubic-bezier(.2,.7,.2,1);
|
||||
}
|
||||
.navigation-result:hover, .navigation-result:focus-visible, .navigation-result[aria-selected="true"] { outline: 0; background: var(--blue-soft); color: var(--blue-dark); }
|
||||
.navigation-search-empty { padding: 18px 9px; color: #111; font-size: 13px; }
|
||||
.navigation-search-footnote { margin-top: 10px; padding-top: 9px; border-top: 1px solid var(--line); color: #111; font-size: 11px; }
|
||||
.navigation-search-empty { padding: 18px 9px; color: #111; font-size: var(--font-body); }
|
||||
.navigation-search-footnote { margin-top: 10px; padding-top: 9px; border-top: 1px solid var(--line); color: #111; font-size: var(--font-note); }
|
||||
|
||||
@media (max-width: 1140px) {
|
||||
.page-content { padding: 15px 15px 20px; }
|
||||
@@ -549,7 +564,7 @@ body { background: var(--background); }
|
||||
.topbar-search.ant-btn { width: 30px; justify-content: center; padding: 0; }
|
||||
.topbar-search > span:not(.anticon), .topbar-search kbd { display: none; }
|
||||
.topbar-help.ant-btn { width: 28px; }
|
||||
.topbar-theme.ant-btn { gap: 4px; padding: 0 5px; font-size: 11px; }
|
||||
.topbar-theme.ant-btn { gap: 4px; padding: 0 5px; font-size: var(--font-note); }
|
||||
.top-organization { display: none; }
|
||||
.mobile-brand { background: var(--sidebar-surface); }
|
||||
.page-content { padding: 11px 10px 18px; }
|
||||
@@ -562,7 +577,7 @@ body { background: var(--background); }
|
||||
.metric-card:hover { background: var(--hover); }
|
||||
.metric-table-scroll .combined-column,
|
||||
.metric-table-scroll .combined-column.ant-table-cell-fix-left,
|
||||
.metric-table-scroll th.combined-column { background: var(--blue-soft) !important; }
|
||||
.metric-table-scroll th.combined-column { background: var(--table-combined, var(--blue-soft)) !important; }
|
||||
.metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.black) { background: var(--blue-soft); }
|
||||
.basis-card { background: var(--blue-soft); }
|
||||
.workspace-caption { padding-bottom: 6px; }
|
||||
@@ -575,7 +590,7 @@ body { background: var(--background); }
|
||||
.ant-drawer .ant-drawer-content-wrapper { transition-duration: .01ms !important; }
|
||||
}
|
||||
|
||||
.analysis-reports { padding: 12px 15px; border-top: 1px solid var(--border-color, #dce3ec); font-size: 13px; }
|
||||
.analysis-reports { padding: 12px 15px; border-top: 1px solid var(--border-color, #dce3ec); font-size: var(--font-body); }
|
||||
.analysis-reports summary { cursor: pointer; font-weight: 600; }
|
||||
.analysis-reports p { color: var(--text-secondary, #667085); line-height: 1.6; }
|
||||
.analysis-report-plans { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; padding-top: 12px; }
|
||||
@@ -594,14 +609,17 @@ body { background: var(--background); }
|
||||
.query-toolbar-tail { flex: 0 0 auto; margin-left: 0; }
|
||||
.query-more-toggle { display: flex; flex: 0 0 auto; align-items: center; gap: 3px; min-height: 28px; }
|
||||
.query-more-toggle > .ant-btn { flex-shrink: 0; }
|
||||
.query-filter-summary { color: var(--muted-ink, #657087); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.query-filter-summary { color: var(--muted-ink, #657087); font-size: var(--font-control); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.query-extra-fields { display: flex; flex: 1 0 100%; order: 2; flex-wrap: wrap; gap: 12px 20px; padding: 10px 0 3px; border-top: 1px solid var(--line); }
|
||||
.query-extra-error { flex: 1 0 100%; order: 2; }
|
||||
.query-toolbar .organization-breadcrumb { order: 3; }
|
||||
.query-extra-field .ant-select { width: 240px; min-width: 180px; }
|
||||
.query-options-hint { color: var(--muted-ink, #657087); padding: 8px 12px; font-size: 12px; }
|
||||
.filter-field-settings { padding: 16px; margin-bottom: 16px; }
|
||||
.filter-field-settings p { color: var(--muted-ink, #657087); font-size: 13px; }
|
||||
.query-options-hint { color: var(--muted-ink, #657087); padding: 8px 12px; font-size: var(--font-control); }
|
||||
.filter-field-settings { padding: 10px 12px; margin-bottom: 12px; }
|
||||
.filter-field-settings .section-heading-row { min-height: 28px; padding: 0; gap: 8px; flex-direction: row; flex-wrap: wrap; align-items: center; }
|
||||
.filter-field-settings p { margin: 4px 0 8px; color: var(--muted-ink, #657087); font-size: var(--font-control); line-height: 1.5; }
|
||||
.filter-field-settings .ant-table-wrapper .ant-table.ant-table-small .ant-table-thead > tr > th,
|
||||
.filter-field-settings .ant-table-wrapper .ant-table.ant-table-small .ant-table-tbody > tr > td { padding: 6px 8px !important; }
|
||||
@media (max-width: 760px) {
|
||||
.query-toolbar > .query-primary-field { flex: 1 1 145px; min-width: 0; max-width: none; }
|
||||
.query-primary-field .ant-select, .query-extra-field .ant-select, .query-period-field .ant-select { width: 100%; min-width: 0; flex: initial; }
|
||||
@@ -614,4 +632,4 @@ body { background: var(--background); }
|
||||
.query-filter-summary { order: 3; flex-basis: 100%; }
|
||||
}
|
||||
|
||||
.query-quality-summary { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 14px; color: var(--muted-ink); font-size: 12px; margin: 0 0 14px; }
|
||||
.query-quality-summary { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 14px; color: var(--muted-ink); font-size: var(--font-control); margin: 0 0 14px; }
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
export type MonitorRow = Record<string, unknown>;
|
||||
const labels: Record<string, string> = {
|
||||
QUEUED: '等待处理', RUNNING: '处理中', COMPLETED: '已完成', SUCCEEDED: '已完成',
|
||||
FAILED: '失败', ERROR: '失败', CANCELLED: '已取消', PARTIAL: '部分完成',
|
||||
IMPORT: '数据导入', RELEASE_POST_PUBLISH: '报表发布后处理', BACKUP_CREATE_VERIFY: '创建并验证备份', BACKUP_VERIFY: '备份复核',
|
||||
ANALYSIS: '智能分析', WORKFLOW_IMPORT: '导入并更新报表', WORKFLOW_RECALCULATE: '重新计算报表',
|
||||
WORKFLOW_APPLY_RULE: '更新计算规则', WORKFLOW_APPLY_MAPPING: '更新对应关系与基础数据',
|
||||
WORKFLOW_PUBLISH: '发布报表', WORKFLOW_RESTORE_SOURCE: '恢复来源并更新报表',
|
||||
WORKFLOW_DELETE_SOURCE: '移除来源并更新报表', WORKFLOW_DELETE_SOURCES: '移除来源并更新报表',
|
||||
VALIDATING: '校验中', VERSION_CREATED: '配置已保存', REBUILDING: '重新计算中', PUBLISHING: '发布中',
|
||||
TASK_FAILURE: '任务失败', TASK_BACKLOG: '任务排队超时', SOURCE_DELAY: '来源更新延迟', STORAGE_LOW: '可用磁盘空间不足', BACKUP_STALE: '备份验证超时',
|
||||
OPEN: '待处理', RECOVERED: '已恢复', WARNING: '警告', ERROR_SEVERITY: '错误', CRITICAL: '严重', INFO: '提示',
|
||||
ISOLATED_RESTORE_VERIFIED: '恢复验证通过', BACKUP_CREATED_NOT_RESTORE_VERIFIED: '已备份,未验证恢复', CREATED: '已创建,待验证', VERIFIED: '已验证',
|
||||
};
|
||||
export function monitorLabel(value: unknown, fallback = '—'): string {
|
||||
return typeof value === 'string' && value ? labels[value] || fallback : fallback;
|
||||
}
|
||||
export function isActive(row: MonitorRow): boolean { return ['QUEUED', 'RUNNING'].includes(String(row.status)); }
|
||||
export function isFailed(row: MonitorRow): boolean { return ['FAILED', 'ERROR', 'PARTIAL'].includes(String(row.status)); }
|
||||
export function taskFailure(row: MonitorRow): string {
|
||||
if (!isFailed(row)) return '—';
|
||||
const errors = Array.isArray(row.errors) ? row.errors.map(error => typeof error === 'string' ? error : error?.message).filter(Boolean).join(';') : '';
|
||||
const reason = String(row.errorMessage || errors || row.errorCode || '服务端未记录失败原因');
|
||||
return reason === 'evidence_incomplete' ? '分析证据不完整,本轮仅部分完成' : reason;
|
||||
}
|
||||
export function taskPercent(row: MonitorRow): number | null {
|
||||
if (['COMPLETED', 'SUCCEEDED'].includes(String(row.status))) return 100;
|
||||
if (row.progress === null || row.progress === undefined || row.progress === '') return null;
|
||||
const n = Number(row.progress); return Number.isFinite(n) ? Math.max(0, Math.min(100, n)) : null;
|
||||
}
|
||||
export function orderedTasks(items: MonitorRow[], filter: string): MonitorRow[] {
|
||||
const rank = (row: MonitorRow) => isActive(row) ? 0 : isFailed(row) ? 1 : 2;
|
||||
return items.filter(row => filter === 'all' || (filter === 'active' ? isActive(row) : filter === 'failed' ? isFailed(row) : ['COMPLETED', 'SUCCEEDED'].includes(String(row.status))))
|
||||
.sort((a,b) => rank(a)-rank(b) || String(b.createdAt).localeCompare(String(a.createdAt)));
|
||||
}
|
||||
export function alertsForStatus(items: MonitorRow[], status: string): MonitorRow[] { return items.filter(row => row.status === status); }
|
||||
export function alertObject(row: MonitorRow): string {
|
||||
return String(row.objectId || ({ BACKUP_STALE: '备份', STORAGE_LOW: '服务器磁盘', TASK_BACKLOG: '任务队列', TASK_FAILURE: '后台任务', SOURCE_DELAY: '数据来源' }[String(row.alertType)] || '平台'));
|
||||
}
|
||||
export function backupSummary(latest: MonitorRow): string {
|
||||
if (!latest.createdAt) return '暂无备份记录';
|
||||
const v = latest.verification && typeof latest.verification === 'object' ? latest.verification as MonitorRow : {};
|
||||
if (latest.status === 'ISOLATED_RESTORE_VERIFIED' && ['databaseRestoreVerified','applicationFilesVerified','requiredApplicationInputsVerified','archiveFilesVerified','archiveReferencesVerified'].every(key => v[key] === true)) return '数据库及文件恢复验证通过';
|
||||
return latest.status === 'ISOLATED_RESTORE_VERIFIED' ? '恢复验证范围不完整' : monitorLabel(latest.status, '备份验证状态待确认');
|
||||
}
|
||||
+9
-2
@@ -2,10 +2,17 @@ export type Stage = 'black' | 'bright';
|
||||
export type ViewKind = 'overall' | 'department' | 'group' | 'product' | 'projectGroup';
|
||||
export type PeriodKind = 'year' | 'quarter' | 'month';
|
||||
|
||||
export interface SourceColumnField { key: string; label: string; type: string; stages: Stage[]; columns: Partial<Record<Stage,string>> }
|
||||
export interface SourceColumnFilter { field: string; stages: Stage[]; operator: 'in' | 'not_in' | 'is_empty' | 'not_empty'; values?: string[] }
|
||||
|
||||
export interface QueryParams {
|
||||
year: number;
|
||||
stage?: Stage;
|
||||
columnFilters?: SourceColumnFilter[];
|
||||
month?: number;
|
||||
quarter?: number;
|
||||
monthStart?: number;
|
||||
monthEnd?: number;
|
||||
department?: string;
|
||||
group?: string;
|
||||
product?: string;
|
||||
@@ -31,8 +38,8 @@ export interface RecordsParams extends QueryParams {
|
||||
|
||||
export type RecordExportParams = Pick<
|
||||
QueryParams,
|
||||
'year' | 'month' | 'quarter' | 'department' | 'group' | 'product' | 'projectGroup' | 'includeUnassigned' | 'releaseId' | 'extraFilters'
|
||||
| 'productSearch'
|
||||
'year' | 'month' | 'quarter' | 'monthStart' | 'monthEnd' | 'department' | 'group' | 'product' | 'projectGroup' | 'includeUnassigned' | 'releaseId' | 'extraFilters'
|
||||
| 'productSearch' | 'stage' | 'columnFilters'
|
||||
>;
|
||||
|
||||
export interface DefectMetric {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/* Workspace typography: shared by query, intake, management and reading views. */
|
||||
:root {
|
||||
--font-ui: "PingFang SC", "Microsoft YaHei", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
--font-numeric: Arial, "Helvetica Neue", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
--font-note: 12px;
|
||||
--font-control: 12px;
|
||||
--font-table: 12px;
|
||||
--font-body: 13px;
|
||||
--font-reading: 14px;
|
||||
--font-section: 14px;
|
||||
--font-dialog-title: 16px;
|
||||
--font-page-title: 18px;
|
||||
--font-metric: clamp(22px, 2.15vw, 31px);
|
||||
--font-metric-primary: clamp(26px, 2.5vw, 36px);
|
||||
--font-metric-mobile: clamp(19px, 6vw, 27px);
|
||||
}
|
||||
|
||||
body, button, input, textarea, select { font-family: var(--font-ui); }
|
||||
|
||||
/* Component content inherits this tier instead of Ant Design's mixed sizes. */
|
||||
.app-shell :is(.ant-btn,.ant-input,.ant-input-number,.ant-select,.ant-segmented,.ant-tag,.ant-pagination),
|
||||
:is(.management-modal,.management-drawer,.structured-config-modal) :is(.ant-btn,.ant-input,.ant-input-number,.ant-select,.ant-segmented,.ant-tag) {
|
||||
font-size: var(--font-control);
|
||||
}
|
||||
.app-shell .ant-form-item-label > label,
|
||||
.management-modal .ant-form-item-label > label,
|
||||
.structured-config-modal .ant-form-item-label > label { font-size: var(--font-control); }
|
||||
.app-shell .ant-tabs-tab { font-size: var(--font-body); }
|
||||
.ant-modal-title,.ant-drawer-title { font-size: var(--font-dialog-title); }
|
||||
.ant-tooltip-inner { font-size: var(--font-note); }
|
||||
+12
-6
@@ -1,10 +1,16 @@
|
||||
const lightSurfaces = {
|
||||
ink: '#222C3C', secondaryInk: '#637187', placeholder: '#7E8B9E',
|
||||
surface: '#FFFFFF', subtle: '#F5F7FB', elevated: '#FFFFFF',
|
||||
line: '#DCE2EC', teal: '#268775',
|
||||
} as const;
|
||||
|
||||
export const workspaceThemes = [
|
||||
{ id: 'light', name: '浅蓝', primary: '#607AE1', soft: '#EEF1FF', background: '#F3F5FA', hover: '#F5F6FF', muted: '#B0BCEE', metricGrid: '#9BAAC0', metricGridHead: '#7F91AA' },
|
||||
{ id: 'soft', name: '柔蓝', primary: '#5078AE', soft: '#E7EFF9', background: '#EDF2F8', hover: '#F0F5FB', muted: '#A7BDD9', metricGrid: '#98AAC0', metricGridHead: '#7C91AA' },
|
||||
{ id: 'deep', name: '深蓝', primary: '#34578F', soft: '#DFE8F5', background: '#E5EBF3', hover: '#E9EFF8', muted: '#99AFCD', metricGrid: '#94A7C0', metricGridHead: '#7188A7' },
|
||||
{ id: 'bright', name: '亮蓝', primary: '#008CF6', soft: '#E3F2FF', background: '#EFF7FC', hover: '#EDF8FF', muted: '#8DC7F4', metricGrid: '#96ADC3', metricGridHead: '#7697B3' },
|
||||
{ id: 'classic', name: '经典蓝', primary: '#4472C4', soft: '#E7EFFB', background: '#F0F4FA', hover: '#EEF3FC', muted: '#A1B9E2', metricGrid: '#95A8BF', metricGridHead: '#788EAA' },
|
||||
{ id: 'dark', name: '夜间黑', primary: '#8AA7FF', soft: '#202C49', background: '#0E1420', hover: '#202B3E', muted: '#516A9A', metricGrid: '#45566D', metricGridHead: '#5B6D85' },
|
||||
{ ...lightSurfaces, id: 'light', name: '浅蓝', primary: '#607AE1', soft: '#EEF1FF', background: '#F3F5FA', hover: '#F5F6FF', muted: '#B0BCEE', metricGrid: '#BCC8D8', metricGridHead: '#9EADC2' },
|
||||
{ ...lightSurfaces, id: 'soft', name: '柔蓝', primary: '#5078AE', soft: '#E7EFF9', background: '#EDF2F8', hover: '#F0F5FB', muted: '#A7BDD9', metricGrid: '#BAC8D8', metricGridHead: '#9AADBF' },
|
||||
{ ...lightSurfaces, id: 'deep', name: '深蓝', primary: '#34578F', soft: '#DFE8F5', background: '#E5EBF3', hover: '#E9EFF8', muted: '#99AFCD', metricGrid: '#B7C5D7', metricGridHead: '#97ABC3' },
|
||||
{ ...lightSurfaces, id: 'bright', name: '亮蓝', primary: '#008CF6', soft: '#E3F2FF', background: '#EFF7FC', hover: '#EDF8FF', muted: '#8DC7F4', metricGrid: '#BBCDDC', metricGridHead: '#9AB5CA' },
|
||||
{ ...lightSurfaces, id: 'classic', name: '经典蓝', primary: '#4472C4', soft: '#E7EFFB', background: '#F0F4FA', hover: '#EEF3FC', muted: '#A1B9E2', metricGrid: '#BAC8D9', metricGridHead: '#9BADCA' },
|
||||
{ id: 'dark', name: '午夜黑', primary: '#8E98EF', soft: '#293251', background: '#080F1E', hover: '#202C43', muted: '#53638E', metricGrid: '#344157', metricGridHead: '#46536B', ink: '#E5EAF3', secondaryInk: '#A4AEC0', placeholder: '#98A5BB', surface: '#111827', subtle: '#1E2A40', elevated: '#182238', line: '#2E3B50', teal: '#72C6AD' },
|
||||
] as const;
|
||||
|
||||
export type WorkspaceTheme = (typeof workspaceThemes)[number];
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
/* Shared finish for every palette. Layout dimensions remain in the existing styles. */
|
||||
:root {
|
||||
--control-radius: 4px;
|
||||
--panel-radius: 5px;
|
||||
--surface-subtle: #f5f7fb;
|
||||
--surface-elevated: #fff;
|
||||
--table-head: color-mix(in srgb, var(--surface) 55%, var(--background));
|
||||
--table-combined: color-mix(in srgb, var(--blue-soft) 62%, var(--surface));
|
||||
--table-bright-head: color-mix(in srgb, var(--teal) 12%, var(--surface));
|
||||
--table-row-alt: color-mix(in srgb, var(--surface) 97%, var(--blue-soft));
|
||||
--panel-shadow: 0 2px 7px #21375605;
|
||||
}
|
||||
:root[data-workspace-theme='dark'] {
|
||||
--table-head: #222d42;
|
||||
--table-combined: #1b2339;
|
||||
--table-bright-head: #213b43;
|
||||
--table-row-alt: #111b2d;
|
||||
--panel-shadow: none;
|
||||
}
|
||||
body, .app-shell, .main-column { color: var(--ink); background: var(--background); }
|
||||
.panel, .metric-strip { box-shadow: var(--panel-shadow); }
|
||||
.metric-strip { border-radius: var(--panel-radius); overflow: hidden; }
|
||||
.nav-item { border-radius: var(--control-radius); }
|
||||
.nav-item.active { box-shadow: inset 3px 0 var(--blue); }
|
||||
.nav-group-label { color: var(--ink); }
|
||||
.nav-item .anticon { color: var(--muted-ink); }
|
||||
.nav-item.active .anticon { color: var(--blue-dark); }
|
||||
.metric-value { font-weight: 700; font-variant-numeric: tabular-nums lining-nums; }
|
||||
.metric-card small { color: var(--muted-ink); }
|
||||
.metric-table-scroll .ant-table { background: var(--surface); color: var(--ink); }
|
||||
.metric-table-scroll .ant-table-thead > tr > th { background: var(--table-head); color: var(--ink); }
|
||||
.metric-table-scroll .ant-table-tbody > tr > td { background: var(--surface); color: var(--ink); }
|
||||
.metric-table-scroll .ant-table-tbody > tr:nth-child(even) > td { background: var(--table-row-alt); }
|
||||
.metric-table-scroll .ant-table-tbody > tr:hover > td,
|
||||
.metric-table-scroll .ant-table-tbody > tr.ant-table-row:hover > td { background: var(--hover); }
|
||||
.ant-segmented { border-radius: var(--control-radius); }
|
||||
.ant-segmented .ant-segmented-item-selected { color: var(--blue-dark); background: var(--blue-soft); box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--blue) 22%, transparent); }
|
||||
.ant-segmented .ant-segmented-item, .ant-segmented .ant-segmented-thumb { border-radius: calc(var(--control-radius) - 1px); }
|
||||
.ant-btn-primary { box-shadow: 0 1px 2px #101b3010; }
|
||||
.ant-btn:focus-visible, .nav-item:focus-visible, .metric-card:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; }
|
||||
.workspace-theme-dropdown .ant-dropdown-menu { border-radius: var(--panel-radius); }
|
||||
.workspace-theme-dropdown .ant-dropdown-menu-item { border-radius: calc(var(--control-radius) - 1px); }
|
||||
:root[data-workspace-theme='dark'] .panel,
|
||||
:root[data-workspace-theme='dark'] .metric-strip { box-shadow: none; }
|
||||
Reference in New Issue
Block a user