修复:查询局部刷新与智能分析会话交互,完善分析收尾和配置切换

This commit is contained in:
2026-10-23 15:30:06 +08:00
parent 5fbeb52b93
commit 6394e057bf
40 changed files with 2107 additions and 239 deletions
+1 -1
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="light" />
<title>质量中心 · 质量洞察</title>
<title>质量数据分析平台</title>
</head>
<body>
<div id="root"></div>
+27 -10
View File
@@ -1,10 +1,11 @@
import { useRef, useState } from 'react';
import { Alert, App, Button, Form, Input, Modal, Spin } from 'antd';
import { Alert, App, Button, Form, Input, Modal, Select, Spin, Tag } from 'antd';
import { SettingOutlined } from '@ant-design/icons';
import { api } from './api';
export type AnalysisModelSettings = { baseUrl: string; model: string; hasApiKey: boolean; revision: string };
export type AnalysisModelSettingsInput = { baseUrl: string; model: string; apiKey?: string; revision?: string };
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 function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
const { message } = App.useApp();
@@ -14,16 +15,18 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const [settings, setSettings] = useState<AnalysisModelSettings>();
const [profileId, setProfileId] = useState<string>();
const selectedProfile = settings?.profiles.find(profile => profile.id === profileId);
const [notice, setNotice] = useState<{ type: 'success' | 'error'; text: string }>();
const sequence = useRef(0);
const close = () => { if (saving) return; sequence.current += 1; setOpen(false); form.resetFields(); setNotice(undefined); setTesting(false); };
const load = async () => {
const current = ++sequence.current;
setOpen(true); setLoading(true); setSettings(undefined); setNotice(undefined); form.resetFields();
setOpen(true); setLoading(true); setSettings(undefined); setProfileId(undefined); setNotice(undefined); form.resetFields();
try {
const value = await api.analysisSettings();
if (sequence.current !== current) return;
setSettings(value); form.setFieldsValue({ baseUrl: value.baseUrl, model: value.model, apiKey: '' });
setSettings(value); setProfileId(value.activeProfileId); form.setFieldsValue({ baseUrl: value.baseUrl, model: value.model, apiKey: '' });
} catch (error) {
if (sequence.current === current && !onUnauthorized(error)) setNotice({ type: 'error', text: error instanceof Error ? error.message : '读取配置失败' });
} finally { if (sequence.current === current) setLoading(false); }
@@ -35,15 +38,15 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
const current = sequence.current;
setNotice(undefined); test ? setTesting(true) : setSaving(true);
try {
const body = { ...values, revision: settings.revision };
const body = { ...values, revision: settings.revision, profileId };
if (test) {
const result = await api.testAnalysisSettings(body);
if (sequence.current === current) setNotice({ type: result.success ? 'success' : 'error', text: result.message });
} else {
const result = await api.saveAnalysisSettings(body);
if (sequence.current !== current) return;
setSettings(result); form.setFieldsValue({ apiKey: '' });
setNotice({ type: 'success', text: '已保存,下一轮分析使用新配置。' }); message.success('API 配置已保存');
setSettings(result); setProfileId(result.activeProfileId); form.setFieldsValue({ baseUrl: result.baseUrl, model: result.model, apiKey: '' });
setNotice({ type: 'success', text: '已使用此配置,后续新分析将使用它;正在运行的分析继续完成。' }); message.success('API 配置已切换');
}
} catch (error) {
if (sequence.current === current && !onUnauthorized(error)) setNotice({ type: 'error', text: error instanceof Error ? error.message : '操作失败,请重试' });
@@ -54,12 +57,26 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
<Modal title="API 配置" open={open} width={540} onCancel={close} footer={<>
<Button onClick={close} disabled={saving}>关闭</Button>
<Button loading={testing} disabled={loading || saving || !settings} onClick={() => void submit(true)}>测试连接</Button>
<Button type="primary" loading={saving} disabled={loading || testing || !settings} onClick={() => void submit(false)}>保存配置</Button>
<Button type="primary" loading={saving} disabled={loading || testing || !settings} onClick={() => void submit(false)}>保存并使用</Button>
</>}>
{loading ? <div style={{ padding: 32, textAlign: 'center' }}><Spin /></div> : <>
{settings && <div style={{ marginBottom: 20 }}>
<div style={{ marginBottom: 8 }}>选择配置 <Tag color="blue">当前使用:{settings.profiles.find(profile => profile.id === settings.activeProfileId)?.name || settings.model}</Tag></div>
<div style={{ display: 'flex', gap: 8 }}>
<Select aria-label="选择 API 配置" style={{ flex: 1, minWidth: 0 }} value={profileId} disabled={saving || testing}
options={settings.profiles.map(profile => ({ value: profile.id, label: `${profile.name} · ${profile.model}` }))}
onChange={id => {
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: '' });
}} />
<Button disabled={saving || testing || profileId === settings.activeProfileId} loading={saving} onClick={() => void submit(false)}>立即使用</Button>
</div>
</div>}
<Form form={form} layout="vertical" disabled={saving || testing} onValuesChange={() => setNotice(undefined)}>
<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={settings?.hasApiKey ? '已配置密钥;留空保留。更换接口地址时需重新填写。' : '密钥仅保存在服务端,保存后不回显。'} rules={settings?.hasApiKey ? [] : [{ required: true, whitespace: true, message: '请填写 API Key' }]}><Input.Password placeholder={settings?.hasApiKey ? '已配置,留空保留' : '请输入 API Key'} autoComplete="new-password" maxLength={4096} /></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>
{notice && <Alert showIcon type={notice.type} message={notice.text} />}
+44 -42
View File
@@ -1,13 +1,13 @@
import { useEffect, useState } from 'react';
import { Spin } from 'antd';
import { CheckCircleOutlined, CloseCircleOutlined, DownOutlined, RightOutlined } from '@ant-design/icons';
import { analysisIsRunning } from './analysisConversationState';
import { CheckCircleOutlined, CloseCircleOutlined, ClockCircleOutlined, RightOutlined } from '@ant-design/icons';
import { analysisIsRunning, compactAnalysisTimeline, duplicatesFinalAnalysisAnswer } from './analysisConversationState';
import { AiMarkdown } from './AiMarkdown';
import { sanitizeAnalysisDisplayText } from './analysisDisplayText';
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: '排序', year: '年', month: '月', quarter: '季度', 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: '来源明细核查' };
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_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]) => {
const shown = typeof value === 'object' && value ? inputText(record(value)).replaceAll('\n', ',') : typeof value === 'boolean' ? value ? '是' : '否' : INPUT_VALUES[String(value)] || String(value);
@@ -15,48 +15,50 @@ function inputText(input: Record<string, unknown>): string {
}).join('\n');
}
function ToolCall({ entry, running }: { entry: Record<string, unknown>; running: boolean }) {
const failed = entry.status === 'failed' && !entry.recovered;
const ended = entry.hasResult || ['completed', 'failed'].includes(String(entry.status));
const active = !ended && running;
const input = record(entry.input);
const text = sanitizeAnalysisDisplayText(String(entry.text || entry.outputSummary || ''));
const status = entry.recovered ? '已恢复' : failed ? '未成功' : active ? '执行中' : ended ? '已返回' : '已停止';
return <details className={`analysis-event-tool ${failed ? 'is-failed' : ''}`}>
<summary className="analysis-tool-heading" aria-label={`${callLabel(entry)},${status},展开详情`}>
{active ? <Spin size="small" /> : failed ? <CloseCircleOutlined /> : ended ? <CheckCircleOutlined /> : <ClockCircleOutlined />}
<strong title={callLabel(entry)}>{callLabel(entry)}</strong><RightOutlined className="analysis-tool-chevron" />
</summary>
<div className="analysis-tool-details">
<p>{status}</p>
{Object.keys(input).length > 0 && <p className="analysis-event-conditions">{inputText(input)}</p>}
{text && <p>{text}</p>}
{typeof entry.at === 'string' && <time>{entry.at}</time>}
</div>
</details>;
}
export function AnalysisProcess({ turn }: { turn: Record<string, unknown> }) {
const result = record(turn.result);
const plan = record(turn.plan || result.plan);
const running = analysisIsRunning(turn.status || result.status);
const raw = turn.timeline || result.timeline || plan.timeline;
const timeline = compactAnalysisTimeline(Array.isArray(raw) ? raw.map(record) : []);
const answer = String(result.answer || turn.answer || '');
const rawSteps = turn.steps || result.steps || plan.steps;
const steps = Array.isArray(rawSteps) ? rawSteps.map(record) : [];
const [open, setOpen] = useState(running);
const [now, setNow] = useState(Date.now());
useEffect(() => { setOpen(running); }, [running]);
useEffect(() => {
if (!running) return;
const timer = window.setInterval(() => setNow(Date.now()), 1000);
return () => window.clearInterval(timer);
}, [running]);
if (!running && !steps.length) return null;
const started = Date.parse(String(turn.startedAt || plan.startedAt || turn.createdAt || ''));
const elapsed = Number.isFinite(started) ? Math.max(0, Math.floor((now - started) / 1000)) : undefined;
const message = sanitizeAnalysisDisplayText(String(turn.progressMessage || plan.progressMessage || (turn.status === 'QUEUED' ? '任务已排队,等待开始' : '正在研究问题并准备下一步查询…')));
return <section className={`analysis-process ${running ? 'is-running' : ''}`} aria-label="分析调用过程">
<button type="button" className="analysis-process-toggle" aria-expanded={open} onClick={() => setOpen(value => !value)}>
{running ? <Spin size="small" /> : <CheckCircleOutlined />}
<strong>{running ? '正在分析' : '查看分析过程'}</strong>
<span>{steps.length ? `${steps.length} 次调用` : '准备中'}{running && elapsed !== undefined ? ` · ${elapsed} 秒` : ''}</span>
{open ? <DownOutlined /> : <RightOutlined />}
</button>
{open && <div className="analysis-process-body">
<ol>{steps.map((step, index) => {
const state = String(step.status || '').toLowerCase();
const recovered = step.recovered === true;
const failed = ['failed', 'error'].includes(state) && !recovered;
const active = ['started', 'running', 'queued'].includes(state) && running;
const begin = Date.parse(String(step.startedAt || ''));
const end = Date.parse(String(step.finishedAt || ''));
const seconds = Number.isFinite(begin) && Number.isFinite(end) ? Math.max(0, (end - begin) / 1000).toFixed(1) : undefined;
const input = record(step.input);
return <li key={String(step.step || index)}>
<div className="analysis-process-step">{active ? <Spin size="small" /> : failed ? <CloseCircleOutlined /> : <CheckCircleOutlined />}<strong>{index + 1}. {callLabel(step)}</strong><span>{active ? '进行中' : recovered ? '已重试成功' : failed ? '未成功' : '已结束'}{seconds ? ` · ${seconds} 秒` : ''}</span></div>
{Object.keys(input).length > 0 && <details><summary>查询条件</summary><pre>{inputText(input)}</pre></details>}
{typeof step.outputSummary === 'string' && <p>{sanitizeAnalysisDisplayText(step.outputSummary)}</p>}
</li>;
})}</ol>
{running && <p className="analysis-process-current" role="status">{message}</p>}
</div>}
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>;
}
+2 -2
View File
@@ -36,7 +36,7 @@ function ReportDocument({ turn, stamp }: { turn: Row; stamp: string }) {
const question = sanitizeAnalysisDisplayText(String(turn.question || '质量分析报告'));
return <div className="q-report">
<style>{reportCss}</style>
<header><div className="q-eyebrow">质量中心 · 分析报告</div><h1>{question.length > 90 ? `${question.slice(0, 90)}…` : question}</h1><div className="q-subtitle">{period(main.context)}{period(main.context) ? ' · ' : ''}{stamp}</div></header>
<header><div className="q-eyebrow">质量数据分析平台 · 分析报告</div><h1>{question.length > 90 ? `${question.slice(0, 90)}…` : question}</h1><div className="q-subtitle">{period(main.context)}{period(main.context) ? ' · ' : ''}{stamp}</div></header>
{String(turn.status || result.status) === 'PARTIAL' && <p className="q-partial">本次分析部分完成,以下保留已获得的结果。</p>}
{Object.keys(summary).length > 0 && <div className="q-kpis">
<div className="q-kpi"><span>{adjusted ? '综合合格率(不含本部报废)' : '综合合格率'}</span><strong>{coverage.blackRows === 0 && coverage.brightRows === 0 ? '—' : rate(adjusted ? summary.compositeRateWithoutHeadquartersScrap : summary.compositeRate)}</strong></div>
@@ -57,7 +57,7 @@ function ReportDocument({ turn, stamp }: { turn: Row; stamp: string }) {
})}
{results.filter(item => item.kind === 'analysis_statistics').map((item, index) => <section key={`trend-${index}`}><h2>{stageName(item.stage)} · 历史趋势</h2><table><thead><tr><th>序号</th><th>期间</th><th>阶段合格率</th></tr></thead><tbody>{rows(item.trendChange).map((row, i) => <tr key={i}><td>{i + 1}</td><td>{text(row.label || row.period)}</td><td>{rate(row.stageRate)}</td></tr>)}</tbody></table></section>)}
{results.filter(item => Array.isArray(item.rows) && item.dimension && item.stage).map((item, index) => <section key={`top-${index}`}><h2>{stageName(item.stage)} · TOP核查对象</h2><table><thead><tr><th>序号</th><th>对象</th><th>报废重量(kg)</th><th>占比</th></tr></thead><tbody>{rows(item.rows).slice(0, 10).map((row, i) => <tr key={i}><td>{i + 1}</td><td>{text(row.label || row.key)}</td><td>{number(row.weight)}</td><td>{rate(row.share)}</td></tr>)}</tbody></table></section>)}
<footer>数据来源:质量中心。指标沿用正式计算口径,原因判断的依据与局限见分析结论。</footer>
<footer>数据来源:质量数据分析平台。指标沿用正式计算口径,原因判断的依据与局限见分析结论。</footer>
</div>;
}
+91 -16
View File
@@ -7,12 +7,12 @@ import {
Button,
Checkbox,
Drawer,
Dropdown,
Empty,
Form,
Input,
Modal,
Pagination,
Popconfirm,
Progress,
Select,
Spin,
@@ -22,7 +22,7 @@ import {
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { QualityTable as Table } from './QualityTable';
import { DeleteOutlined, DownloadOutlined, ReloadOutlined, RobotOutlined } from '@ant-design/icons';
import { DeleteOutlined, DownloadOutlined, 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';
import type { DataWorkflowStatus } from './NoCodeDataTypes';
@@ -33,6 +33,7 @@ import { TargetVersionAdmin } from './AnalyticsCompletion';
import { AnalysisReportExport, NativeAnalysisReport } from './AnalysisReportExport';
import { AiMarkdown } from './AiMarkdown';
import { AnalysisApiSettings } from './AnalysisApiSettings';
import { acceptAnalysisEvent, analysisScrollFollows, partialAnalysisNotice, partialAnswerIsOnlyProgress } from './analysisConversationState';
import { AnalysisProcess } from './AnalysisProcess';
import { activeAnalysisTurn, analysisIsRunning, beginAnalysisSelection, defaultAnalysisSession, rememberAnalysisSession, rememberPendingAnalysisSession, settledAnalysisTurn } from './analysisConversationState';
import './analysis-chat.css';
@@ -76,8 +77,9 @@ const ANALYSIS_FINAL_STATUSES = new Set(['COMPLETED', 'PARTIAL', 'FAILED', 'CANC
function generateReportPrompt(turn: Record<string, unknown>): string {
const result = isObjectRecord(turn.result) ? turn.result : turn;
const question = (typeof turn.question === 'string' ? turn.question : '').trim().slice(0, 240);
const answer = typeof result.answer === 'string' ? result.answer : typeof turn.answer === 'string' ? turn.answer : '';
const prefix = `请将关于「${question || '本次质量分析'}」的这次分析生成报告,沿用该分析的期间与范围。\n\n本次分析结论供参考,请忠于已有数据,不要补造指标或数字:\n`;
const answer = partialAnswerIsOnlyProgress(turn) ? '' : typeof result.answer === 'string' ? result.answer : typeof turn.answer === 'string' ? turn.answer : '';
const partial = String(turn.status || result.status).toUpperCase() === 'PARTIAL';
const prefix = `请将关于「${question || '本次质量分析'}」的这次分析生成报告,沿用该分析的期间与范围。${partial ? '本次分析部分完成,报告须保留这个状态和未完成范围,不得写成已全部核验。' : ''}\n\n本次分析结论供参考,请忠于已有数据,不要补造指标或数字:\n`;
return `${prefix}${answer.slice(0, Math.max(0, 1600 - prefix.length))}`;
}
@@ -945,7 +947,10 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
}
function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown) => boolean; user: AuthUser }) {
const { message } = App.useApp();
const { message, modal } = App.useApp();
const [renameTarget, setRenameTarget] = useState<Record<string, unknown> | null>(null);
const [renameTitle, setRenameTitle] = useState('');
const [renaming, setRenaming] = useState(false);
const initialParams = new URLSearchParams(window.location.search);
const initialSessionId = initialParams.get('sessionId') || '';
const initialTurnId = initialParams.get('turnId') || '';
@@ -971,8 +976,17 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
const subscriptionGeneration = useRef(0);
const [releaseId, setReleaseId] = useState<string>();
const [sourceResultRef, setSourceResultRef] = useState<AnalysisResultRef>();
const conversationEnd = useRef<HTMLDivElement>(null);
useEffect(() => { conversationEnd.current?.scrollIntoView({ block: 'nearest' }); }, [lastTurn, busy]);
const conversation = useRef<HTMLDivElement>(null);
const followOutput = useRef(true);
const previousScrollTop = useRef(0);
useEffect(() => { followOutput.current = true; previousScrollTop.current = 0; }, [sessionId]);
useEffect(() => {
const element = conversation.current;
if (element && followOutput.current) {
element.scrollTop = element.scrollHeight;
previousScrollTop.current = element.scrollTop;
}
}, [lastTurn, busy, turns, sessionId]);
const loadSessions = async () => {
try { const items = collectionItems(await api.analysisSessions()); if (mounted.current) setSessions(items); }
@@ -1141,6 +1155,16 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
}
};
const renameSession = async () => {
if (!renameTarget || !renameTitle.trim() || renaming) return;
setRenaming(true);
try {
await api.renameAnalysisSession(String(renameTarget.id), renameTitle.trim());
setRenameTarget(null); await loadSessions(); message.success('会话已重命名');
} catch (value) { if (!onUnauthorized(value)) message.error(apiMessage(value)); }
finally { setRenaming(false); }
};
const followTurn = async (id: string, question: string, sessionOverride?: string) => {
if (!mounted.current) return;
streamController.current?.abort();
@@ -1165,6 +1189,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
onEvent: event => {
if (!current()) return;
receivedEvents += 1;
if (!acceptAnalysisEvent(event.id, eventCursors.current[id])) return;
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' ? '正在整理分析结论…' : '正在分析…';
@@ -1179,6 +1204,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
}
setLastTurn(previous => {
const prior = previous || {};
if (prior.id === id && ANALYSIS_FINAL_STATUSES.has(String(prior.status || '').toUpperCase()) && !ANALYSIS_FINAL_STATUSES.has(eventStatus)) return prior;
const priorResult = isObjectRecord(prior.result) ? prior.result : {};
const status = data.status || (['progress', 'message', 'heartbeat'].includes(event.event.toLowerCase()) ? prior.status || 'RUNNING' : event.event.toUpperCase());
return {
@@ -1192,6 +1218,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
...(typeof data.startedAt === 'string' ? { startedAt: data.startedAt } : {}),
...(typeof data.updatedAt === 'string' ? { updatedAt: data.updatedAt } : {}),
progressMessage: messageText,
...(Array.isArray(data.timeline) ? { timeline: data.timeline } : {}),
plan: data.plan || prior.plan,
...(eventResult ? { result: { ...priorResult, ...eventResult } } : {}),
};
@@ -1297,7 +1324,15 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
if (!mounted.current || generation !== navigationGeneration.current) return;
setStreamProgress('正在停止分析…');
const detail = await api.analysisTurn(id);
if (mounted.current && generation === navigationGeneration.current) setLastTurn(previous => ({ ...detail, id, question: previous?.question }));
if (mounted.current && generation === navigationGeneration.current) {
setLastTurn(previous => ({ ...detail, id, question: previous?.question }));
if (ANALYSIS_FINAL_STATUSES.has(String(detail.status || '').toUpperCase())) {
subscriptionGeneration.current += 1;
streamController.current?.abort(); streamController.current = null;
setBusy(false); setActiveTurnId(''); setStreamProgress('');
await loadSessions();
}
}
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
};
@@ -1344,6 +1379,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
const submit = async (question = query) => {
if (!question.trim()) return;
if (busy || historyLoading) return;
followOutput.current = true;
const selection = beginAnalysisSelection(user.id);
rememberAnalysisSession(user.id, '');
const generation = navigationGeneration.current;
@@ -1390,15 +1426,27 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
<div className="analysis-workspace">
<aside className="panel analysis-session-panel">
<div className="analysis-session-heading"><strong>会话</strong><Button type="primary" size="small" onClick={newSession}>新会话</Button></div>
{historyLoading ? <div className="loading-panel compact"><Spin />正在读取会话…</div> : sessions.length ? <div className="analysis-session-list">{sessions.map(item => <div key={String(item.id)} className={`analysis-session-row ${sessionId === item.id ? 'active' : ''}`}><button className="analysis-session-item" onClick={() => void openSession(String(item.id))}><strong>{toText(item.title || '未命名会话')}</strong><small>{String(item.updatedAt || item.createdAt || '').slice(0, 10)}{analysisIsRunning(item.activeTurnStatus) && <span className="analysis-session-state">{item.activeTurnStatus === 'QUEUED' ? '排队中' : '分析中'}</span>}</small></button><Popconfirm title="删除此会话及其分析记录?" description="删除后无法恢复" okText="删除" cancelText="取消" okButtonProps={{ danger: true }} onConfirm={() => void deleteSession(String(item.id))}><Button className="analysis-session-delete" type="text" danger icon={<DeleteOutlined />} aria-label={`删除会话 ${toText(item.title || '未命名会话')}`} disabled={analysisIsRunning(item.activeTurnStatus)} /></Popconfirm></div>)}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无历史会话" />}
{historyLoading ? <div className="loading-panel compact"><Spin />正在读取会话…</div> : sessions.length ? <div className="analysis-session-list">{sessions.map(item => <div key={String(item.id)} className={`analysis-session-row ${sessionId === item.id ? 'active' : ''}`}><button className="analysis-session-item" onClick={() => void openSession(String(item.id))}><strong>{toText(item.title || '未命名会话')}</strong><small>{String(item.updatedAt || item.createdAt || '').slice(0, 10)}{analysisIsRunning(item.activeTurnStatus) && <span className="analysis-session-state">{item.activeTurnStatus === 'QUEUED' ? '排队中' : '分析中'}</span>}</small></button><Dropdown trigger={['click']} menu={{ items: [
{ key: 'rename', icon: <EditOutlined />, label: '重命名' },
{ key: 'delete', icon: <DeleteOutlined />, label: '删除', danger: true, disabled: analysisIsRunning(item.activeTurnStatus) },
], onClick: ({ key }) => {
if (key === 'rename') { setRenameTarget(item); setRenameTitle(String(item.title || '')); }
else if (key === 'delete') modal.confirm({ title: '删除此会话及其分析记录?', content: '删除后无法恢复', okText: '删除', cancelText: '取消', okButtonProps: { danger: true }, onOk: () => deleteSession(String(item.id)) });
} }}><Button className="analysis-session-menu" type="text" icon={<MoreOutlined />} aria-label={`会话操作 ${toText(item.title || '未命名会话')}`} /></Dropdown></div>)}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无历史会话" />}
</aside>
<section className="panel analysis-chat-panel">
<div className="analysis-conversation" aria-live="polite">
<div className="analysis-conversation" ref={conversation} aria-live="polite" onWheel={event => {
if (event.deltaY < 0 && event.currentTarget.scrollTop > 0) followOutput.current = false;
}} onScroll={event => {
const element = event.currentTarget;
followOutput.current = analysisScrollFollows(previousScrollTop.current, element.scrollTop,
element.scrollHeight - element.clientHeight - element.scrollTop, followOutput.current);
previousScrollTop.current = element.scrollTop;
}}>
{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 || '')); }} onGenerateReport={() => void submit(generateReportPrompt(turn))} retryDisabled={busy || historyLoading} />)}
{lastTurn && <AnalysisTurn turn={lastTurn} onRetry={() => void retryTurn(lastTurn)} onResume={id => { if (!historyLoading) void followTurn(id, String(lastTurn.question || '')); }} onGenerateReport={() => void submit(generateReportPrompt(lastTurn))} retryDisabled={busy || historyLoading} />}
{busy && <div className="analysis-progress"><span>{streamProgress || '正在分析…'}</span><Button size="small" danger onClick={() => void cancelTurn()}>停止分析</Button></div>}
{!turns.length && !lastTurn && !busy && <div className="analysis-empty"><RobotOutlined /><strong>想了解哪些质量情况?</strong><span>例如:9月汽车交通的合格率为什么下降?</span></div>}
<div ref={conversationEnd} />
</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(); void submit(); } }} />
@@ -1406,13 +1454,16 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
</div>
</section>
</div>
<Modal title="重命名会话" open={Boolean(renameTarget)} confirmLoading={renaming} okText="保存" cancelText="取消" okButtonProps={{ disabled: !renameTitle.trim() }} onCancel={() => { if (!renaming) setRenameTarget(null); }} onOk={() => void renameSession()}>
<Input aria-label="会话名称" value={renameTitle} maxLength={160} disabled={renaming} onChange={event => setRenameTitle(event.target.value)} onPressEnter={() => void renameSession()} />
</Modal>
</div>;
}
function AnalysisTurn({ turn, onResume, onRetry, onGenerateReport, retryDisabled = false }: { turn: Record<string, unknown>; onResume?: (turnId: string) => void; onRetry?: (turnId: string) => void; onGenerateReport?: () => void; retryDisabled?: boolean }) {
const question = typeof turn.question === 'string' ? turn.question : '';
const result = isObjectRecord(turn.result) ? turn.result : turn;
const answer = typeof result.answer === 'string' ? result.answer : typeof turn.answer === 'string' ? turn.answer : '';
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 engine = String(result.engine || turn.engine || '').toUpperCase();
const reportMarkdown = typeof result.reportMarkdown === 'string' ? result.reportMarkdown : typeof turn.reportMarkdown === 'string' ? turn.reportMarkdown : '';
@@ -1421,18 +1472,19 @@ function AnalysisTurn({ turn, onResume, onRetry, onGenerateReport, retryDisabled
const errorValue = result.error || turn.error;
const failure = typeof errorValue === 'string' ? errorValue : '分析暂时中断,可以重试或继续提问。';
const emptyStatus = status === 'CANCELLED' ? '本次分析已取消,未返回回答内容。'
: status === 'PARTIAL' ? '本次分析部分完成,但未返回可显示的回答内容。'
: status === 'PARTIAL' ? '本轮已保存查询过程,尚未形成最终答复。'
: status === 'COMPLETED' ? '分析任务已完成,但未返回回答内容。'
: failure;
return <article className="analysis-turn">
{question && <div className="analysis-question"><p>{question}</p></div>}
<AnalysisTurnMetadata turn={turn} status={status} />
<AnalysisProcess turn={turn} />
{(answer || !resumable || !retryDisabled) && <div className="analysis-answer">
{(!resumable || !Array.isArray(turn.timeline || (isObjectRecord(turn.plan) ? turn.plan.timeline : undefined))) && (answer || !resumable || !retryDisabled) && <div className="analysis-answer">
{answer ? <AiMarkdown content={answer} className="ai-answer" /> : <p className={resumable ? 'analysis-chat-notice' : undefined}>{resumable ? '分析任务仍在运行,尚未返回完整回答。' : emptyStatus}</p>}
{status === 'PARTIAL' && <p className="analysis-chat-notice">部分分析尚未完成,可以重试或继续追问。</p>}
{status === 'PARTIAL' && answer && <p className="analysis-chat-notice">{partialAnalysisNotice(result.stopReason || turn.stopReason || (isObjectRecord(turn.plan) ? turn.plan.stopReason : ''))}</p>}
<div className="analysis-message-actions">
{reportMarkdown.trim() && <NativeAnalysisReport turn={turn} reportMarkdown={reportMarkdown} reportHtml={reportHtml} />}
{!reportMarkdown.trim() && engine === 'NAO' && status === 'COMPLETED' && answer && onGenerateReport && <Button type="text" size="small" icon={<DownloadOutlined />} disabled={retryDisabled} onClick={onGenerateReport}>生成报告</Button>}
{!reportMarkdown.trim() && engine === 'NAO' && ['COMPLETED', 'PARTIAL'].includes(status) && answer && onGenerateReport && <Button type="text" size="small" icon={<DownloadOutlined />} disabled={retryDisabled} onClick={onGenerateReport}>生成报告</Button>}
{!reportMarkdown.trim() && engine !== 'NAO' && answer && ['COMPLETED', 'PARTIAL'].includes(status) && <AnalysisReportExport turn={turn} />}
{['FAILED', 'CANCELLED', 'PARTIAL'].includes(status) && typeof turn.id === 'string' && onRetry && <Button size="small" type="text" disabled={retryDisabled} onClick={() => onRetry(String(turn.id))}>重新分析</Button>}
{resumable && !retryDisabled && typeof turn.id === 'string' && onResume && <Button size="small" type="text" onClick={() => onResume(String(turn.id))}>继续分析</Button>}
@@ -1441,6 +1493,29 @@ function AnalysisTurn({ turn, onResume, onRetry, onGenerateReport, retryDisabled
</article>;
}
function AnalysisTurnMetadata({ turn, status }: { turn: Record<string, unknown>; status: string }) {
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]);
const plan = isObjectRecord(turn.plan) ? turn.plan : {};
const date = (value: unknown) => typeof value === 'string' && Number.isFinite(Date.parse(value)) ? Date.parse(value) : undefined;
const start = date(turn.startedAt) ?? date(plan.startedAt);
const finish = date(turn.finishedAt);
const duration = typeof turn.durationMs === 'number' ? turn.durationMs : start !== undefined && (running || finish !== undefined) ? Math.max(0, (running ? now : finish!) - start) : undefined;
const seconds = duration === undefined ? undefined : Math.floor(duration / 1000);
const durationText = seconds === undefined ? '' : seconds >= 3600 ? `${Math.floor(seconds / 3600)}小时${Math.floor(seconds % 3600 / 60)}分${seconds % 60}秒` : seconds >= 60 ? `${Math.floor(seconds / 60)}分${seconds % 60}秒` : `${seconds}秒`;
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="分析运行信息">
<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>;
}
function isObjectRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
+86
View File
@@ -0,0 +1,86 @@
import { useEffect, useState } from 'react';
import { Alert, App, Button, Descriptions, Form, Input, Modal, Tabs } from 'antd';
import { api } from './api';
import type { AuthUser } from './types';
export type AccountTab = 'profile' | 'password';
type PasswordValues = { currentPassword: string; newPassword: string; confirmation: string };
const roles: Record<string, string> = {
DATA_MAINTAINER: '数据维护', DATA_PUBLISHER: '数据发布', QUALITY_VIEWER: '质量查看',
RULE_MAINTAINER: '规则维护', SYSTEM_ADMIN: '系统管理', SYSTEM_OPERATOR: '运行维护',
BUSINESS_ANALYST: '业务分析', AUDIT_VIEWER: '审计查看',
};
export default function PersonalAccount({ user, tab, onClose, onUserChange, onUnauthorized, onLogout }: {
user: AuthUser; tab: AccountTab | null; onClose: () => void;
onUserChange: (user: AuthUser) => void; onUnauthorized: (error: unknown) => boolean;
onLogout: () => Promise<void>;
}) {
const { message } = App.useApp();
const [form] = Form.useForm<PasswordValues>();
const [activeTab, setActiveTab] = useState<AccountTab>('profile');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const forced = user.forcePasswordChange === true;
const open = tab !== null || forced;
useEffect(() => {
if (open) { setActiveTab(forced ? 'password' : tab || 'profile'); setError(''); form.resetFields(); }
}, [open, tab, forced, form]);
const save = async (values: PasswordValues) => {
setBusy(true); setError('');
try {
await api.changePassword(values.currentPassword, values.newPassword);
form.resetFields();
onUserChange({ ...user, forcePasswordChange: false });
onClose();
message.success('密码已修改,下次登录请使用新密码');
} catch (failure) {
if (!onUnauthorized(failure)) setError(failure instanceof Error ? failure.message : '修改失败,请重试');
} finally { setBusy(false); }
};
return <Modal className="personal-account-modal" open={open} title="个人账户" width={520} footer={null}
closable={!forced && !busy} maskClosable={!forced && !busy} keyboard={!forced && !busy}
onCancel={() => { if (!busy && !forced) onClose(); }} destroyOnHidden>
{forced && <Alert type="warning" showIcon message="请先修改初始密码" style={{ marginBottom: 16 }} />}
<Tabs activeKey={activeTab} onChange={key => setActiveTab(key as AccountTab)} items={[
{ key: 'profile', label: '个人资料', disabled: forced || busy, children: <Descriptions column={1} bordered size="small" items={[
{ key: 'username', label: '登录账号', children: user.username },
{ key: 'name', label: '姓名', children: user.displayName || '未设置' },
{ key: 'departments', label: '所属部门', children: user.departments.map(name => name === '质量管理部' ? '质量中心' : name).join('、') || '未设置' },
{ key: 'roles', label: '角色', children: user.roles.map(role => roles[role] || role).join('、') || '未设置' },
]} /> },
{ key: 'password', label: '修改密码', children: <Form form={form} layout="vertical" onFinish={save} requiredMark={false}
onValuesChange={() => setError('')} disabled={busy}>
<Form.Item name="currentPassword" label="当前密码" rules={[{ required: true, message: '请输入当前密码' }]}>
<Input.Password autoComplete="current-password" />
</Form.Item>
<Form.Item name="newPassword" label="新密码" dependencies={['currentPassword']} rules={[
{ required: true, message: '请输入新密码' },
{ min: 6, message: '新密码至少6位' },
({ getFieldValue }) => ({ validator: (_, value: string) => {
if (value && new TextEncoder().encode(value).length > 72) return Promise.reject(new Error('新密码过长,请缩短后重试'));
if (value && value === getFieldValue('currentPassword')) return Promise.reject(new Error('新密码不能与当前密码相同'));
return Promise.resolve();
} }),
]}>
<Input.Password autoComplete="new-password" placeholder="至少6位" />
</Form.Item>
<Form.Item name="confirmation" label="确认新密码" dependencies={['newPassword']} rules={[
{ required: true, message: '请再次输入新密码' },
({ getFieldValue }) => ({ validator: (_, value: string) => !value || value === getFieldValue('newPassword')
? Promise.resolve() : Promise.reject(new Error('两次输入的新密码不一致')) }),
]}>
<Input.Password autoComplete="new-password" />
</Form.Item>
{error && <Alert type="error" showIcon message={error} style={{ marginBottom: 16 }} />}
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
{forced ? <Button disabled={busy} onClick={() => void onLogout()}>退出登录</Button> : <Button disabled={busy} onClick={onClose}>取消</Button>}
<Button type="primary" htmlType="submit" loading={busy}>保存密码</Button>
</div>
</Form> },
]} />
</Modal>;
}
+32 -18
View File
@@ -26,11 +26,13 @@ import {
SettingOutlined,
TeamOutlined,
ToolOutlined,
UserOutlined,
} from '@ant-design/icons';
import { ApiError, api } from './api';
import type { AuthUser, QueryParams } from './types';
import { workspaceThemes, type WorkspaceThemeId } from './ui-themes';
import { readableSelectPopup } from './readableSelectPopup';
import PersonalAccount, { type AccountTab } from './PersonalAccount';
const QueryPage = lazy(() => import('./QueryPage'));
const ManagementPages = lazy(() => import('./ManagementPages'));
@@ -112,6 +114,7 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
const [user, setUser] = useState<AuthUser | null>(null);
const [sessionLoading, setSessionLoading] = useState(true);
const [sessionError, setSessionError] = useState('');
const [accountTab, setAccountTab] = useState<AccountTab | null>(null);
useEffect(() => {
const syncFromLocation = () => {
@@ -173,7 +176,12 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
return false;
}, []);
if (sessionLoading) return <div className="screen-state"><Spin indicator={<LoadingOutlined spin />} /> <span>正在连接质量中心…</span></div>;
const logout = async () => {
try { await api.logout(); setAccountTab(null); setUser(null); }
catch (error) { if (!handleUnauthorized(error)) message.error(error instanceof Error ? error.message : '退出失败'); }
};
if (sessionLoading) return <div className="screen-state"><Spin indicator={<LoadingOutlined spin />} /> <span>正在连接质量数据分析平台…</span></div>;
if (sessionError) return <div className="screen-state"><div className="state-card"><strong>服务暂不可用</strong><p>{sessionError}</p><Button onClick={() => window.location.reload()}>重新连接</Button></div></div>;
if (!user) return <LoginPage onSuccess={setUser} />;
@@ -182,9 +190,9 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
<aside className="sidebar">
<button className="brand" onClick={() => navigate('overall')} aria-label="回到总体汇总">
<span className="brand-mark" aria-hidden="true"><i /><i /><i /></span>
<span>质量中心</span>
<span>质量数据分析平台</span>
</button>
<div className="workspace-caption">质量中心 · 分析工作台</div>
<div className="workspace-caption">分析工作台</div>
<nav className="side-navigation" aria-label="主导航">
{navGroups.map(group => (
<div className="nav-group" key={group.label}>
@@ -204,12 +212,11 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
))}
</nav>
<div className="user-block">
<span className="avatar">{(user.displayName || user.username).slice(0, 1)}</span>
<span className="user-copy"><strong>{user.displayName || user.username}</strong><small>{user.departments.length ? user.departments.map(shownDepartment).join('、') : '质量中心'}</small></span>
<Tooltip title="退出登录"><Button type="text" icon={<LogoutOutlined />} aria-label="退出登录" onClick={async () => {
try { await api.logout(); setUser(null); }
catch (error) { if (!handleUnauthorized(error)) message.error(error instanceof Error ? error.message : '退出失败'); }
}} /></Tooltip>
<button type="button" className="user-profile-trigger" aria-label="打开个人账户" onClick={() => setAccountTab('profile')}>
<span className="avatar">{(user.displayName || user.username).slice(0, 1)}</span>
<span className="user-copy"><strong>{user.displayName || user.username}</strong><small>{user.departments.map(shownDepartment).join('、') || '个人账户'}</small></span>
</button>
<Tooltip title="退出登录"><Button type="text" icon={<LogoutOutlined />} aria-label="退出登录" onClick={() => void logout()} /></Tooltip>
</div>
</aside>
@@ -233,18 +240,23 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
<BgColorsOutlined /><span>{appearance.name}</span><DownOutlined />
</Button>
</Dropdown>
<span className="top-organization"><TeamOutlined />质量中心</span>
{user.departments.length > 0 && <span className="top-organization"><TeamOutlined />{user.departments.map(shownDepartment).join('、')}</span>}
<Dropdown trigger={['click']} menu={{ items: [
{ key: 'profile', icon: <UserOutlined />, label: '个人资料' },
{ key: 'password', icon: <KeyOutlined />, label: '修改密码' },
{ type: 'divider' },
{ key: 'logout', icon: <LogoutOutlined />, label: '退出登录' },
], onClick: ({ key }) => { if (key === 'logout') void logout(); else setAccountTab(key as AccountTab); } }}>
<Button type="text" aria-label="个人账户菜单"><UserOutlined />{user.displayName || user.username}<DownOutlined /></Button>
</Dropdown>
</div>
</header>
<div className="mobile-brand">
<span className="brand-mark" aria-hidden="true"><i /><i /><i /></span><strong>质量中心</strong>
<span className="brand-mark" aria-hidden="true"><i /><i /><i /></span><strong>质量数据分析平台</strong>
<Select<PageKey> {...readableSelectPopup} aria-label="页面导航" value={page} onChange={value => navigate(value)} options={[
...navGroups.map(group => ({ label: group.label, options: group.items.map(([value, label]) => ({ value, label })) })),
]} />
<Button type="text" icon={<LogoutOutlined />} aria-label="退出登录" onClick={async () => {
try { await api.logout(); setUser(null); }
catch (error) { if (!handleUnauthorized(error)) message.error(error instanceof Error ? error.message : '退出失败'); }
}} />
<Button type="text" icon={<UserOutlined />} aria-label="打开个人账户" onClick={() => setAccountTab('profile')} />
</div>
<div className="page-content">
<Suspense fallback={<div className="loading-panel"><Spin />正在打开页面…</div>}>
@@ -256,6 +268,8 @@ export default function QualityWorkspace({ appearance, onAppearanceChange }: Qua
</Suspense>
</div>
</main>
<PersonalAccount user={user} tab={accountTab} onClose={() => setAccountTab(null)} onUserChange={setUser}
onUnauthorized={handleUnauthorized} onLogout={logout} />
</div>
);
}
@@ -279,13 +293,13 @@ function LoginPage({ onSuccess }: { onSuccess: (user: AuthUser) => void }) {
return (
<div className="login-screen">
<section className="login-art" aria-label="质量中心品牌介绍">
<section className="login-art" aria-label="质量数据分析平台品牌介绍">
<div className="login-orbit login-orbit-one" aria-hidden="true" />
<div className="login-orbit login-orbit-two" aria-hidden="true" />
<div className="login-brand-lockup">
<img src="/yunsheng-logo.png" alt="宁波韵升" />
<span className="login-brand-divider" />
<strong>质量中心</strong>
<strong>质量数据分析平台</strong>
</div>
<div className="login-art-copy">
<span className="login-eyebrow">QUALITY DATA PLATFORM</span>
@@ -304,7 +318,7 @@ function LoginPage({ onSuccess }: { onSuccess: (user: AuthUser) => void }) {
<Input.Password autoComplete="current-password" placeholder="请输入密码" disabled={busy} />
</Form.Item>
{loginError && <Alert className="login-error" type="error" showIcon message={loginError} role="alert" />}
<Button className="login-submit" type="primary" htmlType="submit" loading={busy} block>{busy ? '正在登录…' : '登录质量中心'}</Button>
<Button className="login-submit" type="primary" htmlType="submit" loading={busy} block>{busy ? '正在登录…' : '登录'}</Button>
</Form>
</div>
<footer className="login-footer">宁波韵升股份有限公司 <span>·</span> © 2026</footer>
+50 -31
View File
@@ -38,9 +38,8 @@ import type {
ViewKind,
} from './types';
import type { PageKey } from './QualityWorkspace';
import { M01Insights } from './AnalyticsCompletion';
import { readableSelectPopup } from './readableSelectPopup';
import { isInternalDataField } from './publicDataDisplay';
import { isInternalDataField, readableMetricFormula } from './publicDataDisplay';
import { previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
import { defectWeightRate } from './trendMetrics';
import './query-motion.css';
@@ -248,7 +247,7 @@ function toApiParams(args: {
}
function applyTrendObject(query: QueryParams, trendObject: string, view: ViewKind): QueryParams {
if (!trendObject) return query;
if (!trendObject) return { ...query };
const params: QueryParams = { ...query };
if (view === 'department') params.department = trendObject;
if (view === 'group') params.group = trendObject;
@@ -319,11 +318,8 @@ export default function QueryPage({ page, onUnauthorized }: {
const [recordMonth, setRecordMonth] = useState<number>();
const [basisOpen, setBasisOpen] = useState(false);
const trendAnchorTop = useRef<number | null>(null);
useEffect(() => {
const timer = window.setTimeout(() => setAppliedSearch(search), 300);
return () => window.clearTimeout(timer);
}, [search]);
const tableContent = useRef<HTMLDivElement>(null);
const tableHeight = useRef(525);
useEffect(() => {
setTrendObject('');
@@ -386,11 +382,14 @@ export default function QueryPage({ page, onUnauthorized }: {
}, [drilldownContextKey]);
const metricParams = useMemo<QueryParams>(() => ({ ...queryParams, trendGranularity: 'month' }), [queryParams]);
const metricKey = useMemo(() => JSON.stringify(metricParams), [metricParams]);
const currentMetricsData = dataKey === metricKey ? data : null;
const currentMetricsError = errorKey === metricKey ? error : '';
const currentMetricsData = dataKey === metricKey && !currentMetricsError ? data : null;
const queryPending = !currentMetricsData && !currentMetricsError;
const queryBusy = loading || queryPending;
const metricKeyRef = useRef(metricKey);
useLayoutEffect(() => {
if (currentMetricsData && tableContent.current) tableHeight.current = tableContent.current.getBoundingClientRect().height;
}, [currentMetricsData, fullFields, drilledProduct]);
metricKeyRef.current = metricKey;
const useSummaryTrend = period === 'year' && !trendObject && trendGranularity === 'month';
const trendParams = useMemo<QueryParams>(() => {
@@ -585,8 +584,17 @@ export default function QueryPage({ page, onUnauthorized }: {
if (trendAnchorTop.current == null) return;
const nextTop = document.getElementById('monthly-trend')?.getBoundingClientRect().top;
if (nextTop != null) window.scrollBy(0, nextTop - trendAnchorTop.current);
trendAnchorTop.current = null;
}, [period, year, month, quarter]);
// Keep the anchor through the response as the new result may have a
// different row count. Clearing it at request start allowed a second jump.
if (currentMetricsData || currentMetricsError) trendAnchorTop.current = null;
}, [period, year, month, quarter, currentMetricsData, currentMetricsError]);
useEffect(() => {
const releaseAnchor = () => { trendAnchorTop.current = null; };
window.addEventListener('wheel', releaseAnchor, { passive: true });
window.addEventListener('touchstart', releaseAnchor, { passive: true });
return () => { window.removeEventListener('wheel', releaseAnchor); window.removeEventListener('touchstart', releaseAnchor); };
}, []);
const years = (options?.years || []).map(value => { const numeric = Number(String(value).match(/\d{4}/)?.[0]); return { label: `${numeric}年`, value: numeric }; }).filter(item => Number.isFinite(item.value));
const filterSelect = (label: string, value: string[], choices: string[] | undefined, change: (value: string[]) => void, allowUnassigned = true) => (
@@ -616,7 +624,7 @@ export default function QueryPage({ page, onUnauthorized }: {
const formulaDescriptions = rawFormulaDescriptions && typeof rawFormulaDescriptions === 'object' && !Array.isArray(rawFormulaDescriptions) ? rawFormulaDescriptions as Record<string, unknown> : {};
const compositeFormula = formulaDescriptions[rateBasis === 'original' ? 'compositeRate' : 'compositeRateWithoutHeadquartersScrap'];
const brightFormula = formulaDescriptions[rateBasis === 'original' ? 'brightRate' : 'brightRateWithoutHeadquartersScrap'];
const formulaText = (description: unknown) => typeof description === 'string' && description.trim() ? description : '当前指标服务未提供公式说明';
const formulaText = readableMetricFormula;
const blackDefectItems = activeDefectData?.defects?.black || [];
const brightDefectItems = activeDefectData?.defects?.bright || [];
const organizationPaths = options?.organizationPaths || [];
@@ -642,8 +650,8 @@ export default function QueryPage({ page, onUnauthorized }: {
if (search.trim().toLocaleLowerCase() === trendObject.toLocaleLowerCase()) setSearch('');
}
}, [options, trendOptions, trendObject, search]);
const setSynchronizedSearch = (value: string) => {
setSearch(value);
const applySearch = (value = search) => {
setAppliedSearch(value.trim());
const normalized = value.trim().toLocaleLowerCase();
const exactOption = normalized ? trendOptions.find(item => item.value.trim().toLocaleLowerCase() === normalized) : undefined;
setTrendObject(exactOption?.value || '');
@@ -652,6 +660,7 @@ export default function QueryPage({ page, onUnauthorized }: {
const selected = value || '';
setTrendObject(selected);
setSearch(selected);
setAppliedSearch(selected);
};
const organizationSummary = [
department.length ? `产业部:${department.map(value => value === '__UNASSIGNED__' ? '未分类' : value).join('、')}` : '',
@@ -693,7 +702,7 @@ export default function QueryPage({ page, onUnauthorized }: {
<Checkbox className="query-unassigned" checked={includeUnassigned} onChange={event => setIncludeUnassigned(event.target.checked)}>包含未分类行</Checkbox>
<div className="query-toolbar-tail">
<span className={`query-status ${queryBusy ? 'busy' : currentMetricsError ? 'failed' : ''}`}><i />{queryBusy ? '正在查询' : currentMetricsError ? '查询失败' : '查询完成'}</span>
<Button type="text" onClick={() => { const previous = previousCompleteMonth(); const previousQuarter = previousCompleteQuarter(); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setIncludeUnassigned(false); setSearch(''); setTrendObject(''); setYear(page === 'overall' ? new Date().getFullYear() : previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod(page === 'overall' ? 'year' : 'month'); setTrendGranularity('month'); }}>重置</Button>
<Button type="text" onClick={() => { const previous = previousCompleteMonth(); const previousQuarter = previousCompleteQuarter(); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setIncludeUnassigned(false); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(page === 'overall' ? new Date().getFullYear() : previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod(page === 'overall' ? 'year' : 'month'); setTrendGranularity('month'); }}>重置</Button>
</div>
{organizationSummary.length > 0 && <div className="organization-breadcrumb" aria-label="当前组织路径">
<span>组织路径</span><Button type="link" onClick={() => { setDepartment([]); setGroup([]); setProduct([]); }}>全部组织</Button>
@@ -702,14 +711,19 @@ export default function QueryPage({ page, onUnauthorized }: {
</section>
{currentMetricsError && <Alert showIcon type="error" message="质量指标查询失败" description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
<section className="metric-strip" aria-label="质量指标">
<section className={`metric-strip ${!currentMetricsData ? 'query-awaiting-data' : ''}`} aria-label="质量指标" aria-busy={queryBusy} inert={!currentMetricsData}>
<div className="rate-basis-control"><span>亮片本部报废调整</span><Segmented size="small" value={rateBasis} options={[{ label: '原口径', value: 'original' }, { label: '去本部报废', value: 'withoutHeadquartersScrap' }]} onChange={value => setRateBasis(value as typeof rateBasis)} aria-label="合格率口径" /></div>
<MetricCard primary label={rateBasis === 'original' ? '综合合格率' : '综合调整率'} value={rateText(visibleCompositeRate(rowForSummary, rateBasis))} onClick={() => setBasisOpen(true)} />
<MetricCard label="黑片合格率" value={rateText(visibleStageRate(rowForSummary, 'black'))} note={hasStageRows(rowForSummary, 'black') ? hasValidRateDenominator(rowForSummary, 'black') ? `合格重量 ${numberText(rowForSummary?.black?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少黑片来源'} stage="black" onClick={() => openRecords(null, 'black')} />
<MetricCard label={rateBasis === 'original' ? '亮片合格率' : '亮片调整率'} value={rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))} note={hasStageRows(rowForSummary, 'bright') ? hasValidRateDenominator(rowForSummary, 'bright') ? `合格重量 ${numberText(rowForSummary?.bright?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少亮片来源'} stage="bright" onClick={() => openRecords(null, 'bright')} />
<MetricCard label="报废总重" value={rowForSummary && (hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright')) ? `${numberText((rowForSummary.black.scrapWeight ?? 0) + (rowForSummary.bright.scrapWeight ?? 0))} kg` : '—'} note={hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright') ? `黑片 ${numberText(rowForSummary?.black?.scrapWeight)} kg · 亮片 ${numberText(rowForSummary?.bright?.scrapWeight)} kg` : '缺少阶段来源'} onClick={() => openRecords(null, 'black')} />
<MetricCard label="黑片合格率" value={rateText(visibleStageRate(rowForSummary, 'black'))} note={!currentMetricsData ? (queryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') ? hasValidRateDenominator(rowForSummary, 'black') ? `合格重量 ${numberText(rowForSummary?.black?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少黑片来源'} stage="black" onClick={() => openRecords(null, 'black')} />
<MetricCard label={rateBasis === 'original' ? '亮片合格率' : '亮片调整率'} value={rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))} note={!currentMetricsData ? (queryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'bright') ? hasValidRateDenominator(rowForSummary, 'bright') ? `合格重量 ${numberText(rowForSummary?.bright?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少亮片来源'} stage="bright" onClick={() => openRecords(null, 'bright')} />
<MetricCard label="报废总重" value={rowForSummary && (hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright')) ? `${numberText((rowForSummary.black.scrapWeight ?? 0) + (rowForSummary.bright.scrapWeight ?? 0))} kg` : '—'} note={!currentMetricsData ? (queryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright') ? `黑片 ${numberText(rowForSummary?.black?.scrapWeight)} kg · 亮片 ${numberText(rowForSummary?.bright?.scrapWeight)} kg` : '缺少阶段来源'} onClick={() => openRecords(null, 'black')} />
</section>
<div className="query-quality-summary" aria-label="数据覆盖摘要">
<span>{currentMetricsData ? <>来源覆盖 {currentMetricsData.coverage.sourceMonths.filter(item => item.blackRows > 0 || item.brightRows > 0).length} 个月 · 参与计算 {currentMetricsData.coverage.includedRows.toLocaleString('zh-CN')} / 原始 {currentMetricsData.coverage.rawRows.toLocaleString('zh-CN')} 行 · 未分类 {currentMetricsData.coverage.excludedBlankRows.toLocaleString('zh-CN')} 行({includeUnassigned ? '已包含' : '本次排除'})</> : queryBusy ? '正在更新来源覆盖…' : '来源覆盖暂不可用'}</span>
<Button type="link" size="small" disabled={!currentMetricsData} onClick={() => setBasisOpen(true)}>质量范围说明</Button>
</div>
{['department', 'group', 'product'].includes(page) && <>
{options?.projectGroupStatus === 'UNCONFIGURED' && <Alert showIcon type="info" message="项目组映射尚未配置" description="项目组与源 Excel 业务分组是不同维度。映射启用前,此处不会将业务分组冒充项目组,也不会提供项目组筛选。" />}
</>}
@@ -719,13 +733,15 @@ export default function QueryPage({ page, onUnauthorized }: {
<div className="section-heading-row">
<SectionHeading title={drilledProduct ? '产品月度质量数据' : page === 'overall' ? `${period === 'year' ? '年度月度' : period === 'quarter' ? '季度' : '月度'}汇总` : `${scopeName}质量汇总`} subtitle={drilledProduct ? `${year} 年 · ${drilledProduct} · 重量 / kg 合格率 / %` : '重量 / kg 合格率 / %'} />
<div className="table-tools">
<Input allowClear={!drilledProduct} disabled={Boolean(drilledProduct)} maxLength={view === 'product' ? 256 : undefined} prefix={<SearchOutlined />} placeholder={view === 'product' ? '输入关键词或完整产品名称' : `搜索${view === 'group' ? '业务分组' : '汇总对象'}`} value={drilledProduct || search} onChange={event => setSynchronizedSearch(event.target.value)} aria-label={view === 'product' ? '搜索产品名称并同步筛选指标和趋势' : '搜索汇总对象'} />
<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>
{drilledProduct && <Button onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回产品汇总</Button>}
</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
rows={drilledTrendData}
@@ -741,7 +757,7 @@ export default function QueryPage({ page, onUnauthorized }: {
onBasis={() => setBasisOpen(true)}
onDrilldown={() => undefined}
/>
) : queryPending ? <div className="loading-panel query-metrics-loading"><Spin />正在查询真实指标数据…</div> : visibleRows.length === 0 ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={currentMetricsError ? '查询失败,暂无可展示结果' : '当前条件下暂无数据'} /> : (
) : (
<MetricTable
rows={visibleRows}
view={view}
@@ -752,6 +768,7 @@ export default function QueryPage({ page, onUnauthorized }: {
rateBasis={rateBasis}
onDetail={openRecords}
onBasis={() => setBasisOpen(true)}
emptyText={queryBusy ? '正在更新数据…' : currentMetricsError ? '查询失败,暂无可展示结果' : '当前条件下暂无数据'}
onDrilldown={row => {
if (view === 'overall') setViewOverride('department');
else if (view === 'department' && row.department) { setDepartment([row.department]); setViewOverride('group'); }
@@ -767,7 +784,8 @@ export default function QueryPage({ page, onUnauthorized }: {
}}
/>
)}
<div className="table-footer"><span>{drilledProduct ? trendLoading && trendDataKey !== trendKey ? `${drilledProduct} · 正在查询月度数据` : `${drilledProduct} · 共 ${drilledTrendData.length} 个月` : page === 'overall' && period === 'year' ? `年度月份 12 行 · 已有数据 ${new Set((currentMetricsData?.trend || []).map(item => String(item.month))).size} 个月` : `共 ${visibleRows.length} 行`}</span></div>
</div></Spin>
<div className="table-footer"><span>{queryBusy ? '正在更新当前查询结果…' : drilledProduct ? trendLoading && trendDataKey !== trendKey ? `${drilledProduct} · 正在查询月度数据` : `${drilledProduct} · 共 ${drilledTrendData.length} 个月` : page === 'overall' && period === 'year' ? `年度月份 12 行 · 已有数据 ${new Set((currentMetricsData?.trend || []).map(item => String(item.month))).size} 个月` : `共 ${visibleRows.length} 行`}</span></div>
</section>
<div className="analysis-stack">
@@ -810,18 +828,16 @@ export default function QueryPage({ page, onUnauthorized }: {
</section>;
})}
</div>
<DefectParetoPanel key={defectQueryKey} releaseId={currentMetricsData?.release?.id} query={defectQueryParams} externalScrapWeight={blackDefectItems.find(item => item.name === '外废')?.weight} onUnauthorized={onUnauthorized} />
{currentMetricsData ? <DefectParetoPanel key={defectQueryKey} releaseId={currentMetricsData.release?.id} query={defectQueryParams} externalScrapWeight={blackDefectItems.find(item => item.name === '外废')?.weight} onUnauthorized={onUnauthorized} /> : <div className="defect-pareto-status">{queryBusy ? '正在更新不良数据…' : '不良数据暂不可用'}</div>}
</section>
</div>
</>
<M01Insights key={queryKey} query={queryParams} onUnauthorized={onUnauthorized} />
<div className="query-footer"><span>查询数据由服务端按当前数据返回</span><Button type="link" onClick={() => setBasisOpen(true)}>计算口径</Button></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>
<p className="basis-copy">正式指标按当前数据绑定的规则与筛选条件计算。综合合格率是黑片合格率与亮片合格率相乘的业务指标。以下公式及空值处理说明来自指标服务;缺少阶段来源时不展示对应率。</p>
<dl className="basis-details">
<dt>综合公式</dt><dd>{formulaText(compositeFormula)}</dd>
<dt>黑片公式</dt><dd>{formulaText(formulaDescriptions.blackRate)}</dd>
@@ -829,9 +845,11 @@ export default function QueryPage({ page, onUnauthorized }: {
<dt>统计范围</dt><dd>{year}年{period === 'month' ? ` ${MONTHS[month - 1]}` : period === 'quarter' ? ` 第${quarter}季度` : '度'} · {scopeName}</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>原始 {data?.coverage.rawRows ?? '—'} · 参与 {data?.coverage.includedRows ?? '—'} · 未分类排除 {data?.coverage.excludedBlankRows ?? '—'}</dd>
<dt>映射状态</dt><dd>未映射 {data?.coverage.unmappedRows ?? '—'} · 项目组配置未就绪 {data?.coverage.projectGroupUnconfiguredRows ?? '—'}</dd>
<dt>来源行覆盖</dt><dd>原始 {currentMetricsData?.coverage.rawRows ?? '—'} · 参与 {currentMetricsData?.coverage.includedRows ?? '—'} · 未分类行 {includeUnassigned ? '(已选择包含)' : '(本次排除)'} {currentMetricsData?.coverage.excludedBlankRows ?? '—'}</dd>
<dt>业务分类映射</dt><dd>未映射 {currentMetricsData?.coverage.unmappedRows ?? '—'} 行</dd>
<dt>项目组维度</dt><dd>{currentMetricsData?.coverage.projectGroupUnconfiguredRows ?? '—'} 行未配置项目组归属。该计数不等于排除行数;是否参与指标由当前筛选及规则决定。</dd>
</dl>
<details><summary>查看服务返回的公式原文</summary><pre>{JSON.stringify(formulaDescriptions, null, 2)}</pre></details>
</Modal>
<RecordsDrawer
@@ -1035,11 +1053,12 @@ function useCompactTable() {
}
function MetricTable({
rows, view, layoutView = view, pageSizeOverride, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown,
rows, view, layoutView = view, pageSizeOverride, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, emptyText = '当前条件下暂无数据',
}: {
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;
}) {
const compact = useCompactTable();
const blackDefects = fullFields ? defectsFor(rows, 'black') : [];
@@ -1094,7 +1113,7 @@ function MetricTable({
const scroll = { x: scrollWidth };
const displayColumns = compact ? columns.flatMap(column => 'children' in column && column.children ? column.children : [column]) : columns;
const pageRows = dataSource.slice((effectivePage - 1) * effectivePageSize, effectivePage * effectivePageSize);
return <div className="metric-table-scroll"><Table<MetricRow> size="small" bordered columns={displayColumns} dataSource={pageRows} pagination={false} scroll={scroll} rowKey="key" locale={{ emptyText: '当前条件下暂无数据' }} />
return <div className="metric-table-scroll"><Table<MetricRow> size="small" bordered columns={displayColumns} dataSource={pageRows} pagination={false} scroll={scroll} rowKey="key" locale={{ emptyText }} />
{pageSizeOverride == null && <MetricTablePagination current={currentPage} total={dataSource.length} pageSize={pageSize} onChange={(nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); }} />}
</div>;
}
+38 -12
View File
@@ -8,7 +8,9 @@
.analysis-simple-page .analysis-session-item{padding:14px 12px;gap:5px}
.analysis-simple-page .analysis-session-item small{font-size:11px}
.analysis-session-state{float:right;color:#1680c5;font-weight:500;margin-left:6px}
.analysis-simple-page .analysis-conversation{min-height:0;gap:26px;padding:30px max(24px,calc((100% - 850px)/2));scroll-behavior:smooth;overscroll-behavior:contain}
.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-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}
@@ -32,21 +34,32 @@
.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-process{border:1px solid #e5ebf3;border-radius:8px;background:#fafcfe;min-width:0}
.analysis-process-toggle{display:flex;align-items:center;gap:9px;padding:11px 13px;width:100%;border:0;background:transparent;color:#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:#7b899d}
.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-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-process-body li{padding:10px 0;border-top:1px solid #edf1f6}
.analysis-process-step{display:flex;align-items:center;gap:8px;font-size:12px;color:#63758b}
.analysis-process-step strong{color:#3e536e;font-weight:500}
.analysis-process-step>span:last-child{margin-left:auto;color:#8390a2;white-space:nowrap}
.analysis-process-body details{margin:7px 0 0 23px;color:#7b899c;font-size:12px}
.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-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 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 summary{cursor:pointer}
.analysis-process-body pre{margin:6px 0;white-space:pre-wrap;overflow-wrap:anywhere;font:12px/1.8 inherit;color:#5e7088}
.analysis-process-body li p,.analysis-process-current{font-size:12px;line-height:1.8;color:#7b899b;margin:5px 0 0 23px}
.analysis-process-current{margin:10px 0 0;color:#526b8a}
.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-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 .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-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}
@@ -70,3 +83,16 @@
@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(prefers-reduced-motion:reduce){.analysis-simple-page .analysis-conversation{scroll-behavior:auto}}
.analysis-event-stream { display: grid; gap: 6px; margin: 8px 0; }
.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::-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-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-event-tool.is-failed { border-left-color: #d66; }
+84
View File
@@ -41,3 +41,87 @@ export function settledAnalysisTurn(id: string, question: string, detail: Record
delete result.result;
return { ...result, id, question, status, result };
}
/** Durable SSE IDs are decimal database sequences, potentially larger than JS integers. */
export function acceptAnalysisEvent(id: string | undefined, cursor: string | undefined): boolean {
if (!id || !cursor) return true;
if (/^\d+$/.test(id) && /^\d+$/.test(cursor)) return BigInt(id) > BigInt(cursor);
return id !== cursor;
}
/** Providers may prefix streamed text with whitespace that the saved answer trims. */
export function duplicatesFinalAnalysisAnswer(segment: string, answer: string): boolean {
const text = segment.trimStart();
return Boolean(text.trim()) && answer.trimStart().startsWith(text);
}
/** Render a call once, updating its original row when the result arrives. */
export function compactAnalysisTimeline(entries: Record<string, unknown>[]): Record<string, unknown>[] {
const rows: Record<string, unknown>[] = [];
const calls = new Map<string, number>();
for (const entry of entries) {
if (entry.kind === 'assistant') { rows.push({ ...entry }); continue; }
if (!['tool_start', 'tool_result'].includes(String(entry.kind))) continue;
const id = typeof entry.toolCallId === 'string' ? entry.toolCallId : '';
const index = id ? calls.get(id) : undefined;
if (index === undefined) {
if (id) calls.set(id, rows.length);
rows.push({ ...entry, kind: 'tool', hasResult: entry.kind === 'tool_result' });
} else {
const prior = rows[index];
if (entry.kind === 'tool_result') rows[index] = { ...prior, ...entry, kind: 'tool', sequence: prior.sequence,
at: prior.at, finishedAt: entry.at, input: prior.input || entry.input, hasResult: true };
else if (!prior.input && entry.input) rows[index] = { ...prior, input: entry.input };
}
}
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 function partialAnalysisNotice(reason: unknown): string {
const value = String(reason || '');
if (value === 'mcp_error') return '部分数据查询未成功,已保留其余分析结果。可以重试或继续追问。';
if (value === 'length') return '回答达到输出长度上限,已保存现有内容。可以重试或继续追问。';
if (/timeout|超时/.test(value)) return '本轮分析达到处理时限,已保存现有结果。可以重试或继续追问。';
if (value === 'evidence_incomplete') return '所需数据尚未齐全,已展示现有结果。可以继续追问。';
return '本轮分析未完整结束,已保存现有结果。可以重试或继续追问。';
}
/** Old answers keep their original wording; surface their explicitly recorded scope limitation. */
export function hasUnreconciledEvidence(turn: Record<string, unknown>): boolean {
const record = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
const result = record(turn.result), plan = record(turn.plan || result.plan);
const entries = turn.timeline || result.timeline || plan.timeline;
const checks = new Map<string, string>();
if (Array.isArray(entries)) for (const item of entries) {
const event = record(item);
if (event.kind !== 'tool_result' || event.status !== 'completed') continue;
for (const [key, status] of Object.entries(record(event.evidenceChecks))) {
if (/^[a-f0-9]{16}$/.test(key) && typeof status === 'string' && ['unresolved', 'checked', 'expected'].includes(status)) checks.set(key, status);
}
}
if (checks.size) return [...checks.values()].includes('unresolved');
const text = [turn.answer, result.answer, ...(Array.isArray(entries) ? entries.map(item => record(item).text) : [])].filter(item => typeof item === 'string').join('\n');
return /未(?:与|和)[^。!?\n]{0,24}(?:对账|核对)|未(?:完全)?对账/.test(text);
}
/** A stopped turn may save its last pre-tool progress note; keep it in chronology,
* but do not repeat it as a final answer below later tool results. */
export function partialAnswerIsOnlyProgress(turn: Record<string, unknown>): boolean {
const record = (value: unknown): Record<string, unknown> => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
const result = record(turn.result), plan = record(turn.plan || result.plan);
if (String(turn.status || result.status).toUpperCase() !== 'PARTIAL') return false;
const answer = String(result.answer || turn.answer || '').trim();
const entries = turn.timeline || result.timeline || plan.timeline;
if (!answer || !Array.isArray(entries)) return false;
let lastAssistant = -1;
for (let index = entries.length - 1; index >= 0; index--) {
if (record(entries[index]).kind === 'assistant') { lastAssistant = index; break; }
}
if (lastAssistant < 0 || String(record(entries[lastAssistant]).text || '').trim() !== answer) return false;
return entries.slice(lastAssistant + 1).some(item => ['tool_start', 'tool_result'].includes(String(record(item).kind)));
}
+1 -1
View File
@@ -72,7 +72,7 @@ function deleteRanges(value: string, ranges: TextRange[]): string {
/** Remove internal release/story metadata while preserving business versions, values, and evidence IDs. */
export function sanitizeAnalysisDisplayText(value: string): string {
// Keep the useful status phrase while hiding the report's internal revision tag.
const withoutRevisionPhrase = value.replace(
const withoutRevisionPhrase = value.replace(/<tool_call\b[^>]*>[\s\S]*?(?:<\/tool_call>|$)/gi, '').replace(
/报告已更新为\s*(?:\*{1,2})?v\d+(?:\.\d+)*\s*复核版(?:\*{1,2})?/gi,
'报告已更新',
);
+22 -38
View File
@@ -1,3 +1,4 @@
import { consumeEventStream, type StreamEvent } from './eventStream';
import { publicErrorMessage } from './publicDataDisplay';
import type {
AuthUser,
@@ -18,7 +19,7 @@ export class ApiError extends Error {
details: unknown;
constructor(status: number, message: string, details?: unknown) {
super(publicErrorMessage(message));
super(publicErrorMessage(message, status));
this.name = 'ApiError';
this.status = status;
this.details = details;
@@ -27,6 +28,14 @@ export class ApiError extends Error {
let csrfToken: string | undefined;
async function fetchApi(path: string, init: RequestInit): Promise<Response> {
try { return await fetch(path, init); }
catch (error) {
if (init.signal?.aborted || (error instanceof DOMException && error.name === 'AbortError')) throw error;
throw new ApiError(0, '无法连接质量数据服务,请检查网络后重试;当前无法确认数据覆盖。');
}
}
async function readResponse<T>(response: Response): Promise<T> {
const raw = await response.text();
let payload: unknown;
@@ -51,13 +60,14 @@ async function readResponse<T>(response: Response): Promise<T> {
: `请求失败(${response.status})`;
throw new ApiError(response.status, message, payload);
}
if (typeof payload === 'string') throw new ApiError(response.status, '服务返回格式异常,请稍后重试。');
return payload as T;
}
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
const headers = new Headers(init.headers);
if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json');
const response = await fetch(path, {
const response = await fetchApi(path, {
...init,
headers,
credentials: 'same-origin',
@@ -67,7 +77,7 @@ async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
}
async function requestBlob(path: string, signal?: AbortSignal): Promise<{ blob: Blob; filename: string }> {
const response = await fetch(path, { credentials: 'same-origin', cache: 'no-store', signal });
const response = await fetchApi(path, { credentials: 'same-origin', cache: 'no-store', signal });
if (!response.ok) {
const raw = await response.text();
let payload: unknown = raw;
@@ -84,16 +94,12 @@ async function requestBlob(path: string, signal?: AbortSignal): Promise<{ blob:
return { blob: await response.blob(), filename };
}
export interface StreamEvent {
id?: string;
event: string;
data: unknown;
}
export type { StreamEvent } from './eventStream';
async function readEventStream(path: string, options: { signal?: AbortSignal; lastEventId?: string; onEvent: (event: StreamEvent) => void }): Promise<void> {
const headers = new Headers({ Accept: 'text/event-stream' });
if (options.lastEventId) headers.set('Last-Event-ID', options.lastEventId);
const response = await fetch(path, { headers, credentials: 'same-origin', cache: 'no-store', signal: options.signal });
const response = await fetchApi(path, { headers, credentials: 'same-origin', cache: 'no-store', signal: options.signal });
if (!response.ok) {
const raw = await response.text();
let payload: unknown = raw;
@@ -102,35 +108,7 @@ async function readEventStream(path: string, options: { signal?: AbortSignal; la
throw new ApiError(response.status, typeof body?.detail === 'string' ? body.detail : typeof body?.message === 'string' ? body.message : `事件流读取失败(${response.status})`, payload);
}
if (!response.body) throw new ApiError(response.status, '浏览器没有收到可读的分析事件流');
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
const dispatch = (frame: string) => {
if (!frame || frame.startsWith(':')) return;
let id: string | undefined;
let event = 'message';
const data: string[] = [];
for (const line of frame.split(/\r?\n/)) {
if (line.startsWith('id:')) id = line.slice(3).trim();
else if (line.startsWith('event:')) event = line.slice(6).trim() || 'message';
else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));
}
if (data.length) {
const raw = data.join('\n');
let value: unknown = raw;
try { value = JSON.parse(raw) as unknown; } catch { /* allow plain text event data */ }
options.onEvent({ ...(id ? { id } : {}), event, data: value });
}
};
while (true) {
const { done, value } = await reader.read();
buffer += decoder.decode(value, { stream: !done });
const frames = buffer.split(/\r?\n\r?\n/);
buffer = frames.pop() || '';
for (const frame of frames) dispatch(frame);
if (done) break;
}
if (buffer.trim()) dispatch(buffer);
await consumeEventStream(response.body, options.onEvent);
}
export async function refreshCsrf(): Promise<string> {
@@ -175,6 +153,9 @@ export const api = {
logout() {
return mutate<void>('/api/auth/logout');
},
changePassword(currentPassword: string, newPassword: string) {
return mutate<{ success: boolean }>('/api/auth/change-password', { currentPassword, newPassword });
},
options() {
return request<OptionsResponse>('/api/options');
},
@@ -402,6 +383,9 @@ export const api = {
deleteAnalysisSession(id: string) {
return mutate<{ deleted: boolean; sessionId: string }>(`/api/analysis/sessions/${encodeURIComponent(id)}`, undefined, 'DELETE');
},
renameAnalysisSession(id: string, title: string) {
return mutate<{ sessionId: string; title: string }>(`/api/analysis/sessions/${encodeURIComponent(id)}`, { title }, 'PATCH');
},
analysisSessionTurns(id: string) {
return request<{ items: Record<string, unknown>[] }>(`/api/analysis/sessions/${encodeURIComponent(id)}/turns`);
},
+42
View File
@@ -0,0 +1,42 @@
export interface StreamEvent {
id?: string;
event: string;
data: unknown;
}
export async function consumeEventStream(body: ReadableStream<Uint8Array>, onEvent: (event: StreamEvent) => void): Promise<void> {
const reader = body.getReader();
const decoder = new TextDecoder();
let buffer = '';
const dispatch = (frame: string) => {
if (!frame) return;
let id: string | undefined;
let event = 'message';
const data: string[] = [];
for (const line of frame.split(/\r?\n/)) {
if (line.startsWith('id:')) id = line.slice(3).trim();
else if (line.startsWith('event:')) event = line.slice(6).trim() || 'message';
else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''));
}
if (data.length) {
const raw = data.join('\n');
let value: unknown = raw;
try { value = JSON.parse(raw) as unknown; } catch {
if (/^[{[]/.test(raw.trim())) throw new Error('分析事件格式异常,需恢复连接');
}
onEvent({ ...(id ? { id } : {}), event, data: value });
}
};
try {
while (true) {
const { done, value } = await reader.read();
buffer += decoder.decode(value, { stream: !done });
const frames = buffer.split(/\r?\n\r?\n/);
buffer = frames.pop() || '';
for (const frame of frames) dispatch(frame);
if (done) break;
}
// SSE dispatch requires a blank-line delimiter. A cut-off final frame is
// replayed from the last durable event ID; EOF must not invent completion.
} finally { reader.releaseLock(); }
}
+1
View File
@@ -17,6 +17,7 @@ function QualityCenterApp() {
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('--blue', appearance.primary);
root.style.setProperty('--blue-dark', dark ? '#A9BDFF' : appearance.primary);
root.style.setProperty('--blue-soft', appearance.soft);
+21 -1
View File
@@ -7,8 +7,28 @@ export function publicJson(value: unknown): string | undefined {
return JSON.stringify(value, (key, child) => isInternalDataField(key) ? undefined : child, 2);
}
export function publicErrorMessage(message: string): string {
export function publicErrorMessage(message: string, status?: number): string {
if (status && [502, 503, 504].includes(status)) return `质量数据服务暂不可用(HTTP ${status}),请稍后重试;当前无法确认数据覆盖。`;
if (/<(?:!doctype|html|head|body|script|title|h1)\b/i.test(message)) return `服务返回异常响应${status ? `(HTTP ${status})` : ''},请稍后重试。`;
return message
.replace(/(?:数据|发布|规则|映射|目标|配置)版本(?:\s*[((]?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}[))]?)?/gi, '当前数据或配置')
.replace(/(?:releaseId|mappingVersionId|ruleVersionId|targetVersionId)\s*[:=:]?\s*[0-9a-f-]{36}/gi, '当前数据或配置');
}
/** Display translation only. The service remains the source of formula and null policies. */
export function readableMetricFormula(description: unknown): string {
if (typeof description !== 'string' || !description.trim()) return '当前指标服务未提供公式说明';
const names: Record<string, string> = {
blackRate: '黑片合格率', brightRate: '亮片合格率', brightRateWithoutHeadquartersScrap: '亮片调整率(去本部报废)',
compositeRate: '综合合格率', compositeRateWithoutHeadquartersScrap: '综合调整率',
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)
.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]}`);
}
+4
View File
@@ -1,5 +1,9 @@
.chart-container.chart-empty { display: none; }
.chart-container svg { display: block; }
.query-awaiting-data { pointer-events: none; }
.query-awaiting-data .metric-value { opacity: .5; }
.query-table-content { min-width: 0; }
.query-table-content[aria-busy="true"] { pointer-events: none; }
.source-records-drawer .ant-drawer-content,
.source-records-drawer .ant-drawer-header,
.source-records-drawer .ant-drawer-body { background: var(--surface, #fff); }
+6 -1
View File
@@ -28,7 +28,7 @@ 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: 11px; min-height: 34px; padding: 0 7px; border: 0; background: transparent; text-align: left; font-size: 19px; font-weight: 700; cursor: pointer; }
.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-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; }
@@ -44,6 +44,9 @@ button { color: inherit; }
.nav-item.active .anticon { color: var(--blue); }
.nav-group-tail { padding-top: 2px; }
.user-block { display: flex; min-height: 52px; align-items: center; gap: 9px; padding: 9px 3px 0; border-top: 1px solid var(--line); }
.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; }
.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; }
@@ -610,3 +613,5 @@ body { background: var(--background); }
.query-toolbar-tail { flex: 1 0 100%; }
.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; }
+1
View File
@@ -159,6 +159,7 @@ export interface AuthUser {
roles: string[];
departments: string[];
groups: string[];
forcePasswordChange?: boolean;
}
export interface Collection<T = Record<string, unknown>> {