修复:快照合并分析图并支持导出订单对应表

快照将不良构成与柏拉图合并为一个选项,完整保留页面容器,黑片和亮片继续并排展示两张分析图;迁移旧快照选项并等待组合图的数据准备完成。

销售订单类型对应表支持下载当前生效版本的完整Excel,订单号按文本写入,保留前导零,沿用管理员角色与来源字段权限。导出开始时固定版本,使用滚动工作簿限制内存。

菜单、页面及快照标题统一改为黑片数据和亮片数据。

验证:11项前端检查、8项后端单元测试通过;157698条实际对应关系与数据库逐条一致,重新导入预览零变更;黑片完整快照和亮片单模块快照均通过视觉检查。
This commit is contained in:
2026-11-04 09:06:07 +08:00
parent 80cd9e79eb
commit 147b56d0fd
11 changed files with 133 additions and 20 deletions
+3 -3
View File
@@ -40,7 +40,7 @@ import { CachedWorkspacePages, preloadWorkspacePage, type WorkspaceNavigation }
export type PageKey = 'overall' | 'department' | 'group' | 'product' | 'blackProduct' | 'brightProduct' | 'basis' | 'analysis' | 'sources' | 'imports' | 'rules' | 'mappings' | 'masterData' | 'tasks' | 'access';
const pageNames: Record<PageKey, string> = {
overall: '总体合格率', department: '产业部', group: '产业部-业务分组', product: '产品汇总', blackProduct: '黑片汇总', brightProduct: '亮片汇总',
overall: '总体合格率', department: '产业部', group: '产业部-业务分组', product: '产品汇总', blackProduct: '黑片数据', brightProduct: '亮片数据',
basis: '数据与计算依据', analysis: '智能分析', sources: '数据接入', imports: '导入与校验',
rules: '指标与目标', mappings: '对应关系', masterData: '基础数据', tasks: '任务与监控', access: '权限与审计',
};
@@ -68,8 +68,8 @@ const navGroups = [
['overall', '总体合格率', AppstoreOutlined],
['department', '产业部', ApartmentOutlined],
['product', '产品汇总', DatabaseOutlined],
['blackProduct', '黑片汇总', DatabaseOutlined],
['brightProduct', '亮片汇总', DatabaseOutlined],
['blackProduct', '黑片数据', DatabaseOutlined],
['brightProduct', '亮片数据', DatabaseOutlined],
] as const,
},
{
+2 -2
View File
@@ -827,13 +827,13 @@ export default function QueryPage({ page, onUnauthorized }: {
</SmoothTableFrame>
</QueryTablePanel>
<section className="panel section-panel defects-panel" ref={defectsSection} aria-busy={defectsRefreshing} style={{ minHeight: queryBusy && trendAnchorTop.current != null ? defectsHeight.current : undefined }}>
<section className="panel section-panel defects-panel" data-snapshot-module="defects" ref={defectsSection} aria-busy={defectsRefreshing} style={{ minHeight: queryBusy && trendAnchorTop.current != null ? defectsHeight.current : undefined }}>
<div className="section-heading-row">
<SectionHeading title="不良具体构成" />
{defectsRefreshing && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}
</div>
{trendObjectMetricsError && <Alert showIcon type="warning" message="当前趋势对象的不良数据读取失败" description={trendObjectMetricsError} />}
<div className="defect-stage-grid" data-snapshot-module="defects" inert={!activeDefectData}>
<div className="defect-stage-grid" inert={!activeDefectData}>
{(['black', 'bright'] as const).map(stage => {
const items = stage === 'black' ? blackDefectItems : brightDefectItems;
return <section className="defect-stage-column" key={stage} aria-label={`${stage === 'black' ? '黑片' : '亮片'}不良构成`}>
+12 -3
View File
@@ -1,12 +1,13 @@
import { useEffect,useRef,useState } from 'react';
import { Alert,App,Button,Modal,Select,Space,Table } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { DownloadOutlined,UploadOutlined } from '@ant-design/icons';
import { api } from './api';
import type { SalesOrderTypePreview,SalesOrderTypeStatus,SalesOrderTypeVersion } from './salesOrderTypes';
export function SalesOrderTypeSettings({onUnauthorized}:{onUnauthorized:(error:unknown)=>boolean}) {
const {message,modal}=App.useApp();
const [status,setStatus]=useState<SalesOrderTypeStatus>();
const [exporting,setExporting]=useState(false);const exportController=useRef<AbortController|undefined>(undefined);
const [error,setError]=useState('');const [busy,setBusy]=useState(false);
const [open,setOpen]=useState(false);const [history,setHistory]=useState(false);
const [file,setFile]=useState<File>();const [mode,setMode]=useState<'MERGE'|'REPLACE'>('MERGE');
@@ -14,7 +15,7 @@ export function SalesOrderTypeSettings({onUnauthorized}:{onUnauthorized:(error:u
const input=useRef<HTMLInputElement>(null);const generation=useRef(0);
const failure=(e:unknown)=>{if(!onUnauthorized(e))setError(e instanceof Error?e.message:'操作失败');};
const load=()=>api.salesOrderTypeStatus().then(setStatus);
useEffect(()=>{let alive=true;api.salesOrderTypeStatus().then(value=>{if(alive)setStatus(value);}).catch(e=>{if(alive&&!onUnauthorized(e))setError(e instanceof Error?e.message:'对应表读取失败');});return()=>{alive=false;generation.current++;};},[onUnauthorized]);
useEffect(()=>{let alive=true;api.salesOrderTypeStatus().then(value=>{if(alive)setStatus(value);}).catch(e=>{if(alive&&!onUnauthorized(e))setError(e instanceof Error?e.message:'对应表读取失败');});return()=>{alive=false;generation.current++;const exporting=exportController.current;exportController.current=undefined;exporting?.abort();};},[onUnauthorized]);
const current=status?.versions.find(version=>version.id===status.versionId);
const inspect=async()=>{
if(!file)return;const revision=++generation.current;setBusy(true);setError('');setPreview(undefined);
@@ -26,9 +27,17 @@ export function SalesOrderTypeSettings({onUnauthorized}:{onUnauthorized:(error:u
try{await api.importSalesOrderTypes(file,mode,preview.expectedVersion,preview.sha256);await load();setOpen(false);setPreview(undefined);message.success('销售订单类型对应表已更新');}
catch(e){failure(e);setPreview(undefined);}finally{setBusy(false);}
};
const exportFile=async()=>{
if(exporting)return;
const controller=new AbortController();exportController.current=controller;setExporting(true);setError('');
try{
const {blob,filename}=await api.exportSalesOrderTypes(controller.signal);if(controller.signal.aborted)return;
const url=URL.createObjectURL(blob),link=document.createElement('a');link.href=url;link.download=filename;document.body.append(link);link.click();link.remove();window.setTimeout(()=>URL.revokeObjectURL(url),1000);message.success('对应表已开始下载');
}catch(e){if(!controller.signal.aborted)failure(e);}finally{if(exportController.current===controller){exportController.current=undefined;setExporting(false);}}
};
const restore=(version:SalesOrderTypeVersion)=>modal.confirm({title:'恢复此销售订单对应表?',content:'历史质量数据的后续查询将采用此版本的对应关系。',okText:'恢复',onOk:async()=>{setBusy(true);try{await api.activateSalesOrderTypes(version.id,status?.versionId||'');await load();setHistory(false);message.success('对应表已恢复');}catch(e){failure(e);throw e;}finally{setBusy(false);}}});
return <section className="sales-order-type-settings" style={{marginTop:24}}>
<div className="section-heading-row"><strong>销售订单类型对应</strong><Space><Button size="small" disabled={busy||!status?.versions.length} onClick={()=>setHistory(true)}>历史版本</Button><Button size="small" icon={<UploadOutlined/>} disabled={busy} onClick={()=>{setFile(undefined);setPreview(undefined);setError('');setOpen(true);}}>导入对应表</Button></Space></div>
<div className="section-heading-row"><strong>销售订单类型对应</strong><Space><Button size="small" icon={<DownloadOutlined/>} loading={exporting} disabled={busy||!status?.versionId} onClick={()=>void exportFile()}>导出对应表</Button><Button size="small" disabled={busy||!status?.versions.length} onClick={()=>setHistory(true)}>历史版本</Button><Button size="small" icon={<UploadOutlined/>} disabled={busy} onClick={()=>{setFile(undefined);setPreview(undefined);setError('');setOpen(true);}}>导入对应表</Button></Space></div>
<p>{current?`${current.rowCount.toLocaleString('zh-CN')} 个订单 · ${current.sourceFile}`:'尚未导入销售订单类型对应表'}</p>
{error&&!open&&<Alert showIcon type="error" message={error}/>}
<Modal open={open} title="导入销售订单类型对应表" onCancel={()=>{if(!busy){generation.current++;setOpen(false);}}} maskClosable={!busy} closable={!busy} footer={<Space><Button disabled={busy} onClick={()=>setOpen(false)}>取消</Button>{preview?<Button type="primary" loading={busy} onClick={()=>void commit()}>确认导入</Button>:<Button type="primary" loading={busy} disabled={!file} onClick={()=>void inspect()}>预览</Button>}</Space>}>
+4 -4
View File
@@ -105,7 +105,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
const formulaKey=stage==='black'?'blackRate':rateBasis==='original'?'brightRate':'brightRateWithoutHeadquartersScrap';
return <div className="query-page stage-product-page">
{supportError&&<Alert showIcon type="error" message="查询条件读取失败" description={supportError} action={<Button onClick={()=>void loadSupport()}>重试</Button>}/>}
<section className="query-toolbar panel" data-snapshot-module="filters" aria-label={`${label}汇总条件`}>
<section className="query-toolbar panel" data-snapshot-module="filters" aria-label={`${label}数据条件`}>
<Segmented aria-label="统计周期" value={period} options={[{label:'年度',value:'year'},{label:'季度',value:'quarter'},{label:'月度',value:'month'}]} onChange={v=>{automaticPeriod.current=false;setPeriod(v as PeriodKind);}}/>
<div role="group" className="query-field query-period-field query-period-year"><span>年份</span><Select aria-label="年份" value={year} onChange={v=>{automaticPeriod.current=false;setYear(v);}} options={(options?.years?.length?options.years:[year]).map(v=>({label:`${v}年`,value:v}))}/></div>
{period==='month'&&<div role="group" className="query-field query-period-field query-period-month"><span>月份</span><Select aria-label="月份" value={month} onChange={v=>{automaticPeriod.current=false;setMonth(v);}} options={Array.from({length:12},(_,i)=>({label:`${String(i+1).padStart(2,'0')}月`,value:i+1}))}/></div>}
@@ -117,7 +117,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
<Button type="text" size="small" icon={moreFiltersOpen?<UpOutlined/>:<DownOutlined/>} aria-expanded={moreFiltersOpen} aria-controls={`stage-more-filters-${stage}`} onClick={()=>setMoreFiltersOpen(open=>!open)}>更多筛选{moreFilterCount?`(已选 ${moreFilterCount} 项)`:''}</Button>
{moreFilterCount>0&&<Button type="link" size="small" onClick={()=>{setProjectGroup([]);setSourceFilters([]);setExtraFilters({});}}>清除</Button>}
</div>
<div className="query-toolbar-tail"><span className={`query-status ${queryBusy?'busy':queryFailed?'failed':''}`}><i/>{queryBusy?'正在查询':queryFailed?'查询失败':'查询完成'}</span><QuerySnapshotButton title={`${label}汇总`} queryKey={JSON.stringify([draft,trendMode,trendObject,trendGranularity,rateBasis,fullFields,defectDisplay,revision])} disabled={queryBusy || !current} onUnauthorized={onUnauthorized} /><Button type="default" onClick={reset}>重置</Button></div>
<div className="query-toolbar-tail"><span className={`query-status ${queryBusy?'busy':queryFailed?'failed':''}`}><i/>{queryBusy?'正在查询':queryFailed?'查询失败':'查询完成'}</span><QuerySnapshotButton title={`${label}数据`} queryKey={JSON.stringify([draft,trendMode,trendObject,trendGranularity,rateBasis,fullFields,defectDisplay,revision])} disabled={queryBusy || !current} onUnauthorized={onUnauthorized} /><Button type="default" onClick={reset}>重置</Button></div>
{moreFiltersOpen&&<div className="query-extra-fields" id={`stage-more-filters-${stage}`}>
{extraFields.map(field=><SalesOrderTypeSelect key={field.key} field={field} filters={extraFilters} releaseId={draft.releaseId} stage={stage} onUnauthorized={onUnauthorized} onChange={setExtraFilters}/>)}
{options?.projectGroupStatus==='READY'&&select('项目组',projectGroup,options.projectGroups||[],setProjectGroup,true)}
@@ -159,10 +159,10 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
onDrilldown={row=>{if(drilledProduct)return;const selected=row.product||'__UNASSIGNED__';drillParentSearch.current=appliedSearch;setDrilledProduct(selected);setTrendGranularity('month');setTrendMode('production');}}/>
</SmoothTableFrame>
</QueryTablePanel>
<section className="panel section-panel defects-panel" aria-busy={loading||!current}>
<section className="panel section-panel defects-panel" data-snapshot-module="defects" aria-busy={loading||!current}>
<div className="section-heading-row"><SectionHeading title="不良具体构成"/></div>
<div className="stage-defect-comparison">
<section className="defect-stage-column" data-snapshot-module="defects" inert={!current||loading} aria-label={`${label}不良构成`}>
<section className="defect-stage-column" inert={!current||loading} aria-label={`${label}不良构成`}>
<h3 className={`defect-stage-title ${stage}`}><i/>{label}</h3>
{displayed?.data.defects[stage]?.length ? <DefectBreakdown items={displayed.data.defects[stage]} stage={stage} totalWeight={summary?.totalWeight} maximum={Math.max(0,...displayed.data.defects[stage].map(item=>item.weight||0))} onDetail={()=>openDetail(null,stage)}/> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={loading?'正在查询不良数据…':'当前条件下暂无不良分类数据'}/>}
</section>
+1
View File
@@ -206,6 +206,7 @@ async function mutateForm<T>(path: string, body: FormData): Promise<T> {
}
export const api = {
exportSalesOrderTypes(signal?:AbortSignal) { return requestBlob('/api/sales-order-types/export',signal); },
salesOrderTypeStatus() { return request<SalesOrderTypeStatus>('/api/sales-order-types'); },
async salesOrderTypePreview(file:File,mode:string) {
const body=new FormData();body.append('file',file);body.append('mode',mode);
-1
View File
@@ -7,5 +7,4 @@
.query-snapshot-heading span { color:var(--ink-muted); font-size:12px; }
.query-snapshot-capture > * { flex-shrink:0; }
.query-snapshot-capture .query-snapshot-filter-summary { width:100%; flex-basis:100%; color:var(--ink); white-space:normal; overflow-wrap:anywhere; }
.query-snapshot-capture .query-snapshot-defect-module { background:var(--surface); border:1px solid var(--line); padding:16px; border-radius:var(--panel-radius,4px); }
.query-snapshot-capture :is(.ant-btn,.object-drilldown,.table-value,.header-link) { cursor:default; }
+6 -6
View File
@@ -1,14 +1,15 @@
export const QUERY_SNAPSHOT_MODULES = [
{ key: 'filters', label: '查询条件' }, { key: 'metrics', label: '指标卡片' },
{ key: 'trend', label: '变化趋势' }, { key: 'table', label: '汇总表' },
{ key: 'defects', label: '不良构成' }, { key: 'pareto', label: '细分缺陷柏拉图' },
{ key: 'defects', label: '不良构成与柏拉图' },
] as const;
export type QuerySnapshotModule = typeof QUERY_SNAPSHOT_MODULES[number]['key'];
const KEYS = new Set<string>(QUERY_SNAPSHOT_MODULES.map(module => module.key));
export function parseSnapshotModules(raw: unknown): QuerySnapshotModule[] {
if (!Array.isArray(raw)) return QUERY_SNAPSHOT_MODULES.map(module => module.key);
return QUERY_SNAPSHOT_MODULES.filter(module => raw.includes(module.key) && KEYS.has(module.key)).map(module => module.key);
const migrated = raw.map(key => key === 'pareto' ? 'defects' : key);
return QUERY_SNAPSHOT_MODULES.filter(module => migrated.includes(module.key) && KEYS.has(module.key)).map(module => module.key);
}
export function snapshotImageSize(width: number, height: number) {
@@ -48,16 +49,16 @@ export async function captureQuerySnapshot(root: HTMLElement, selected: QuerySna
if (!selected.length) throw new Error('请至少选择一个模块');
const check = () => { if (cancelled() || !root.isConnected || !root.offsetWidth) throw new Error('查询页面已变化,请重新生成快照'); };
check();
root.dispatchEvent(new CustomEvent('quality:query-snapshot', { detail: { modules: selected } }));
root.dispatchEvent(new CustomEvent('quality:query-snapshot', { detail: { modules: selected.includes('defects') ? [...selected, 'pareto'] : selected } }));
const modules = snapshotModuleElements(root, selected);
progress('正在等待所选模块加载完成…');
const started = performance.now();
let previous = '', stableSince = performance.now();
while (true) {
check();
const failed = modules.find(({ node }) => node.dataset.snapshotReady === 'error');
const failed = modules.find(({ node }) => node.dataset.snapshotReady === 'error' || node.querySelector('[data-snapshot-ready="error"]'));
if (failed) throw new Error(`“${failed.label}”读取失败,请重试后生成快照`);
const busy = modules.some(({ node }) => node.dataset.snapshotReady === 'false' || node.matches('[aria-busy="true"],[inert]') || node.querySelector('[aria-busy="true"],[inert]'));
const busy = modules.some(({ node }) => node.dataset.snapshotReady === 'false' || node.matches('[aria-busy="true"],[inert]') || node.querySelector('[aria-busy="true"],[inert],[data-snapshot-ready="false"]'));
const signature = modules.map(({ node }) => node.innerHTML).join('');
if (signature !== previous || busy) { previous = signature; stableSince = performance.now(); }
if (!busy && performance.now() - stableSince >= 250) break;
@@ -108,7 +109,6 @@ export async function captureQuerySnapshot(root: HTMLElement, selected: QuerySna
}
}
clone.querySelectorAll('.query-snapshot-controls,.query-toolbar-tail,.query-status,.query-more-toggle,.query-export-button,.ant-select-dropdown,.ant-table-filter-trigger,.ant-tooltip,.mobile-scroll-hint').forEach(element => element.remove());
if (key === 'defects' || key === 'pareto') clone.classList.add('query-snapshot-defect-module');
frame.append(clone);
}
root.append(frame);