Files
quality_analyse/web/src/ProductDrilldownDrawer.tsx
T
lyun ff7bbe3e46 同步:完善质量分析工作台并更新主题字体
同步已上线的智能分析执行协议、来源查询、图表报告与管理页面配套代码。
补齐数据库迁移、运行依赖和回归测试,保留原有指标计算口径。
统一午夜黑及其他主题的控件细节、中文和业务数字字体。
排除本地业务数据、凭据、预览、发布与验收产物。

验证:生产构建通过,320项前端回归通过;本轮仅同步Git,不再次部署。
2026-10-30 22:40:58 +08:00

100 lines
8.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useState } from 'react';
import { Alert, Button, Drawer, Empty, Segmented, Spin } from 'antd';
import { api } from './api';
import { AnalysisVisuals } from './AnalysisVisuals';
import { QualityTable } from './QualityTable';
import { authorizeAnalysisSnapshot, reportSnapshotIdentity } from './analysisSnapshot';
import { productDrilldownQuery, productTrendVisual, resolveProductDrilldown, type ProductDrilldownBinding, type ProductDrilldownView } from './analysisProductDrilldown';
import { publicJson } from './publicDataDisplay';
import type { AnalysisVisual } from './analysisVisualsModel';
import type { FocusProductRow } from './analysisReportModel';
import type { FineDefectTopResponse, RecordsResponse, Stage } from './types';
import './analysis-product-drilldown.css';
export interface ProductDrilldownSelection {
binding: ProductDrilldownBinding;
row: FocusProductRow;
view: ProductDrilldownView;
trigger: HTMLElement;
}
type Loaded = { kind: 'defects'; data: FineDefectTopResponse } | { kind: 'trend'; visuals: AnalysisVisual[] } | { kind: 'records'; data: RecordsResponse };
const titles = { defects: '看缺陷', trend: '看趋势', records: '看来源明细' };
const numberText = (value: number | null) => value === null ? '—' : value.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
/** Keeps the report mounted and its scroll position intact while querying the
* clicked row's immutable filters through the existing read-only APIs. */
export function AnalysisProductDrilldown({ turn, selection, onClose }: { turn: Record<string, unknown>; selection: ProductDrilldownSelection; onClose: () => void }) {
const { binding } = selection;
const [open, setOpen] = useState(true);
const [view, setView] = useState(selection.view);
const [stage, setStage] = useState<Stage>(binding.stages[0]);
const [periodIndex, setPeriodIndex] = useState(0);
const [page, setPage] = useState(1);
const [revision, setRevision] = useState(0);
const [loaded, setLoaded] = useState<Loaded | null>(null);
const [error, setError] = useState('');
const [loading, setLoading] = useState(true);
useEffect(() => {
if (!open) return;
const controller = new AbortController();
setLoading(true); setLoaded(null); setError('');
const load = async (): Promise<Loaded> => {
// Permission and stored-answer changes are checked before every request,
// including retries and paging; the backend also enforces current access.
const snapshot = await api.analysisTurnSnapshot(binding.turnId);
if (!['COMPLETED', 'PARTIAL', 'CANCELLED'].includes(String(snapshot.status || '').toUpperCase()) || reportSnapshotIdentity(snapshot) !== reportSnapshotIdentity(turn)) throw new Error('分析结果或访问权限已变化,请重新打开本轮分析。');
if (controller.signal.aborted) throw new DOMException('Aborted', 'AbortError');
const current = resolveProductDrilldown(snapshot, selection.row);
if (!current.binding || JSON.stringify(current.binding) !== JSON.stringify(binding)) throw new Error('本条查询范围已变化,请关闭后重新打开。');
const query = productDrilldownQuery(binding, binding.periods[periodIndex].period);
if (view === 'records') return { kind: 'records', data: await api.records({ ...query, stage, page, pageSize: 25 }, controller.signal) };
if (view === 'defects') {
const { view: _view, trendGranularity: _granularity, ...filters } = query;
const data = await api.fineDefectTop({ ...filters, stage, mode: 'top', dimension: 'defect', limit: 100 }, controller.signal);
if (data.releaseId !== binding.query.releaseId) throw new Error('查询返回的数据版本已变化,请重新打开本轮分析。');
return { kind: 'defects', data };
}
const snapshots = await Promise.all(binding.periods.map(period => api.metrics(productDrilldownQuery(binding, period.period), controller.signal)));
return { kind: 'trend', visuals: productTrendVisual(binding, snapshots) };
};
load().then(value => { if (!controller.signal.aborted) setLoaded(value); })
.catch(value => { if (!controller.signal.aborted) setError(value instanceof Error ? value.message : '读取失败,请重试。'); })
.finally(() => { if (!controller.signal.aborted) setLoading(false); });
return () => controller.abort();
}, [open, view, stage, periodIndex, page, revision, binding, turn, selection.row]);
const restoreFocus = (visible: boolean) => {
if (visible) return;
if (selection.trigger.isConnected) selection.trigger.focus({ preventScroll: true });
onClose();
};
const sourceColumns = [
{ title: '来源文件', dataIndex: 'sourceFile', width: 220 },
{ title: '工作表', dataIndex: 'sheet', width: 130 },
{ title: '原始行号', dataIndex: 'rowNumber', width: 90, align: 'center' as const },
{ title: '产业部', dataIndex: 'department', width: 150 },
{ title: '业务分组', dataIndex: 'group', width: 170 },
{ title: '原始字段', key: 'raw', width: 220, render: (_: unknown, row: RecordsResponse['rows'][number]) => <details className="analysis-product-source-row"><summary>查看原始字段</summary><dl>{Object.entries(JSON.parse(publicJson(row.raw || {}) || '{}') as Record<string, unknown>).map(([name, value]) => <div key={name}><dt>{name}</dt><dd>{value === null ? '—' : typeof value === 'object' ? JSON.stringify(value) : String(value)}</dd></div>)}</dl></details> },
];
return <Drawer className="analysis-product-drawer" title={binding.product} open={open} onClose={() => setOpen(false)} afterOpenChange={restoreFocus} width="min(1080px, 100vw)" destroyOnHidden>
<div className="analysis-product-controls">
<Segmented aria-label="产品下钻内容" value={view} options={(Object.keys(titles) as ProductDrilldownView[]).map(value => ({ label: titles[value], value }))} onChange={value => { setView(value as ProductDrilldownView); setPage(1); }} />
{view !== 'trend' && binding.stages.length > 1 && <Segmented aria-label="下钻阶段" value={stage} options={binding.stages.map(value => ({ label: value === 'black' ? '黑片' : '亮片', value }))} onChange={value => { setStage(value as Stage); setPage(1); }} />}
{view !== 'trend' && binding.periods.length > 1 && <Segmented aria-label="下钻期间" value={periodIndex} options={binding.periods.map((period, index) => ({ label: period.label, value: index }))} onChange={value => { setPeriodIndex(Number(value)); setPage(1); }} />}
</div>
{(view === 'trend' || binding.periods.length === 1 || binding.stages.length === 1) && <p className="analysis-product-context">{view === 'trend' ? [...binding.periods].reverse().map(period => period.label).join(' → ') : binding.periods.length === 1 ? binding.periods[0].label : ''}{binding.stages.length === 1 ? `${binding.periods.length === 1 || view === 'trend' ? ' · ' : ''}${binding.stages[0] === 'black' ? '黑片' : '亮片'}` : ''}</p>}
{error ? <Alert type="error" showIcon message="下钻加载失败" description={error} action={<Button size="small" onClick={() => setRevision(value => value + 1)}>重试</Button>} />
: loading ? <div className="analysis-product-loading" role="status"><Spin />正在读取{titles[view].slice(1)}…</div>
: loaded?.kind === 'trend' ? loaded.visuals.length ? <AnalysisVisuals visuals={loaded.visuals} embedded visualState="ready" beforeExport={() => authorizeAnalysisSnapshot(turn)} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="原分析期间内没有可用趋势数据" />
: loaded?.kind === 'defects' ? <>
<p className="analysis-product-context">来源细分重量(kg),用于缺陷核查。</p>
{loaded.data.sourceRows > 0 && loaded.data.coverage?.available !== false && loaded.data.rows.length ? <QualityTable rowKey="key" dataSource={loaded.data.rows} pagination={false} columns={[
{ title: '具体缺陷', dataIndex: 'label' }, { title: '报废类别', dataIndex: 'category', width: 150 },
{ title: '来源重量(kg)', dataIndex: 'weight', align: 'right', width: 170, render: numberText },
]} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="原分析范围内没有可用的细分缺陷数据" />}
{loaded.data.coverage?.categories?.some(category => category.reconciliationStatus !== 'RECONCILED') && <p className="analysis-product-context">部分来源细分尚不能与正式报废重量核对一致,不能据此计算总体贡献。</p>}
</> : loaded?.kind === 'records' ? <QualityTable rowKey="id" dataSource={loaded.data.rows} columns={sourceColumns} scroll={{ x: 1050 }} locale={{ emptyText: '原分析范围内没有来源记录' }} pagination={{ current: page, pageSize: 25, total: loaded.data.total, showSizeChanger: false, showTotal: total => `共 ${total} 条`, onChange: next => setPage(next) }} /> : null}
</Drawer>;
}