优化:查询页面平滑切换与默认月份高亮

This commit is contained in:
2026-11-01 14:49:37 +08:00
parent d89bd2e451
commit 19bd9b0122
14 changed files with 450 additions and 126 deletions
+16
View File
@@ -63,3 +63,19 @@
- 未选中月份保色 50%,替代原来的 28%;既有 340 毫秒过渡及再次点击取消选择保持。 - 未选中月份保色 50%,替代原来的 28%;既有 340 毫秒过渡及再次点击取消选择保持。
- 六主题共用 web/src/trendBarPalette.ts;其他浅色主题沿用各自蓝色方向,午夜黑同步增强对比度。 - 六主题共用 web/src/trendBarPalette.ts;其他浅色主题沿用各自蓝色方向,午夜黑同步增强对比度。
- 方案已获用户明确发布授权。候选预览控制栏和其他深度候选不进入正式页面。 - 方案已获用户明确发布授权。候选预览控制栏和其他深度候选不进入正式页面。
## 2026-11-01:查询结果连续更新与阅读顺序
- 按用户要求调整为:指标卡、趋势图、汇总表、不良具体构成;总体、产业部、业务分组、产品、黑片和亮片查询保持一致。
- 查询期间保留最后一次成功的卡片数据和表格及其期间、视图信息;旧结果暂时禁止打开明细及导出,新响应到达后恢复操作。
- 卡片和已存在的表格单元格数字、表格高度采用 520 毫秒连续过渡;减少动态效果设置下直接更新。
- Excel 始终使用最终服务端数值,不导出动画中的中间值。六主题逐帧检查、黑片与亮片实际页面检查及 42 项相关检查通过;当前仅本地修改,待用户发布。
## 2026-11-01:默认可用月份与页面切换(本地)
- 无显式查询期间的新页面默认进入月度:优先上个月;上个月未出现在已发布月份列表时,仅回退到上上个月。重置和切回月度采用同一规则。
- 复用 `/api/options` 的 `periods` / `latestDataPeriod`,不额外拉取完整报表判断。手动选择、分享链接、已缓存查询期间不被自动覆盖。
- 不同页面之间采用 280ms 新旧内容交叉淡化,取消整页位移,顶部和侧栏保持稳定。目标页面先提交内容及滚动位置,再交接画面;首次加载等待最多 900ms,内容稳定 32ms 后提前开始。连续导航立即打断上一次切换,返回保留筛选及滚动位置。减少动态效果或浏览器不支持时直接切换。
- 六个查询页默认月份、六主题切换、手动选择的慢加载保护、显式年月和返回时的筛选/滚动位置均已在本地验证。页面转场补充快速连续点击、取消等待及不可见控件保护验证,53 项相关检查通过,尚未发布。
- 黑片与亮片页移除指标卡下方的来源统计与计算口径整行,回收空隙;计算说明仍可从指标卡或表头查看。趋势图关联已生效的月份/季度,默认月份及查询后同步选中加深,年度取消月份高亮。六主题选中效果已检查。
- 2026-11-01 发布前生产构建与 57 项相关检查通过;此次仅更新前端,不修改计算逻辑或业务数据。
+26 -7
View File
@@ -1,3 +1,5 @@
import { flushSync } from 'react-dom';
import { createWorkspaceTransition, waitForWorkspaceContent } from './workspaceTransition';
import { forwardRef, lazy, Suspense, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react'; import { forwardRef, lazy, Suspense, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react';
import { Alert, Button, Spin } from 'antd'; import { Alert, Button, Spin } from 'antd';
import { api } from './api'; import { api } from './api';
@@ -22,12 +24,20 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
page: PageKey; user: AuthUser; onPageChange: (page: PageKey) => void; onUserChange: (user: AuthUser) => void; onUnauthorized: (error: unknown) => boolean; page: PageKey; user: AuthUser; onPageChange: (page: PageKey) => void; onUserChange: (user: AuthUser) => void; onUnauthorized: (error: unknown) => boolean;
}>(function CachedWorkspacePages({ page, user, onPageChange, onUserChange, onUnauthorized }, ref) { }>(function CachedWorkspacePages({ page, user, onPageChange, onUserChange, onUnauthorized }, ref) {
const entries = useRef(new Map<PageKey, Entry>([[page, { initialSearch: location.search, search: location.search, key: 0, scroll: 0 }]])); const entries = useRef(new Map<PageKey, Entry>([[page, { initialSearch: location.search, search: location.search, key: 0, scroll: 0 }]]));
const requested = useRef(page);
const current = useRef(page), generation = useRef(0), key = useRef(0); const current = useRef(page), generation = useRef(0), key = useRef(0);
const revisions = useRef<{ authRevision: string; dataRevision: string } | null>(null); const revisions = useRef<{ authRevision: string; dataRevision: string } | null>(null);
const validation = useRef<Promise<boolean> | null>(null); const validation = useRef<Promise<boolean> | null>(null);
const [refreshKey, setRefreshKey] = useState(0), [, render] = useState(0); const [refreshKey, setRefreshKey] = useState(0), [, render] = useState(0);
const [ready, setReady] = useState(false), [error, setError] = useState(''); const [ready, setReady] = useState(false), [error, setError] = useState('');
const [navigationBusy, setNavigationBusy] = useState(false);
const alive = useRef(true); const alive = useRef(true);
const transitions = useRef<ReturnType<typeof createWorkspaceTransition> | null>(null);
if (!transitions.current) transitions.current = createWorkspaceTransition(
typeof document.startViewTransition === 'function' ? document.startViewTransition.bind(document) : undefined,
() => window.matchMedia('(prefers-reduced-motion: reduce)').matches,
busy => { if (alive.current) setNavigationBusy(busy); },
);
const validate = () => { const validate = () => {
if (validation.current) return validation.current; if (validation.current) return validation.current;
const epoch = generation.current; const epoch = generation.current;
@@ -39,6 +49,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
const latest = await api.me(); const latest = await api.me();
if (!alive.current || generation.current !== epoch) return false; if (!alive.current || generation.current !== epoch) return false;
// 权限改变时清除全部旧缓存,重建此刻正在查看的页面;校验不负责切换路由。 // 权限改变时清除全部旧缓存,重建此刻正在查看的页面;校验不负责切换路由。
transitions.current?.cancel(); requested.current = current.current;
onUserChange(latest); entries.current.clear(); onUserChange(latest); entries.current.clear();
entries.current.set(current.current, { initialSearch: location.search, search: location.search, key: ++key.current, scroll: 0 }); entries.current.set(current.current, { initialSearch: location.search, search: location.search, key: ++key.current, scroll: 0 });
render(value => value + 1); render(value => value + 1);
@@ -66,14 +77,22 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
const previous = entries.current.get(next); const previous = entries.current.get(next);
if (!previous || force) entries.current.set(next, { initialSearch: search, search, key: ++key.current, scroll: 0 }); if (!previous || force) entries.current.set(next, { initialSearch: search, search, key: ++key.current, scroll: 0 });
const entry = entries.current.get(next)!; const entry = entries.current.get(next)!;
if (!pop) history.pushState({}, '', `${location.pathname}${entry.search}`); requested.current = next;
current.current = next; onPageChange(next); render(value => value + 1); transitions.current!.run(async signal => {
// 本地页面先响应点击,网络校验在后台进行;连续切换共享尚未结束的请求。 if (!alive.current || entries.current.get(next) !== entry) return;
void validate(); // 与浏览器快照同步提交页面及滚动位置,避免转场结束后再补一次定位。
flushSync(() => {
if (!pop) history.pushState({}, '', `${location.pathname}${entry.search}`);
current.current = next; onPageChange(next); render(value => value + 1);
});
window.scrollTo(0, entry.scroll);
void validate();
await waitForWorkspaceContent(() => document.querySelector(`.page-view[data-page="${next}"]`), signal);
});
}; };
const navigate = (next: PageKey, query?: QueryParams, resultRef?: ResultRef) => { const navigate = (next: PageKey, query?: QueryParams, resultRef?: ResultRef) => {
if (next === 'imports') next = 'sources'; if (next === 'imports') next = 'sources';
if (next === current.current && !query && !resultRef) return; if (next === requested.current && !query && !resultRef) return;
const params = new URLSearchParams({ page: next }); const params = new URLSearchParams({ page: next });
if (query) params.set('context', encode({ query, ...(resultRef ? { resultRef } : {}) })); if (query) params.set('context', encode({ query, ...(resultRef ? { resultRef } : {}) }));
const cached = entries.current.get(next); const cached = entries.current.get(next);
@@ -89,7 +108,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
void validate(); void validate();
const invalidate = () => setRefreshKey(value => value + 1); const invalidate = () => setRefreshKey(value => value + 1);
window.addEventListener(WORKSPACE_INVALIDATED, invalidate); window.addEventListener(WORKSPACE_INVALIDATED, invalidate);
return () => { alive.current = false; generation.current++; validation.current = null; window.removeEventListener(WORKSPACE_INVALIDATED, invalidate); }; return () => { alive.current = false; transitions.current?.cancel(); generation.current++; validation.current = null; window.removeEventListener(WORKSPACE_INVALIDATED, invalidate); };
}, []); }, []);
const activeEntryKey = entries.current.get(page)?.key; const activeEntryKey = entries.current.get(page)?.key;
useLayoutEffect(() => { useLayoutEffect(() => {
@@ -101,7 +120,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
if (!ready) return connectionNotice || <div className="loading-panel"><Spin />正在打开工作台…</div>; if (!ready) return connectionNotice || <div className="loading-panel"><Spin />正在打开工作台…</div>;
return <>{connectionNotice}{Array.from(entries.current.entries()).filter(([name]) => retained(name) || name === page).map(([name, entry]) => { return <>{connectionNotice}{Array.from(entries.current.entries()).filter(([name]) => retained(name) || name === page).map(([name, entry]) => {
const active = name === page; const active = name === page;
return <div key={`${name}-${entry.key}`} className="page-view" data-page={name} hidden={!active} style={!active ? { display: 'none' } : undefined}> return <div key={`${name}-${entry.key}`} className="page-view" data-page={name} hidden={!active} inert={active && navigationBusy} style={!active ? { display: 'none' } : undefined}>
<PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey, onLocationChange: search => { entry.search = search; } }}> <PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey, onLocationChange: search => { entry.search = search; } }}>
<Suspense fallback={<div className="loading-panel"><Spin />正在打开页面…</div>}> <Suspense fallback={<div className="loading-panel"><Spin />正在打开页面…</div>}>
{name === 'blackProduct' || name === 'brightProduct' ? <StageProductPage stage={name === 'blackProduct' ? 'black' : 'bright'} onUnauthorized={onUnauthorized} /> : QUERY_PAGES.includes(name) ? <QueryPage page={name} onUnauthorized={onUnauthorized} onNavigate={navigate} /> : <ManagementPages page={name} user={user} onUnauthorized={onUnauthorized} onNavigate={navigate} />} {name === 'blackProduct' || name === 'brightProduct' ? <StageProductPage stage={name === 'blackProduct' ? 'black' : 'bright'} onUnauthorized={onUnauthorized} /> : QUERY_PAGES.includes(name) ? <QueryPage page={name} onUnauthorized={onUnauthorized} onNavigate={navigate} /> : <ManagementPages page={name} user={user} onUnauthorized={onUnauthorized} onNavigate={navigate} />}
+104 -99
View File
@@ -1,3 +1,4 @@
import { AnimatedMetricText, SmoothTableFrame, useAnimatedMetricText, useRetainedResult } from './QueryResultMotion';
import { trendBarPalette } from './trendBarPalette'; import { trendBarPalette } from './trendBarPalette';
import { getWorkspaceTheme } from './ui-themes'; import { getWorkspaceTheme } from './ui-themes';
import { queryScrapWeight, queryTotalScrapWeight, type QueryRateBasis } from './queryMetricValues'; import { queryScrapWeight, queryTotalScrapWeight, type QueryRateBasis } from './queryMetricValues';
@@ -44,7 +45,7 @@ import type {
import type { PageKey } from './QualityWorkspace'; import type { PageKey } from './QualityWorkspace';
import { readableSelectPopup } from './readableSelectPopup'; import { readableSelectPopup } from './readableSelectPopup';
import { isInternalDataField, readableMetricFormula } from './publicDataDisplay'; import { isInternalDataField, readableMetricFormula } from './publicDataDisplay';
import { previousCompleteMonth, previousCompleteQuarter } from './periodDefaults'; import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
import { defectWeightRate } from './trendMetrics'; import { defectWeightRate } from './trendMetrics';
import './query-motion.css'; import './query-motion.css';
import { ExtraQueryFilters } from './ExtraQueryFilters'; import { ExtraQueryFilters } from './ExtraQueryFilters';
@@ -299,9 +300,10 @@ export default function QueryPage({ page, onUnauthorized }: {
const [options, setOptions] = useState<OptionsResponse | null>(null); const [options, setOptions] = useState<OptionsResponse | null>(null);
const [optionsError, setOptionsError] = useState(''); const [optionsError, setOptionsError] = useState('');
const [optionsLoading, setOptionsLoading] = useState(true); const [optionsLoading, setOptionsLoading] = useState(true);
const automaticPeriod = useRef(!initialQuery.year && !initialQuery.month && !initialQuery.quarter);
const defaultMonth = previousCompleteMonth(); const defaultMonth = previousCompleteMonth();
const defaultQuarter = previousCompleteQuarter(); const defaultQuarter = previousCompleteQuarter();
const [period, setPeriod] = useState<PeriodKind>(initialQuery.month ? 'month' : initialQuery.quarter ? 'quarter' : page === 'overall' ? 'year' : 'month'); const [period, setPeriod] = useState<PeriodKind>(initialQuery.month ? 'month' : initialQuery.quarter ? 'quarter' : initialQuery.year ? 'year' : 'month');
const [year, setYear] = useState(initialQuery.year || (period === 'month' ? defaultMonth.year : period === 'quarter' ? defaultQuarter.year : new Date().getFullYear())); const [year, setYear] = useState(initialQuery.year || (period === 'month' ? defaultMonth.year : period === 'quarter' ? defaultQuarter.year : new Date().getFullYear()));
const [month, setMonth] = useState(initialQuery.month || defaultMonth.month); const [month, setMonth] = useState(initialQuery.month || defaultMonth.month);
const [quarter, setQuarter] = useState(initialQuery.quarter || defaultQuarter.quarter); const [quarter, setQuarter] = useState(initialQuery.quarter || defaultQuarter.quarter);
@@ -342,7 +344,6 @@ export default function QueryPage({ page, onUnauthorized }: {
const [recordQuerySnapshot, setRecordQuerySnapshot] = useState<QueryParams | null>(null); const [recordQuerySnapshot, setRecordQuerySnapshot] = useState<QueryParams | null>(null);
const [basisOpen, setBasisOpen] = useState(false); const [basisOpen, setBasisOpen] = useState(false);
const trendAnchorTop = useRef<number | null>(null); const trendAnchorTop = useRef<number | null>(null);
const tableContent = useRef<HTMLDivElement>(null);
const summaryExport = useRef<{ exportExcel: () => Promise<void> }>(null); const summaryExport = useRef<{ exportExcel: () => Promise<void> }>(null);
const [summaryExporting, setSummaryExporting] = useState(false); const [summaryExporting, setSummaryExporting] = useState(false);
const trendSection = useRef<HTMLElement>(null); const trendSection = useRef<HTMLElement>(null);
@@ -353,7 +354,6 @@ export default function QueryPage({ page, onUnauthorized }: {
if (active && refreshSeen.current !== refreshKey) { refreshSeen.current = refreshKey; setQueryRevision(value => value + 1); } if (active && refreshSeen.current !== refreshKey) { refreshSeen.current = refreshKey; setQueryRevision(value => value + 1); }
if (!active) { setRecordsOpen(false); setBasisOpen(false); } if (!active) { setRecordsOpen(false); setBasisOpen(false); }
}, [active, refreshKey]); }, [active, refreshKey]);
const tableHeight = useRef(525);
@@ -362,8 +362,11 @@ export default function QueryPage({ page, onUnauthorized }: {
api.options().then(result => { api.options().then(result => {
if (!alive) return; if (!alive) return;
setOptions(result); setOptions(result);
const yearOptions = (result.years || []).map(value => Number(String(value).match(/\d{4}/)?.[0])).filter(Number.isFinite); if (automaticPeriod.current) {
if (yearOptions.length && !yearOptions.includes(year)) setYear(Math.max(...yearOptions)); const available = defaultQueryMonth(result);
setYear(available.year); setMonth(available.month);
automaticPeriod.current = false;
}
setOptionsError(''); setOptionsError('');
}).catch(errorValue => { }).catch(errorValue => {
if (onUnauthorized(errorValue)) return; if (onUnauthorized(errorValue)) return;
@@ -413,10 +416,6 @@ export default function QueryPage({ page, onUnauthorized }: {
const queryPending = !currentMetricsData && !currentMetricsError; const queryPending = !currentMetricsData && !currentMetricsError;
const queryBusy = loading || queryPending; const queryBusy = loading || queryPending;
const metricKeyRef = useRef(metricKey); const metricKeyRef = useRef(metricKey);
useLayoutEffect(() => {
// CSS min-height uses layout pixels; DOM rectangles include workspace zoom.
if (currentMetricsData && tableContent.current) tableHeight.current = tableContent.current.offsetHeight;
}, [currentMetricsData, fullFields, drilledProduct]);
metricKeyRef.current = metricKey; metricKeyRef.current = metricKey;
const useSummaryTrend = period === 'year' && !trendObject && trendGranularity === 'month'; const useSummaryTrend = period === 'year' && !trendObject && trendGranularity === 'month';
const trendParams = useMemo<QueryParams>(() => { const trendParams = useMemo<QueryParams>(() => {
@@ -446,6 +445,7 @@ export default function QueryPage({ page, onUnauthorized }: {
}, [queryKey, active]); }, [queryKey, active]);
useEffect(() => { useEffect(() => {
if (optionsLoading) return;
const controller = new AbortController(); const controller = new AbortController();
setLoading(true); setLoading(true);
setError(''); setError('');
@@ -467,7 +467,7 @@ export default function QueryPage({ page, onUnauthorized }: {
setErrorKey(metricKey); setErrorKey(metricKey);
}).finally(() => { if (!controller.signal.aborted) setLoading(false); }); }).finally(() => { if (!controller.signal.aborted) setLoading(false); });
return () => controller.abort(); return () => controller.abort();
}, [metricKey, queryRevision, onUnauthorized]); }, [metricKey, queryRevision, onUnauthorized, optionsLoading]);
useEffect(() => { useEffect(() => {
if (!trendObject || defectQueryKey === queryKey) { if (!trendObject || defectQueryKey === queryKey) {
@@ -491,6 +491,7 @@ export default function QueryPage({ page, onUnauthorized }: {
}, [trendObject, defectQueryKey, queryKey, queryRevision, onUnauthorized]); }, [trendObject, defectQueryKey, queryKey, queryRevision, onUnauthorized]);
useEffect(() => { useEffect(() => {
if (optionsLoading) return;
if (useSummaryTrend) { if (useSummaryTrend) {
setTrendLoading(false); setTrendLoading(false);
return; return;
@@ -506,7 +507,7 @@ export default function QueryPage({ page, onUnauthorized }: {
if (!controller.signal.aborted && !onUnauthorized(errorValue)) message.error(`趋势加载失败:${chooseError(errorValue)}`); if (!controller.signal.aborted && !onUnauthorized(errorValue)) message.error(`趋势加载失败:${chooseError(errorValue)}`);
}).finally(() => { if (!controller.signal.aborted) setTrendLoading(false); }); }).finally(() => { if (!controller.signal.aborted) setTrendLoading(false); });
return () => controller.abort(); return () => controller.abort();
}, [trendKey, useSummaryTrend, queryRevision, onUnauthorized, message]); }, [trendKey, useSummaryTrend, queryRevision, onUnauthorized, message, optionsLoading]);
useEffect(() => { useEffect(() => {
let alive = true; let alive = true;
@@ -568,6 +569,21 @@ export default function QueryPage({ page, onUnauthorized }: {
return orderedRows.filter(row => [row.label, row.department, row.group, row.product, row.projectGroup].filter(Boolean).join(' ').toLocaleLowerCase().includes(term)); return orderedRows.filter(row => [row.label, row.department, row.group, row.product, row.projectGroup].filter(Boolean).join(' ').toLocaleLowerCase().includes(term));
}, [page, period, currentMetricsData, appliedSearch, year, view, department, allowedGroupSet]); }, [page, period, currentMetricsData, appliedSearch, year, view, department, allowedGroupSet]);
const tableReady = drilledProduct ? trendDataKey === trendKey && !trendLoading : !!currentMetricsData;
const retainedTable = useRetainedResult(tableReady ? {
rows: drilledProduct ? drilledTrendData : visibleRows,
view: drilledProduct ? 'overall' as const : view,
layoutView: drilledProduct ? 'product' as const : view,
period: drilledProduct ? 'year' as const : period,
year, month, quarter, drilledProduct,
} : null);
const tableRows = retainedTable?.rows || [];
const tablePeriod = retainedTable?.period || period;
const tableView = retainedTable?.view || view;
const tableMonth = retainedTable?.month || month;
const tableQuarter = retainedTable?.quarter || quarter;
const tableProduct = retainedTable?.drilledProduct || '';
const captureTrendAnchor = useCallback(() => { const captureTrendAnchor = useCallback(() => {
trendAnchorTop.current = trendSection.current?.getBoundingClientRect().top ?? null; trendAnchorTop.current = trendSection.current?.getBoundingClientRect().top ?? null;
// Keep enough document height while the downstream charts are replaced by // Keep enough document height while the downstream charts are replaced by
@@ -575,6 +591,7 @@ export default function QueryPage({ page, onUnauthorized }: {
defectsHeight.current = defectsSection.current?.offsetHeight ?? 0; defectsHeight.current = defectsSection.current?.offsetHeight ?? 0;
}, []); }, []);
const selectTrendPeriod = useCallback((value: number | string) => { const selectTrendPeriod = useCallback((value: number | string) => {
automaticPeriod.current = false;
const raw = String(value); const raw = String(value);
const quarterMatch = raw.match(/^(\d{4})-Q([1-4])$/); const quarterMatch = raw.match(/^(\d{4})-Q([1-4])$/);
const yearMonth = raw.match(/^(\d{4})-(\d{1,2})$/); const yearMonth = raw.match(/^(\d{4})-(\d{1,2})$/);
@@ -662,7 +679,8 @@ export default function QueryPage({ page, onUnauthorized }: {
}, [summaryMetricsData, drilledProduct, defectQueryParams, queryParams, view, message]); }, [summaryMetricsData, drilledProduct, defectQueryParams, queryParams, view, message]);
const summaryMetricsError = drilledProduct ? trendObjectMetricsError : currentMetricsError; const summaryMetricsError = drilledProduct ? trendObjectMetricsError : currentMetricsError;
const summaryBusy = drilledProduct ? trendObjectMetricsLoading || !summaryMetricsData && !summaryMetricsError : queryBusy; const summaryBusy = drilledProduct ? trendObjectMetricsLoading || !summaryMetricsData && !summaryMetricsError : queryBusy;
const rowForSummary = summaryMetricsData?.summary; const displayedSummaryData = useRetainedResult(summaryMetricsData);
const rowForSummary = displayedSummaryData?.summary;
const rawFormulaDescriptions = summaryMetricsData?.context.metricFormulaDescriptions; const rawFormulaDescriptions = summaryMetricsData?.context.metricFormulaDescriptions;
const formulaDescriptions = rawFormulaDescriptions && typeof rawFormulaDescriptions === 'object' && !Array.isArray(rawFormulaDescriptions) ? rawFormulaDescriptions as Record<string, unknown> : {}; const formulaDescriptions = rawFormulaDescriptions && typeof rawFormulaDescriptions === 'object' && !Array.isArray(rawFormulaDescriptions) ? rawFormulaDescriptions as Record<string, unknown> : {};
const compositeFormula = formulaDescriptions[rateBasis === 'original' ? 'compositeRate' : 'compositeRateWithoutHeadquartersScrap']; const compositeFormula = formulaDescriptions[rateBasis === 'original' ? 'compositeRate' : 'compositeRateWithoutHeadquartersScrap'];
@@ -719,11 +737,12 @@ export default function QueryPage({ page, onUnauthorized }: {
value={period} value={period}
options={[{ label: '年度', value: 'year' }, { label: '季度', value: 'quarter' }, { label: '月度', value: 'month' }]} options={[{ label: '年度', value: 'year' }, { label: '季度', value: 'quarter' }, { label: '月度', value: 'month' }]}
onChange={value => { onChange={value => {
automaticPeriod.current = false;
const nextPeriod = value as PeriodKind; const nextPeriod = value as PeriodKind;
setPeriod(nextPeriod); setPeriod(nextPeriod);
setTrendGranularity(nextPeriod === 'quarter' ? 'quarter' : 'month'); setTrendGranularity(nextPeriod === 'quarter' ? 'quarter' : 'month');
if (nextPeriod === 'month') { if (nextPeriod === 'month') {
const previous = previousCompleteMonth(); const previous = defaultQueryMonth(options);
setYear(previous.year); setYear(previous.year);
setMonth(previous.month); setMonth(previous.month);
} else if (nextPeriod === 'quarter') { } else if (nextPeriod === 'quarter') {
@@ -734,9 +753,9 @@ export default function QueryPage({ page, onUnauthorized }: {
}} }}
aria-label="统计周期" aria-label="统计周期"
/> />
<label className="query-field query-period-field query-period-year"><span>年份</span><Select aria-label="年份" value={year} options={years.length ? years : [{ label: `${year}年`, value: year }]} onChange={setYear} loading={optionsLoading} /></label> <label className="query-field query-period-field query-period-year"><span>年份</span><Select aria-label="年份" value={year} options={years.length ? years : [{ label: `${year}年`, value: year }]} onChange={value => { automaticPeriod.current = false; setYear(value); }} loading={optionsLoading} /></label>
{period === 'month' && <label className="query-field query-period-field query-period-month"><span>月份</span><Select aria-label="月份" value={month} options={MONTHS.map((label, index) => ({ label, value: index + 1 }))} onChange={setMonth} /></label>} {period === 'month' && <label className="query-field query-period-field query-period-month"><span>月份</span><Select aria-label="月份" value={month} options={MONTHS.map((label, index) => ({ label, value: index + 1 }))} onChange={value => { automaticPeriod.current = false; setMonth(value); }} /></label>}
{period === 'quarter' && <label className="query-field query-period-field query-period-quarter"><span>季度</span><Select aria-label="季度" value={quarter} options={[1, 2, 3, 4].map(value => ({ label: `第${value}季度`, value }))} onChange={setQuarter} /></label>} {period === 'quarter' && <label className="query-field query-period-field query-period-quarter"><span>季度</span><Select aria-label="季度" value={quarter} options={[1, 2, 3, 4].map(value => ({ label: `第${value}季度`, value }))} onChange={value => { automaticPeriod.current = false; setQuarter(value); }} /></label>}
{filterSelect('产业部', department, options?.departments?.filter(name => !RETIRED_DEPARTMENTS.has(name)), values => { setDepartment(values); setGroup([]); setProduct([]); })} {filterSelect('产业部', department, options?.departments?.filter(name => !RETIRED_DEPARTMENTS.has(name)), values => { setDepartment(values); setGroup([]); setProduct([]); })}
{filterSelect('业务分组', group, allowedGroups, values => { setGroup(values); setProduct([]); }, !department.length)} {filterSelect('业务分组', group, allowedGroups, values => { setGroup(values); setProduct([]); }, !department.length)}
{filterSelect('产品', product, department.length || group.length ? organizationPathOptions.products : options?.products, setProduct)} {filterSelect('产品', product, department.length || group.length ? organizationPathOptions.products : options?.products, setProduct)}
@@ -744,7 +763,7 @@ export default function QueryPage({ page, onUnauthorized }: {
<ExtraQueryFilters key={queryRevision} projectGroup={projectGroup} projectGroups={options?.projectGroupStatus === 'READY' ? options.projectGroups : undefined} onProjectGroup={setProjectGroup} value={extraFilters} onChange={setExtraFilters} onUnauthorized={onUnauthorized} /> <ExtraQueryFilters key={queryRevision} projectGroup={projectGroup} projectGroups={options?.projectGroupStatus === 'READY' ? options.projectGroups : undefined} onProjectGroup={setProjectGroup} value={extraFilters} onChange={setExtraFilters} onUnauthorized={onUnauthorized} />
<div className="query-toolbar-tail"> <div className="query-toolbar-tail">
<span className={`query-status ${queryBusy || summaryBusy ? 'busy' : currentMetricsError || summaryMetricsError ? 'failed' : ''}`}><i />{queryBusy || summaryBusy ? '正在查询' : currentMetricsError || summaryMetricsError ? '查询失败' : '查询完成'}</span> <span className={`query-status ${queryBusy || summaryBusy ? 'busy' : currentMetricsError || summaryMetricsError ? 'failed' : ''}`}><i />{queryBusy || summaryBusy ? '正在查询' : currentMetricsError || summaryMetricsError ? '查询失败' : '查询完成'}</span>
<Button type="default" onClick={() => { const previous = previousCompleteMonth(); const previousQuarter = previousCompleteQuarter(); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); 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> <Button type="default" onClick={() => { automaticPeriod.current = false; const previous = defaultQueryMonth(options); const previousQuarter = previousCompleteQuarter(); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod('month'); setTrendGranularity('month'); }}>重置</Button>
</div> </div>
{organizationSummary.length > 0 && <div className="organization-breadcrumb" aria-label="当前组织路径"> {organizationSummary.length > 0 && <div className="organization-breadcrumb" aria-label="当前组织路径">
<span>组织路径</span><Button type="link" onClick={() => { setDepartment([]); setGroup([]); setProduct([]); }}>全部组织</Button> <span>组织路径</span><Button type="link" onClick={() => { setDepartment([]); setGroup([]); setProduct([]); }}>全部组织</Button>
@@ -754,12 +773,12 @@ export default function QueryPage({ page, onUnauthorized }: {
{currentMetricsError && <Alert showIcon type="error" message="质量指标查询失败" description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />} {currentMetricsError && <Alert showIcon type="error" message="质量指标查询失败" description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
{drilledProduct && summaryMetricsError && <Alert showIcon type="error" message="当前产品指标查询失败" description={summaryMetricsError} action={<Button size="small" onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />} {drilledProduct && summaryMetricsError && <Alert showIcon type="error" message="当前产品指标查询失败" description={summaryMetricsError} action={<Button size="small" onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
<section className={`metric-strip ${!summaryMetricsData ? 'query-awaiting-data' : ''}`} aria-label="质量指标" aria-busy={summaryBusy} inert={!summaryMetricsData}> <section className={`metric-strip ${!displayedSummaryData ? 'query-awaiting-data' : ''}`} aria-label="质量指标" aria-busy={summaryBusy} inert={!summaryMetricsData}>
<div className="rate-basis-control"><Segmented size="small" value={rateBasis} options={[{ label: '原口径', value: 'original' }, { label: '去本部报废', value: 'withoutHeadquartersScrap' }]} onChange={value => setRateBasis(value as typeof rateBasis)} aria-label="合格率口径" /></div> <div className="rate-basis-control"><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="综合合格率" value={rateText(visibleCompositeRate(rowForSummary, rateBasis))} onClick={() => setBasisOpen(true)} /> <MetricCard primary label="综合合格率" value={rateText(visibleCompositeRate(rowForSummary, rateBasis))} onClick={() => setBasisOpen(true)} />
<MetricCard label="黑片合格率" value={rateText(visibleStageRate(rowForSummary, 'black'))} note={!summaryMetricsData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') ? hasValidRateDenominator(rowForSummary, 'black') ? `合格重量 ${numberText(rowForSummary?.black?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少黑片来源'} stage="black" onClick={() => openRecords(null, 'black')} /> <MetricCard label="黑片合格率" value={rateText(visibleStageRate(rowForSummary, 'black'))} note={!displayedSummaryData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') ? hasValidRateDenominator(rowForSummary, 'black') ? `合格重量 ${numberText(rowForSummary?.black?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少黑片来源'} stage="black" onClick={() => openRecords(null, 'black')} />
<MetricCard label="亮片合格率" value={rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))} note={!summaryMetricsData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'bright') ? hasValidRateDenominator(rowForSummary, 'bright') ? `合格重量 ${numberText(rowForSummary?.bright?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少亮片来源'} stage="bright" onClick={() => openRecords(null, 'bright')} /> <MetricCard label="亮片合格率" value={rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))} note={!displayedSummaryData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : 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(queryTotalScrapWeight(rowForSummary, rateBasis))} kg` : '—'} note={!summaryMetricsData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright') ? `黑片 ${numberText(rowForSummary?.black?.scrapWeight)} kg · 亮片 ${numberText(queryScrapWeight(rowForSummary?.bright, 'bright', rateBasis))} kg` : '缺少阶段来源'} onClick={() => openRecords(null, 'black')} /> <MetricCard label="报废总重" value={rowForSummary && (hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright')) ? `${numberText(queryTotalScrapWeight(rowForSummary, rateBasis))} kg` : '—'} note={!displayedSummaryData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright') ? `黑片 ${numberText(rowForSummary?.black?.scrapWeight)} kg · 亮片 ${numberText(queryScrapWeight(rowForSummary?.bright, 'bright', rateBasis))} kg` : '缺少阶段来源'} onClick={() => openRecords(null, 'black')} />
</section> </section>
{['department', 'group', 'product'].includes(page) && <> {['department', 'group', 'product'].includes(page) && <>
@@ -767,77 +786,6 @@ export default function QueryPage({ page, onUnauthorized }: {
</>} </>}
<> <>
<section className="panel section-panel table-panel">
<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 => 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="字段显示" />
<Segmented value={defectDisplay} options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={value=>setDefectDisplay(value as typeof defectDisplay)} aria-label="不良显示方式" />
{!drilledProduct && (view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else { setGroup([]); setDepartment([]); setViewOverride('department'); } }}>{view === 'product' ? '返回业务分组' : '返回产业部'}</Button>}
{drilledProduct && <Button onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回产品汇总</Button>}
<Button icon={<DownloadOutlined />} aria-label="Excel导出" loading={summaryExporting} disabled={queryBusy || summaryBusy || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length} onClick={async () => {
setSummaryExporting(true);
try { await summaryExport.current?.exportExcel(); }
catch (error) { message.error(`导出失败:${chooseError(error)}`); }
finally { setSummaryExporting(false); }
}}>Excel导出</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
ref={summaryExport}
exportFilename={`${drilledProduct || scopeName}质量汇总-${year}${drilledProduct || period === 'year' ? '' : period === 'month' ? `-${String(month).padStart(2, '0')}` : `-Q${quarter}`}-${fullFields ? '完整字段' : '关键指标'}`}
rows={drilledTrendData}
view="overall"
layoutView="product"
pageSizeOverride={12}
period="year"
month={month}
quarter={quarter}
fullFields={fullFields}
defectDisplay={defectDisplay}
rateBasis={rateBasis}
onDetail={openRecords}
onBasis={() => setBasisOpen(true)}
onDrilldown={() => undefined}
/>
) : (
<MetricTable
ref={summaryExport}
exportFilename={`${drilledProduct || scopeName}质量汇总-${year}${drilledProduct || period === 'year' ? '' : period === 'month' ? `-${String(month).padStart(2, '0')}` : `-Q${quarter}`}-${fullFields ? '完整字段' : '关键指标'}`}
rows={visibleRows}
view={view}
period={period}
month={month}
quarter={quarter}
fullFields={fullFields}
defectDisplay={defectDisplay}
rateBasis={rateBasis}
onDetail={openRecords}
onBasis={() => setBasisOpen(true)}
emptyText={queryBusy ? '正在更新数据…' : currentMetricsError ? '查询失败,暂无可展示结果' : '当前条件下暂无数据'}
onDrilldown={row => {
if (view === 'overall') setViewOverride('department');
else if (view === 'department' && row.department) { setSearch(''); setAppliedSearch(''); setTrendObject(''); setGroup([]); setProduct([]); setDepartment([row.department]); setViewOverride('group'); }
else if (view === 'group' && row.group) { setSearch(''); setAppliedSearch(''); setTrendObject(''); setProduct([]); setGroup([row.group]); setViewOverride('product'); }
else if (view === 'product') {
const selectedProduct = row.product || row.label;
if (!selectedProduct) return;
setDrilledProduct(selectedProduct);
setTrendObject(selectedProduct);
setTrendGranularity('month');
setTrendMode('production');
}
}}
/>
)}
</div></Spin>
</section>
<div className="analysis-stack"> <div className="analysis-stack">
<section className="panel section-panel trend-panel" ref={trendSection} id={active ? 'monthly-trend' : undefined}> <section className="panel section-panel trend-panel" ref={trendSection} id={active ? 'monthly-trend' : undefined}>
<div className="section-heading-row trend-heading-row"> <div className="section-heading-row trend-heading-row">
@@ -860,6 +808,62 @@ export default function QueryPage({ page, onUnauthorized }: {
<div className="chart-footnote"><span style={{ marginLeft: 'auto' }}>点击期间筛选,再次点击可取消</span></div> <div className="chart-footnote"><span style={{ marginLeft: 'auto' }}>点击期间筛选,再次点击可取消</span></div>
</section> </section>
<section className="panel section-panel table-panel">
<div className="section-heading-row">
<SectionHeading title={tableProduct ? '产品月度质量数据' : page === 'overall' ? `${tablePeriod === 'year' ? '年度月度' : tablePeriod === 'quarter' ? '季度' : '月度'}汇总` : `${scopeName}质量汇总`} subtitle={tableProduct ? `${retainedTable?.year || year} 年 · ${tableProduct} · 重量 / kg 合格率 / %` : '重量 / kg 合格率 / %'} />
<div className="table-tools">
{(queryBusy || !tableReady) && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}
<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="字段显示" />
<Segmented value={defectDisplay} options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={value=>setDefectDisplay(value as typeof defectDisplay)} aria-label="不良显示方式" />
{!drilledProduct && (view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else { setGroup([]); setDepartment([]); setViewOverride('department'); } }}>{view === 'product' ? '返回业务分组' : '返回产业部'}</Button>}
{drilledProduct && <Button onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回产品汇总</Button>}
<Button icon={<DownloadOutlined />} aria-label="Excel导出" loading={summaryExporting} disabled={queryBusy || summaryBusy || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length} onClick={async () => {
setSummaryExporting(true);
try { await summaryExport.current?.exportExcel(); }
catch (error) { message.error(`导出失败:${chooseError(error)}`); }
finally { setSummaryExporting(false); }
}}>Excel导出</Button>
</div>
</div>
<div className="mobile-scroll-hint">横向滑动查看完整指标</div>
<SmoothTableFrame busy={queryBusy || !tableReady} blocked={queryBusy || summaryBusy || !tableReady}>
<MetricTable
ref={summaryExport}
exportFilename={`${drilledProduct || scopeName}质量汇总-${year}${drilledProduct || period === 'year' ? '' : period === 'month' ? `-${String(month).padStart(2, '0')}` : `-Q${quarter}`}-${fullFields ? '完整字段' : '关键指标'}`}
rows={tableRows}
view={tableView}
layoutView={retainedTable?.layoutView || view}
pageSizeOverride={tableProduct ? 12 : undefined}
period={tablePeriod}
month={tableMonth}
quarter={tableQuarter}
fullFields={fullFields}
defectDisplay={defectDisplay}
rateBasis={rateBasis}
onDetail={openRecords}
onBasis={() => setBasisOpen(true)}
emptyText={queryBusy ? '正在更新数据…' : currentMetricsError ? '查询失败,暂无可展示结果' : '当前条件下暂无数据'}
onDrilldown={row => {
if (drilledProduct) return;
if (view === 'overall') setViewOverride('department');
else if (view === 'department' && row.department) { setSearch(''); setAppliedSearch(''); setTrendObject(''); setGroup([]); setProduct([]); setDepartment([row.department]); setViewOverride('group'); }
else if (view === 'group' && row.group) { setSearch(''); setAppliedSearch(''); setTrendObject(''); setProduct([]); setGroup([row.group]); setViewOverride('product'); }
else if (view === 'product') {
const selectedProduct = row.product || row.label;
if (!selectedProduct) return;
setDrilledProduct(selectedProduct);
setTrendObject(selectedProduct);
setTrendGranularity('month');
setTrendMode('production');
}
}}
/>
</SmoothTableFrame>
</section>
<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" ref={defectsSection} aria-busy={defectsRefreshing} style={{ minHeight: queryBusy && trendAnchorTop.current != null ? defectsHeight.current : undefined }}>
<div className="section-heading-row"> <div className="section-heading-row">
<SectionHeading title="不良具体构成" /> <SectionHeading title="不良具体构成" />
@@ -917,10 +921,11 @@ export default function QueryPage({ page, onUnauthorized }: {
} }
export function MetricCard({ primary, label, value, note, stage, onClick }: { primary?: boolean; label: React.ReactNode; value: string; note?: string; stage?: Stage; onClick: () => void }) { export function MetricCard({ primary, label, value, note, stage, onClick }: { primary?: boolean; label: React.ReactNode; value: string; note?: string; stage?: Stage; onClick: () => void }) {
const parts = value.match(/^(.*?)(%| kg)$/); const displayedValue = useAnimatedMetricText(value);
const parts = displayedValue.match(/^(.*?)(%| kg)$/);
return <button className={`metric-card ${primary ? 'primary' : ''} ${stage || ''}`} onClick={onClick}> return <button className={`metric-card ${primary ? 'primary' : ''} ${stage || ''}`} onClick={onClick}>
<span className="metric-label">{stage && <i className={`stage-dot ${stage}`} />}{label}</span> <span className="metric-label">{stage && <i className={`stage-dot ${stage}`} />}{label}</span>
<strong className="metric-value">{parts ? <>{parts[1]}<span className="metric-unit">{parts[2]}</span></> : value}</strong> <strong className="metric-value">{parts ? <>{parts[1]}<span className="metric-unit">{parts[2]}</span></> : displayedValue}</strong>
{note && <small>{note}</small>} {note && <small>{note}</small>}
</button>; </button>;
} }
@@ -1133,7 +1138,7 @@ export function MetricTable({
align: 'center' as const, align: 'center' as const,
width: field === 'rate' ? (stage === 'bright' && rateBasis !== 'original' ? 164 : fullFields ? 96 : 116) : (fullFields ? 112 : 145), width: field === 'rate' ? (stage === 'bright' && rateBasis !== 'original' ? 164 : fullFields ? 96 : 116) : (fullFields ? 112 : 145),
className: `${field === 'rate' ? `rate-cell ${stage}` : 'weight-cell'} ${className}`, className: `${field === 'rate' ? `rate-cell ${stage}` : 'weight-cell'} ${className}`,
render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{field === 'rate' ? rateText(visibleStageRate(row, stage)) : defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? rateText(defectWeightRate(stageValue(row, stage, field, rateBasis),stageValue(row, stage, 'totalWeight'))) : numberText(stageValue(row, stage, field, rateBasis))}</Button>, render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={field === 'rate' ? rateText(visibleStageRate(row, stage)) : defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? rateText(defectWeightRate(stageValue(row, stage, field, rateBasis),stageValue(row, stage, 'totalWeight'))) : numberText(stageValue(row, stage, field, rateBasis))} /></Button>,
}); });
const defectColumns = (stage: Stage, names: string[]) => names.map(name => ({ const defectColumns = (stage: Stage, names: string[]) => names.map(name => ({
title: `${compact ? stage === 'black' ? '黑片' : '亮片' : ''}${defectDisplay === 'rate' ? defectRateLabel(name) : name}`, title: `${compact ? stage === 'black' ? '黑片' : '亮片' : ''}${defectDisplay === 'rate' ? defectRateLabel(name) : name}`,
@@ -1143,7 +1148,7 @@ export function MetricTable({
width: fullFields ? 100 : 130, width: fullFields ? 100 : 130,
render: (_: unknown, row: MetricRow) => { render: (_: unknown, row: MetricRow) => {
const value = defectList(row, stage).find(item => item.name === name); const value = defectList(row, stage).find(item => item.name === name);
return <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{defectDisplay === 'rate' ? rateText(defectWeightRate(value?.weight,stageValue(row,stage,'totalWeight'))) : numberText(value?.weight ?? null)}</Button>; return <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={defectDisplay === 'rate' ? rateText(defectWeightRate(value?.weight,stageValue(row,stage,'totalWeight'))) : numberText(value?.weight ?? null)} /></Button>;
}, },
})); }));
const brightDetailColumns: ColumnsType<MetricRow> = defectColumns('bright', brightDefects); const brightDetailColumns: ColumnsType<MetricRow> = defectColumns('bright', brightDefects);
@@ -1155,8 +1160,8 @@ export function MetricTable({
const allColumns: ColumnsType<MetricRow> = [ const allColumns: ColumnsType<MetricRow> = [
{ title: isOverall ? period === 'year' ? '月份' : '统计期间' : view === 'group' ? '产业部 / 业务分组' : view === 'product' ? '产品规格' : view === 'projectGroup' ? '项目组' : view === 'department' ? '产业部' : '对象', key: 'object', dataIndex: 'label', fixed: 'left', width: compact ? isOverall ? 100 : 180 : isOverall ? 120 : layoutView === 'product' ? (fullFields ? 240 : 300) : layoutView === 'group' ? (fullFields ? 220 : 260) : (fullFields ? 180 : 220), render: (_: unknown, row) => <span className="object-cell">{view === 'department' || view === 'group' || view === 'product' ? <Button type="link" className="object-drilldown" style={{ userSelect: 'text', WebkitUserSelect: 'text' }} onClick={() => { if (window.getSelection()?.isCollapsed !== false) onDrilldown(row); }}>{title(row)} <span>›</span></Button> : <strong>{title(row)}</strong>}{view === 'group' && row.department && <small>{row.department}</small>}</span> }, { title: isOverall ? period === 'year' ? '月份' : '统计期间' : view === 'group' ? '产业部 / 业务分组' : view === 'product' ? '产品规格' : view === 'projectGroup' ? '项目组' : view === 'department' ? '产业部' : '对象', key: 'object', dataIndex: 'label', fixed: 'left', width: compact ? isOverall ? 100 : 180 : isOverall ? 120 : layoutView === 'product' ? (fullFields ? 240 : 300) : layoutView === 'group' ? (fullFields ? 220 : 260) : (fullFields ? 180 : 220), render: (_: unknown, row) => <span className="object-cell">{view === 'department' || view === 'group' || view === 'product' ? <Button type="link" className="object-drilldown" style={{ userSelect: 'text', WebkitUserSelect: 'text' }} onClick={() => { if (window.getSelection()?.isCollapsed !== false) onDrilldown(row); }}>{title(row)} <span>›</span></Button> : <strong>{title(row)}</strong>}{view === 'group' && row.department && <small>{row.department}</small>}</span> },
{ key: 'stage-black', title: <span className="stage-heading black"><i />黑片</span>, children: [numeric('总重量', 'black', 'totalWeight'), numeric('合格重量', 'black', 'qualifiedWeight'), numeric('报废重量', 'black', 'scrapWeight'), ...defectColumns('black', blackDefects), numeric('合格率', 'black', 'rate')] }, { key: 'stage-black', title: <span className="stage-heading black"><i />黑片</span>, children: [numeric('总重量', 'black', 'totalWeight'), numeric('合格重量', 'black', 'qualifiedWeight'), numeric('报废重量', 'black', 'scrapWeight'), ...defectColumns('black', blackDefects), numeric('合格率', 'black', 'rate')] },
{ key: 'stage-bright', title: <span className="stage-heading bright"><i />亮片</span>, children: [numeric('总重量', 'bright', 'totalWeight'), numeric('合格重量', 'bright', 'qualifiedWeight'), numeric('报废重量', 'bright', 'scrapWeight'), ...brightDetailColumns, { ...numeric('合格率', 'bright', 'rate'), render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{rateText(visibleStageRate(row, 'bright', rateBasis))}</Button> }] }, { key: 'stage-bright', title: <span className="stage-heading bright"><i />亮片</span>, children: [numeric('总重量', 'bright', 'totalWeight'), numeric('合格重量', 'bright', 'qualifiedWeight'), numeric('报废重量', 'bright', 'scrapWeight'), ...brightDetailColumns, { ...numeric('合格率', 'bright', 'rate'), render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={rateText(visibleStageRate(row, 'bright', rateBasis))} /></Button> }] },
{ title: rateBasisTitle('综合合格率', rateBasis, 'composite', onBasis), key: 'compositeRate', dataIndex: 'compositeRate', align: 'center', fixed: compact ? undefined : 'right', width: 120, className: 'combined-column', render: (_: number | null, row: MetricRow) => <button className="combined-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{rateText(visibleCompositeRate(row, rateBasis))}</button> }, { title: rateBasisTitle('综合合格率', rateBasis, 'composite', onBasis), key: 'compositeRate', dataIndex: 'compositeRate', align: 'center', fixed: compact ? undefined : 'right', width: 120, className: 'combined-column', render: (_: number | null, row: MetricRow) => <button className="combined-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={rateText(visibleCompositeRate(row, rateBasis))} /></button> },
{ title: '操作', key: 'actions', fixed: compact ? undefined : 'right', width: 96, align: 'center', render: (_: unknown, row) => (row as TrendMetricRow).noData ? <span>—</span> : <Button type="link" onClick={() => openRow(row, onlyStage || 'black')}>来源明细</Button> }, { title: '操作', key: 'actions', fixed: compact ? undefined : 'right', width: 96, align: 'center', render: (_: unknown, row) => (row as TrendMetricRow).noData ? <span>—</span> : <Button type="link" onClick={() => openRow(row, onlyStage || 'black')}>来源明细</Button> },
]; ];
const columns = onlyStage ? allColumns.filter(column => !['compositeRate', `stage-${onlyStage === 'black' ? 'bright' : 'black'}`].includes(String(column.key))) : allColumns; const columns = onlyStage ? allColumns.filter(column => !['compositeRate', `stage-${onlyStage === 'black' ? 'bright' : 'black'}`].includes(String(column.key))) : allColumns;
+68
View File
@@ -0,0 +1,68 @@
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
export function useRetainedResult<T>(current: T | null | undefined): T | null {
const previous = useRef<T | null>(null);
useLayoutEffect(() => { if (current != null) previous.current = current; }, [current]);
return current ?? previous.current;
}
function numericText(text: string) {
const match = text.match(/^(-?[\d,]+(?:\.\d+)?)(%| kg)?$/);
if (!match) return null;
const value = Number(match[1].replaceAll(',', ''));
return Number.isFinite(value) ? { value, decimals: match[1].split('.')[1]?.length || 0, unit: match[2] || '' } : null;
}
export function interpolateMetricText(from: string, to: string, progress: number): string {
const start = numericText(from), target = numericText(to);
if (!start || !target || start.unit !== target.unit || progress >= 1) return to;
const value = start.value + (target.value - start.value) * Math.max(0, progress);
return value.toLocaleString('en-US', { minimumFractionDigits: target.decimals, maximumFractionDigits: target.decimals }) + target.unit;
}
export function useAnimatedMetricText(value: string): string {
const [display, setDisplay] = useState(value);
const shown = useRef(value);
useLayoutEffect(() => {
const from = shown.current;
const commit = (text: string) => { shown.current = text; setDisplay(text); };
if (from === value) return;
const startValue = numericText(from), targetValue = numericText(value);
if (!startValue || !targetValue || startValue.unit !== targetValue.unit || window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
commit(value); return;
}
const start = performance.now();
let frame = 0;
const update = (now: number) => {
const progress = Math.min(1, (now - start) / 520);
commit(interpolateMetricText(from, value, 1 - (1 - progress) ** 3));
if (progress < 1) frame = requestAnimationFrame(update);
};
frame = requestAnimationFrame(update);
// 连续点击时从此刻的显示值继续,不回到上一次请求的起点。
return () => cancelAnimationFrame(frame);
}, [value]);
return display;
}
export function AnimatedMetricText({ value }: { value: string }) {
return <span className="animated-metric-text">{useAnimatedMetricText(value)}</span>;
}
export function SmoothTableFrame({ children, busy, blocked }: { children: ReactNode; busy: boolean; blocked: boolean }) {
const content = useRef<HTMLDivElement>(null);
const [height, setHeight] = useState<number>();
useLayoutEffect(() => {
const node = content.current;
if (!node) return;
const measure = () => setHeight(node.offsetHeight);
measure();
const observer = new ResizeObserver(measure);
observer.observe(node);
return () => observer.disconnect();
}, []);
useLayoutEffect(() => { if (content.current) setHeight(content.current.offsetHeight); }, [children]);
return <div className="smooth-table-frame" style={{ height }}>
<div ref={content} className="query-table-content" aria-busy={busy} inert={blocked}>{children}</div>
</div>;
}
+24 -17
View File
@@ -1,3 +1,4 @@
import { SmoothTableFrame, useRetainedResult } from './QueryResultMotion';
import { queryScrapWeight } from './queryMetricValues'; import { queryScrapWeight } from './queryMetricValues';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Alert, App, Button, Empty, Input, Modal, Segmented, Select, Spin } from 'antd'; import { Alert, App, Button, Empty, Input, Modal, Segmented, Select, Spin } from 'antd';
@@ -7,7 +8,7 @@ import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHea
import { StageSourceFilters } from './StageSourceFilters'; import { StageSourceFilters } from './StageSourceFilters';
import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery'; import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery';
import { usePageCache } from './pageCache'; import { usePageCache } from './pageCache';
import { previousCompleteMonth, previousCompleteQuarter } from './periodDefaults'; import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
import { readableSelectPopup } from './readableSelectPopup'; import { readableSelectPopup } from './readableSelectPopup';
import { readableMetricFormula } from './publicDataDisplay'; import { readableMetricFormula } from './publicDataDisplay';
import type { MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage } from './types'; import type { MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage } from './types';
@@ -18,6 +19,7 @@ const rate=(v:number|null|undefined)=>typeof v==='number'?`${(v*100).toFixed(2)}
export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onUnauthorized:(error:unknown)=>boolean}) { export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onUnauthorized:(error:unknown)=>boolean}) {
const {message}=App.useApp();const {active,initialSearch,refreshKey,onLocationChange}=usePageCache(); const {message}=App.useApp();const {active,initialSearch,refreshKey,onLocationChange}=usePageCache();
const [initial]=useState(()=>queryFromLocation(initialSearch));const defaults=previousCompleteMonth(); const [initial]=useState(()=>queryFromLocation(initialSearch));const defaults=previousCompleteMonth();
const automaticPeriod=useRef(!initial.year&&!initial.month&&!initial.quarter);
const [period,setPeriod]=useState<PeriodKind>(initial.quarter?'quarter':initial.month?'month':initial.year?'year':'month'); const [period,setPeriod]=useState<PeriodKind>(initial.quarter?'quarter':initial.month?'month':initial.year?'year':'month');
const [year,setYear]=useState(initial.year||defaults.year);const [month,setMonth]=useState(initial.month||defaults.month);const [quarter,setQuarter]=useState(initial.quarter||previousCompleteQuarter().quarter); const [year,setYear]=useState(initial.year||defaults.year);const [month,setMonth]=useState(initial.month||defaults.month);const [quarter,setQuarter]=useState(initial.quarter||previousCompleteQuarter().quarter);
const [department,setDepartment]=useState(()=>decodeQueryValueList(initial.department));const [group,setGroup]=useState(()=>decodeQueryValueList(initial.group));const [product,setProduct]=useState(()=>decodeQueryValueList(initial.product));const [projectGroup,setProjectGroup]=useState(()=>decodeQueryValueList(initial.projectGroup)); const [department,setDepartment]=useState(()=>decodeQueryValueList(initial.department));const [group,setGroup]=useState(()=>decodeQueryValueList(initial.group));const [product,setProduct]=useState(()=>decodeQueryValueList(initial.product));const [projectGroup,setProjectGroup]=useState(()=>decodeQueryValueList(initial.projectGroup));
@@ -32,7 +34,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
const label=stage==='black'?'黑片':'亮片'; const label=stage==='black'?'黑片':'亮片';
const loadSupport=useCallback(async()=>{ const loadSupport=useCallback(async()=>{
setSupportLoading(true);setSupportError(''); setSupportLoading(true);setSupportError('');
try{const [choices,source]=await Promise.all([api.options(),api.sourceColumnCatalog()]);setOptions(choices);setCatalog(source);} try{const [choices,source]=await Promise.all([api.options(),api.sourceColumnCatalog()]);if(automaticPeriod.current){const available=defaultQueryMonth(choices);setYear(available.year);setMonth(available.month);automaticPeriod.current=false;}setOptions(choices);setCatalog(source);}
catch(error){if(!onUnauthorized(error))setSupportError(error instanceof Error?error.message:'查询条件读取失败');} catch(error){if(!onUnauthorized(error))setSupportError(error instanceof Error?error.message:'查询条件读取失败');}
finally{setSupportLoading(false);} finally{setSupportLoading(false);}
},[onUnauthorized]); },[onUnauthorized]);
@@ -52,23 +54,29 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
const trendKey=JSON.stringify({query:trendQuery,revision}); const trendKey=JSON.stringify({query:trendQuery,revision});
useEffect(()=>{if(!active||!current||!trendQuery)return;const controller=new AbortController();setTrendLoading(true);setTrendError('');void api.metrics(trendQuery,controller.signal).then(value=>{if(!controller.signal.aborted)setTrendResponse({key:trendKey,value});}).catch(error=>{if(!controller.signal.aborted&&!onUnauthorized(error))setTrendError(error instanceof Error?error.message:'趋势读取失败');}).finally(()=>{if(!controller.signal.aborted)setTrendLoading(false);});return()=>controller.abort();},[active,trendKey,!!current,onUnauthorized]); useEffect(()=>{if(!active||!current||!trendQuery)return;const controller=new AbortController();setTrendLoading(true);setTrendError('');void api.metrics(trendQuery,controller.signal).then(value=>{if(!controller.signal.aborted)setTrendResponse({key:trendKey,value});}).catch(error=>{if(!controller.signal.aborted&&!onUnauthorized(error))setTrendError(error instanceof Error?error.message:'趋势读取失败');}).finally(()=>{if(!controller.signal.aborted)setTrendLoading(false);});return()=>controller.abort();},[active,trendKey,!!current,onUnauthorized]);
const visibleTrend=useMemo(()=>fullYearTrend(trendResponse?.key===trendKey?trendResponse.value.trend:[],applied?.year||year,trendGranularity),[trendResponse,trendKey,applied?.year,year,trendGranularity]); const visibleTrend=useMemo(()=>fullYearTrend(trendResponse?.key===trendKey?trendResponse.value.trend:[],applied?.year||year,trendGranularity),[trendResponse,trendKey,applied?.year,year,trendGranularity]);
const selectTrendPeriod=(value:number|string)=>{if(!applied)return;const text=String(value);if(trendGranularity==='year'){const selectedYear=Number(text);if(Number.isFinite(selectedYear)){setYear(selectedYear);setPeriod('year');setApplied({...applied,year:selectedYear,month:undefined,quarter:undefined});}}else if(trendGranularity==='quarter'){const selectedQuarter=Number(text.replace(/^.*Q/,''));if(selectedQuarter>=1&&selectedQuarter<=4){setQuarter(selectedQuarter);setPeriod('quarter');setApplied({...applied,quarter:selectedQuarter,month:undefined});}}else{const selectedMonth=Number(text.slice(-2));if(selectedMonth>=1&&selectedMonth<=12){setMonth(selectedMonth);setPeriod('month');setApplied({...applied,month:selectedMonth,quarter:undefined});}}setRevision(v=>v+1);}; const displayedTrend=useRetainedResult(trendResponse?.key===trendKey?visibleTrend:null)||visibleTrend;
const dirty=!!applied&&JSON.stringify(draft)!==JSON.stringify(applied);const submit=()=>{setApplied(draft);setRevision(v=>v+1);}; const selectedTrendPeriod=trendGranularity==='month'&&applied?.month
? `${applied.year}-${String(applied.month).padStart(2,'0')}`
: trendGranularity==='quarter'&&applied?.quarter ? `${applied.year}-Q${applied.quarter}` : undefined;
const selectTrendPeriod=(value:number|string)=>{if(!applied)return;automaticPeriod.current=false;const text=String(value);if(trendGranularity==='year'){const selectedYear=Number(text);if(Number.isFinite(selectedYear)){setYear(selectedYear);setPeriod('year');setApplied({...applied,year:selectedYear,month:undefined,quarter:undefined});}}else if(trendGranularity==='quarter'){const selectedQuarter=Number(text.replace(/^.*Q/,''));if(selectedQuarter>=1&&selectedQuarter<=4){setQuarter(selectedQuarter);setPeriod('quarter');setApplied({...applied,quarter:selectedQuarter,month:undefined});}}else{const selectedMonth=Number(text.slice(-2));if(selectedMonth>=1&&selectedMonth<=12){setMonth(selectedMonth);setPeriod('month');setApplied({...applied,month:selectedMonth,quarter:undefined});}}setRevision(v=>v+1);};
const dirty=!!applied&&JSON.stringify(draft)!==JSON.stringify(applied);const submit=()=>{automaticPeriod.current=false;setApplied(draft);setRevision(v=>v+1);};
const groups=(options?.groups||[]).filter(name=>!department.length||department.includes(options?.groupDepartments?.[name]||'')); const groups=(options?.groups||[]).filter(name=>!department.length||department.includes(options?.groupDepartments?.[name]||''));
const paths=options?.organizationPaths||[];const products=department.length||group.length?[...new Set(paths.filter(path=>(!department.length||department.includes(path.department||''))&&(!group.length||group.includes(path.group||''))).map(path=>path.product).filter((v):v is string=>!!v))]:options?.products||[]; const paths=options?.organizationPaths||[];const products=department.length||group.length?[...new Set(paths.filter(path=>(!department.length||department.includes(path.department||''))&&(!group.length||group.includes(path.group||''))).map(path=>path.product).filter((v):v is string=>!!v))]:options?.products||[];
const select=(name:string,value:string[],choices:string[],change:(v:string[])=>void)=><label className="query-field query-primary-field"><span>{name}</span><Select {...readableSelectPopup} mode="multiple" allowClear showSearch optionFilterProp="label" aria-label={name} placeholder="全部" maxTagCount="responsive" value={value} options={[...new Set([...choices,...value])].map(v=>({label:v==='__UNASSIGNED__'?'未分类':v,value:v}))} onChange={change}/></label>; const select=(name:string,value:string[],choices:string[],change:(v:string[])=>void)=><label className="query-field query-primary-field"><span>{name}</span><Select {...readableSelectPopup} mode="multiple" allowClear showSearch optionFilterProp="label" aria-label={name} placeholder="全部" maxTagCount="responsive" value={value} options={[...new Set([...choices,...value])].map(v=>({label:v==='__UNASSIGNED__'?'未分类':v,value:v}))} onChange={change}/></label>;
const sortedRows=useMemo(()=>sortStageRowsByTotalWeight(current?.rows||[],stage),[current,stage]); const displayed = useRetainedResult(current && applied ? { data: current, query: applied } : null);
const summary=current?.summary[stage];const stageRate=stage==='bright'&&rateBasis==='withoutHeadquartersScrap'?summary?.rateWithoutHeadquartersScrap:summary?.rate; const displayedQuery = displayed?.query || applied;
const sortedRows=useMemo(()=>sortStageRowsByTotalWeight(displayed?.data.rows||[],stage),[displayed?.data,stage]);
const summary=displayed?.data.summary[stage];const stageRate=stage==='bright'&&rateBasis==='withoutHeadquartersScrap'?summary?.rateWithoutHeadquartersScrap:summary?.rate;
const openDetail=(row:MetricRow|null,_stage:Stage,selectedMonth?:number)=>{if(!applied||!current?.release)return;setRecordVisible(true);setRecords({row,query:{...applied,releaseId:current.release.id,...(row&&selectedMonth==null?{product:row.product||'__UNASSIGNED__'}:{}),...(selectedMonth?{month:selectedMonth,quarter:undefined}: {})}});}; const openDetail=(row:MetricRow|null,_stage:Stage,selectedMonth?:number)=>{if(!applied||!current?.release)return;setRecordVisible(true);setRecords({row,query:{...applied,releaseId:current.release.id,...(row&&selectedMonth==null?{product:row.product||'__UNASSIGNED__'}:{}),...(selectedMonth?{month:selectedMonth,quarter:undefined}: {})}});};
const runExport=async()=>{setExporting(true);try{await exporter.current?.exportExcel();}catch(e){message.error(e instanceof Error?e.message:'导出失败');}finally{setExporting(false);}}; const runExport=async()=>{setExporting(true);try{await exporter.current?.exportExcel();}catch(e){message.error(e instanceof Error?e.message:'导出失败');}finally{setExporting(false);}};
const formulaKey=stage==='black'?'blackRate':rateBasis==='original'?'brightRate':'brightRateWithoutHeadquartersScrap'; const formulaKey=stage==='black'?'blackRate':rateBasis==='original'?'brightRate':'brightRateWithoutHeadquartersScrap';
return <div className="query-page stage-product-page"> return <div className="query-page stage-product-page">
{supportError&&<Alert showIcon type="error" message="查询条件读取失败" description={supportError} action={<Button onClick={()=>void loadSupport()}>重试</Button>}/>} {supportError&&<Alert showIcon type="error" message="查询条件读取失败" description={supportError} action={<Button onClick={()=>void loadSupport()}>重试</Button>}/>}
<section className="query-toolbar panel" aria-label={`${label}汇总条件`}> <section className="query-toolbar panel" aria-label={`${label}汇总条件`}>
<Segmented aria-label="统计周期" value={period} options={[{label:'年度',value:'year'},{label:'季度',value:'quarter'},{label:'月度',value:'month'}]} onChange={v=>setPeriod(v as PeriodKind)}/> <Segmented aria-label="统计周期" value={period} options={[{label:'年度',value:'year'},{label:'季度',value:'quarter'},{label:'月度',value:'month'}]} onChange={v=>{automaticPeriod.current=false;setPeriod(v as PeriodKind);}}/>
<label className="query-field query-period-field"><span>年份</span><Select aria-label="年份" value={year} onChange={setYear} options={(options?.years?.length?options.years:[year]).map(v=>({label:`${v}年`,value:v}))}/></label> <label className="query-field query-period-field"><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}))}/></label>
{period==='month'&&<label className="query-field query-period-field"><span>月份</span><Select aria-label="月份" value={month} onChange={setMonth} options={Array.from({length:12},(_,i)=>({label:`${i+1}月`,value:i+1}))}/></label>} {period==='month'&&<label className="query-field query-period-field"><span>月份</span><Select aria-label="月份" value={month} onChange={v=>{automaticPeriod.current=false;setMonth(v);}} options={Array.from({length:12},(_,i)=>({label:`${i+1}月`,value:i+1}))}/></label>}
{period==='quarter'&&<label className="query-field query-period-field"><span>季度</span><Select aria-label="季度" value={quarter} onChange={setQuarter} options={[1,2,3,4].map(v=>({label:`第${v}季度`,value:v}))}/></label>} {period==='quarter'&&<label className="query-field query-period-field"><span>季度</span><Select aria-label="季度" value={quarter} onChange={v=>{automaticPeriod.current=false;setQuarter(v);}} options={[1,2,3,4].map(v=>({label:`第${v}季度`,value:v}))}/></label>}
{select('产业部',department,options?.departments||[],values=>{setDepartment(values);setGroup([]);setProduct([]);})} {select('产业部',department,options?.departments||[],values=>{setDepartment(values);setGroup([]);setProduct([]);})}
{select('业务分组',group,groups,values=>{setGroup(values);setProduct([]);})} {select('业务分组',group,groups,values=>{setGroup(values);setProduct([]);})}
{select('产品',product,products,setProduct)} {select('产品',product,products,setProduct)}
@@ -86,18 +94,17 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
<MetricCard label="报废重量" value={`${weight(queryScrapWeight(summary,stage,rateBasis))} kg`} onClick={()=>openDetail(null,stage)}/> <MetricCard label="报废重量" value={`${weight(queryScrapWeight(summary,stage,rateBasis))} kg`} onClick={()=>openDetail(null,stage)}/>
<MetricCard label="总重量" value={`${weight(summary?.totalWeight)} kg`} onClick={()=>openDetail(null,stage)}/> <MetricCard label="总重量" value={`${weight(summary?.totalWeight)} kg`} onClick={()=>openDetail(null,stage)}/>
</section> </section>
<div className="query-quality-summary"><span>{current?`来源覆盖 ${current.coverage.sourceMonths.filter(m=>(stage==='black'?m.blackRows:m.brightRows)>0).length} 个月 · 参与计算 ${current.coverage.includedRows.toLocaleString()} 行`:loading?'正在查询…':'暂无统计结果'}</span><Button type="link" disabled={!current} onClick={()=>setBasisOpen(true)}>计算口径</Button></div> <div className="analysis-stack"><section className="panel section-panel trend-panel"><div className="section-heading-row trend-heading-row"><SectionHeading title={`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}变化趋势`} subtitle={`${year} 年 · 当前${label}筛选`}/><Segmented value={trendMode} aria-label="趋势视图" options={[{label:'合格率与产量',value:'production'},{label:'不良率',value:'defects'},{label:`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}数据`,value:'data'}]} onChange={v=>setTrendMode(v as typeof trendMode)}/></div><div className="trend-controls">{trendMode==='data'&&<Segmented value={defectDisplay} aria-label="趋势不良显示方式" options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={v=>setDefectDisplay(v as typeof defectDisplay)}/>}<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={trendGranularity} options={[{label:'按月',value:'month'},{label:'按季度',value:'quarter'},{label:'按年度',value:'year'}]} onChange={setTrendGranularity} aria-label="趋势粒度"/></label></div>{trendError&&<Alert type="warning" message="趋势读取失败" description={trendError}/>}<div className="trend-chart-shell" aria-busy={trendLoading}>{trendMode==='data'?<MetricTable exportFilename={`${label}月度趋势-${year}`} rows={displayedTrend} view="overall" layoutView="product" period="year" month={month} quarter={quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={()=>{}}/>:<TrendChart rows={displayedTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod}/>}{trendLoading&&<span className="trend-refresh-indicator"><Spin size="small"/>正在更新趋势</span>}</div><div className="chart-footnote"><span>指标由来源分量汇总,使用当前生效公式。</span><span>点击期间筛选</span></div></section>
<section className="panel section-panel table-panel"><div className="section-heading-row"><SectionHeading title={`${label}汇总`} subtitle="重量 / kg 合格率 / %"/><div className="table-tools"><Input aria-label="搜索产品名称" placeholder="输入产品名称关键词" allowClear value={search} onChange={e=>setSearch(e.target.value)} onPressEnter={submit}/><Button onClick={submit} disabled={!catalog||!!supportError}>搜索</Button><Segmented value={fullFields?'full':'key'} aria-label="字段显示" options={[{label:'关键指标',value:'key'},{label:'完整字段',value:'full'}]} onChange={v=>setFullFields(v==='full')}/><Segmented value={defectDisplay} aria-label="不良显示方式" options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={v=>setDefectDisplay(v as typeof defectDisplay)}/><Button icon={<DownloadOutlined/>} aria-label="Excel导出" loading={exporting} disabled={!current||loading} onClick={()=>void runExport()}>Excel导出</Button></div></div> <section className="panel section-panel table-panel"><div className="section-heading-row"><SectionHeading title={`${label}汇总`} subtitle="重量 / kg 合格率 / %"/><div className="table-tools"><Input aria-label="搜索产品名称" placeholder="输入产品名称关键词" allowClear value={search} onChange={e=>setSearch(e.target.value)} onPressEnter={submit}/><Button onClick={submit} disabled={!catalog||!!supportError}>搜索</Button><Segmented value={fullFields?'full':'key'} aria-label="字段显示" options={[{label:'关键指标',value:'key'},{label:'完整字段',value:'full'}]} onChange={v=>setFullFields(v==='full')}/><Segmented value={defectDisplay} aria-label="不良显示方式" options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={v=>setDefectDisplay(v as typeof defectDisplay)}/><Button icon={<DownloadOutlined/>} aria-label="Excel导出" loading={exporting} disabled={!current||loading} onClick={()=>void runExport()}>Excel导出</Button></div></div>
<Spin spinning={loading}><MetricTable ref={exporter} exportFilename={`${label}产品汇总-${year}`} rows={sortedRows} view="product" period={period} month={month} quarter={quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={row=>{setProduct([row.product||'__UNASSIGNED__']);setSearch('');setApplied({...applied!,product:row.product||'__UNASSIGNED__',productSearch:undefined});setRevision(v=>v+1);}}/></Spin> <SmoothTableFrame busy={loading||!current} blocked={!current||loading}><MetricTable ref={exporter} exportFilename={`${label}产品汇总-${year}`} rows={sortedRows} view="product" period={displayedQuery?.month?'month':displayedQuery?.quarter?'quarter':'year'} month={displayedQuery?.month||month} quarter={displayedQuery?.quarter||quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={row=>{setProduct([row.product||'__UNASSIGNED__']);setSearch('');setApplied({...applied!,product:row.product||'__UNASSIGNED__',productSearch:undefined});setRevision(v=>v+1);}}/></SmoothTableFrame>
</section> </section>
<div className="analysis-stack"><section className="panel section-panel trend-panel"><div className="section-heading-row trend-heading-row"><SectionHeading title={`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}变化趋势`} subtitle={`${year} 年 · 当前${label}筛选`}/><Segmented value={trendMode} aria-label="趋势视图" options={[{label:'合格率与产量',value:'production'},{label:'不良率',value:'defects'},{label:`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}数据`,value:'data'}]} onChange={v=>setTrendMode(v as typeof trendMode)}/></div><div className="trend-controls">{trendMode==='data'&&<Segmented value={defectDisplay} aria-label="趋势不良显示方式" options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={v=>setDefectDisplay(v as typeof defectDisplay)}/>}<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={trendGranularity} options={[{label:'按月',value:'month'},{label:'按季度',value:'quarter'},{label:'按年度',value:'year'}]} onChange={setTrendGranularity} aria-label="趋势粒度"/></label></div>{trendError&&<Alert type="warning" message="趋势读取失败" description={trendError}/>}<Spin spinning={trendLoading}><div className="trend-chart-shell" aria-busy={trendLoading}>{trendMode==='data'?<MetricTable exportFilename={`${label}月度趋势-${year}`} rows={visibleTrend} view="overall" layoutView="product" period="year" month={month} quarter={quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={()=>{}}/>:<TrendChart rows={visibleTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} onMonth={selectTrendPeriod}/>}</div></Spin><div className="chart-footnote"><span>指标由来源分量汇总,使用当前生效公式。</span><span>点击期间筛选</span></div></section> <section className="panel section-panel defects-panel" aria-busy={loading||!current}>
<section className="panel section-panel defects-panel">
<div className="section-heading-row"><SectionHeading title="不良具体构成" subtitle={`${label} · 占比为分类报废内占比;废率为该类重量 ÷ 总重量`}/></div> <div className="section-heading-row"><SectionHeading title="不良具体构成" subtitle={`${label} · 占比为分类报废内占比;废率为该类重量 ÷ 总重量`}/></div>
<section className="defect-stage-column" aria-label={`${label}不良构成`}> <section className="defect-stage-column" inert={!current||loading} aria-label={`${label}不良构成`}>
<h3 className={`defect-stage-title ${stage}`}><i/>{label}</h3> <h3 className={`defect-stage-title ${stage}`}><i/>{label}</h3>
{current?.defects[stage]?.length ? <DefectBreakdown items={current.defects[stage]} stage={stage} totalWeight={summary?.totalWeight} maximum={Math.max(0,...current.defects[stage].map(item=>item.weight||0))} onDetail={()=>openDetail(null,stage)}/> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={loading?'正在查询不良数据…':'当前条件下暂无不良分类数据'}/>} {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> </section>
{current&&applied&&<DefectParetoPanel releaseId={current.release?.id} query={applied} onlyStage={stage} externalScrapWeight={stage==='black'?current.defects.black.find(item=>item.name==='外废')?.weight:undefined} onUnauthorized={onUnauthorized}/>} {displayed&&<DefectParetoPanel releaseId={displayed.data.release?.id} query={displayed.query} pending={!current||loading} refreshKey={revision} onlyStage={stage} externalScrapWeight={stage==='black'?displayed.data.defects.black.find(item=>item.name==='外废')?.weight:undefined} onUnauthorized={onUnauthorized}/>}
</section></div> </section></div>
<Modal open={basisOpen} title={`${label}计算口径`} onCancel={()=>setBasisOpen(false)} footer={<Button onClick={()=>setBasisOpen(false)}>关闭</Button>}><p>{readableMetricFormula((current?.context.metricFormulaDescriptions as Record<string,unknown>|undefined)?.[formulaKey])}</p></Modal> <Modal open={basisOpen} title={`${label}计算口径`} onCancel={()=>setBasisOpen(false)} footer={<Button onClick={()=>setBasisOpen(false)}>关闭</Button>}><p>{readableMetricFormula((current?.context.metricFormulaDescriptions as Record<string,unknown>|undefined)?.[formulaKey])}</p></Modal>
{records&&<RecordsDrawer key={JSON.stringify(records)} open={recordVisible} row={records.row} query={records.query} stage={stage} lockedStage onStage={()=>{}} onClose={()=>setRecordVisible(false)} onUnauthorized={onUnauthorized}/>} {records&&<RecordsDrawer key={JSON.stringify(records)} open={recordVisible} row={records.row} query={records.query} stage={stage} lockedStage onStage={()=>{}} onClose={()=>setRecordVisible(false)} onUnauthorized={onUnauthorized}/>}
+12
View File
@@ -3,6 +3,18 @@ export function previousCompleteMonth(reference = new Date()): { year: number; m
return { year: previous.getFullYear(), month: previous.getMonth() + 1 }; return { year: previous.getFullYear(), month: previous.getMonth() + 1 };
} }
export function defaultQueryMonth(options?: { periods?: string[]; latestDataPeriod?: { year?: number; month?: number } } | null, reference = new Date()): { year: number; month: number } {
const previous = previousCompleteMonth(reference);
const key = `${previous.year}-${String(previous.month).padStart(2, '0')}`;
const latest = options?.latestDataPeriod;
const latestKey = latest?.year && latest.month && latest.month >= 1 && latest.month <= 12
? `${latest.year}-${String(latest.month).padStart(2, '0')}` : undefined;
const previousMissing = Array.isArray(options?.periods)
? !options.periods.includes(key) : latestKey != null && latestKey < key;
// 只按已发布月份判断;筛选结果为空不会改动用户选定的月份。
return previousMissing ? previousCompleteMonth(new Date(previous.year, previous.month - 1, 1)) : previous;
}
export function previousCompleteQuarter(reference = new Date()): { year: number; quarter: number } { export function previousCompleteQuarter(reference = new Date()): { year: number; quarter: number } {
const firstMonthOfCurrentQuarter = Math.floor(reference.getMonth() / 3) * 3; const firstMonthOfCurrentQuarter = Math.floor(reference.getMonth() / 3) * 3;
const previousQuarterEnd = new Date(reference.getFullYear(), firstMonthOfCurrentQuarter, 0); const previousQuarterEnd = new Date(reference.getFullYear(), firstMonthOfCurrentQuarter, 0);
+3
View File
@@ -51,3 +51,6 @@
.record-query-tools { grid-template-columns: repeat(2, minmax(0, 1fr)); } .record-query-tools { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.record-query-tools > .ant-segmented { grid-column: 2; } .record-query-tools > .ant-segmented { grid-column: 2; }
} }
.smooth-table-frame { min-width: 0; overflow: clip; transition: height 520ms cubic-bezier(.22,.61,.36,1); }
.animated-metric-text { font-variant-numeric: tabular-nums lining-nums; }
@media (prefers-reduced-motion: reduce) { .smooth-table-frame { transition: none; } }
+21
View File
@@ -633,3 +633,24 @@ body { background: var(--background); }
} }
.query-quality-summary { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 14px; color: var(--muted-ink); font-size: var(--font-control); margin: 0 0 14px; } .query-quality-summary { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 14px; color: var(--muted-ink); font-size: var(--font-control); margin: 0 0 14px; }
/* 浏览器保留前后两帧连续交接;顶部与侧栏独立固定,不进行整页位移或缩放。 */
:root { view-transition-name: root; }
.sidebar { view-transition-name: workspace-sidebar; }
.topbar { view-transition-name: workspace-header; }
::view-transition { pointer-events: none; }
::view-transition-group(root),
::view-transition-group(workspace-sidebar),
::view-transition-group(workspace-header) { animation: none; }
::view-transition-old(root) { animation: workspace-page-out 280ms cubic-bezier(.22,.61,.36,1) both; }
::view-transition-new(root) { animation: workspace-page-in 280ms cubic-bezier(.22,.61,.36,1) both; }
::view-transition-old(root), ::view-transition-new(root) { mix-blend-mode: plus-lighter; }
::view-transition-old(workspace-sidebar), ::view-transition-old(workspace-header) { display: none; }
::view-transition-new(workspace-sidebar), ::view-transition-new(workspace-header) { animation: none; }
@keyframes workspace-page-out { to { opacity: 0; } }
@keyframes workspace-page-in { from { opacity: 0; } }
@media (prefers-reduced-motion: reduce) {
::view-transition-group(*) { animation: none !important; }
::view-transition-old(root) { display: none; }
::view-transition-new(root) { animation: none; }
}
+2
View File
@@ -125,6 +125,8 @@ export interface ReleaseOption {
export interface OptionsResponse { export interface OptionsResponse {
years: (number | string)[]; years: (number | string)[];
periods?: string[];
latestDataPeriod?: { year?: number; month?: number };
departments: string[]; departments: string[];
groups: string[]; groups: string[];
groupDepartments?: Record<string, string | null>; groupDepartments?: Record<string, string | null>;
+84
View File
@@ -0,0 +1,84 @@
type Transition = Pick<ViewTransition, 'ready' | 'finished' | 'skipTransition'>;
type StartTransition = (update: () => Promise<void>) => Transition;
/** 每次导航都可打断;跳过旧动画时,旧回调也不能覆盖最后一次选择。 */
export function createWorkspaceTransition(start?: StartTransition, reducedMotion: () => boolean = () => false, onBusy: (busy: boolean) => void = () => {}) {
let sequence = 0;
let running: Transition | undefined;
let controller: AbortController | undefined;
const cancel = () => {
sequence++;
controller?.abort();
running?.skipTransition();
running = undefined;
onBusy(false);
};
return {
cancel,
run(update: (signal: AbortSignal) => void | Promise<void>) {
cancel();
const epoch = sequence;
const request = new AbortController();
controller = request;
let committed = false;
const apply = async () => {
if (epoch !== sequence || request.signal.aborted) return;
committed = true;
await update(request.signal);
};
if (!start || reducedMotion()) { void apply(); return; }
onBusy(true);
try {
const transition = start(apply);
running = transition;
// 重复点击、缩放及不支持的快照状态都可以正常跳过动画。
void transition.ready.catch(() => {});
const finish = () => { if (running === transition) { running = undefined; onBusy(false); } };
void transition.finished.then(finish, finish);
} catch {
onBusy(false);
if (!committed) void apply();
}
},
};
}
/** 首次打开先准备目标内容;网络慢时有明确上限,连续导航会立即解除等待。 */
export function waitForWorkspaceContent(getPage: () => Element | null, signal: AbortSignal, timeout = 900): Promise<void> {
return new Promise(resolve => {
let settled = false;
let settleTimer: number | undefined;
const finish = () => {
if (settled) return;
settled = true;
observer.disconnect();
window.clearTimeout(timer);
window.clearTimeout(settleTimer);
signal.removeEventListener('abort', finish);
resolve();
};
const isReady = () => {
const page = getPage();
return page && !page.querySelector('.loading-panel, .query-table-content[aria-busy="true"], .metric-strip[aria-busy="true"], .trend-chart-shell[aria-busy="true"], .defect-pareto-section[aria-busy="true"]');
};
const check = () => {
if (settled) return;
if (signal.aborted) { finish(); return; }
if (isReady()) {
// 留出一次提交的时间,让图表初始化及后续查询状态先就位。
if (settleTimer == null) settleTimer = window.setTimeout(() => {
settleTimer = undefined;
if (isReady()) finish();
}, 32);
} else {
window.clearTimeout(settleTimer);
settleTimer = undefined;
}
};
const observer = new MutationObserver(check);
const timer = window.setTimeout(finish, timeout);
observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['aria-busy', 'hidden'] });
signal.addEventListener('abort', finish, { once: true });
check();
});
}
+3 -3
View File
@@ -21,7 +21,7 @@ function fixture(props) {
const MONTHS=Array.from({length:12},(_,i)=>String(i+1).padStart(2,'0')+'月'); const MONTHS=Array.from({length:12},(_,i)=>String(i+1).padStart(2,'0')+'月');
const SUMMARY_PAGE_SIZE=15; const SUMMARY_PAGE_SIZE=15;
const useCompactTable=()=>false, useState=v=>[v,()=>{}], useEffect=()=>{}; const useCompactTable=()=>false, useState=v=>[v,()=>{}], useEffect=()=>{};
const Button='Button', Table='Table', MetricTablePagination='Pagination', Tooltip='Tooltip', InfoCircleOutlined='Info'; const AnimatedMetricText='AnimatedMetricText', Button='Button', Table='Table', MetricTablePagination='Pagination', Tooltip='Tooltip', InfoCircleOutlined='Info';
${helpers}\n${table}\nreturn MetricTable; ${helpers}\n${table}\nreturn MetricTable;
`, {compilerOptions:{jsx:ts.JsxEmit.React,target:ts.ScriptTarget.ES2022}}).outputText)(React, (target, create) => Object.assign(target, create()), defectWeightRate, queryScrapWeight, async (filename, columns, rows, value) => { `, {compilerOptions:{jsx:ts.JsxEmit.React,target:ts.ScriptTarget.ES2022}}).outputText)(React, (target, create) => Object.assign(target, create()), defectWeightRate, queryScrapWeight, async (filename, columns, rows, value) => {
exported = { filename, columns, rows, workbook: await createMetricWorkbook(columns, rows, value) }; exported = { filename, columns, rows, workbook: await createMetricWorkbook(columns, rows, value) };
@@ -108,7 +108,7 @@ for (const view of ['overall','department','group','product','projectGroup']) te
assert.match(fields[at('black-totalWeight')-1].header,/总重量 \/ kg$/); assert.match(fields[at('black-totalWeight')-1].header,/总重量 \/ kg$/);
assert.equal(sheet.getRow(2).getCell(at('black-totalWeight')).value,1000); assert.equal(sheet.getRow(2).getCell(at('black-totalWeight')).value,1000);
const rendered=ui.exported.columns.flatMap(column=>column.children||[column]).find(column=>column.key==='black-defect-责废').render(null,data); const rendered=ui.exported.columns.flatMap(column=>column.children||[column]).find(column=>column.key==='black-defect-责废').render(null,data);
assert.equal(rendered.props.children,'12.00%'); assert.equal(rendered.props.children.props.value,'12.00%');
const restored=fixture({rows:[data],view,fullFields:true,defectDisplay:'weight'});await restored.ref.exportExcel(); const restored=fixture({rows:[data],view,fullFields:true,defectDisplay:'weight'});await restored.ref.exportExcel();
const originalFields=workbookColumns(restored.exported.columns),index=originalFields.findIndex(field=>field.key==='black-defect-责废')+1; const originalFields=workbookColumns(restored.exported.columns),index=originalFields.findIndex(field=>field.key==='black-defect-责废')+1;
assert.equal(restored.exported.workbook.getWorksheet('质量汇总').getRow(2).getCell(index).value,120); assert.equal(restored.exported.workbook.getWorksheet('质量汇总').getRow(2).getCell(index).value,120);
@@ -134,7 +134,7 @@ test('本部报废原口径紧随扩散废,调整口径隐藏并在表格及Ex
const fields=workbookColumns(adjusted.exported.columns),at=key=>fields.findIndex(f=>f.key===key)+1; const fields=workbookColumns(adjusted.exported.columns),at=key=>fields.findIndex(f=>f.key===key)+1;
assert.equal(fields.some(f=>f.key==='bright-headquartersScrapWeight'),false); assert.equal(fields.some(f=>f.key==='bright-headquartersScrapWeight'),false);
const scrapColumn=adjusted.exported.columns.flatMap(c=>c.children||[c]).find(c=>c.key==='bright-scrapWeight'); const scrapColumn=adjusted.exported.columns.flatMap(c=>c.children||[c]).find(c=>c.key==='bright-scrapWeight');
assert.equal(scrapColumn.render(null,data).props.children,'70.0'); assert.equal(scrapColumn.render(null,data).props.children.props.value,'70.0');
assert.equal(adjusted.exported.workbook.getWorksheet('质量汇总').getRow(2).getCell(at('bright-scrapWeight')).value,70); assert.equal(adjusted.exported.workbook.getWorksheet('质量汇总').getRow(2).getCell(at('bright-scrapWeight')).value,70);
assert.equal(adjusted.exported.workbook.getWorksheet('质量汇总').getRow(2).getCell(at('bright-totalWeight')).value,1250); assert.equal(adjusted.exported.workbook.getWorksheet('质量汇总').getRow(2).getCell(at('bright-totalWeight')).value,1250);
} }
+27
View File
@@ -0,0 +1,27 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from '../src/periodDefaults.ts';
const now=new Date(2026,10,1,13);
test('上月已发布时显示上月,不使用更早的最新值替代',()=>{
assert.deepEqual(defaultQueryMonth({periods:['2026-09','2026-10']},now),{year:2026,month:10});
assert.deepEqual(defaultQueryMonth({periods:['2026-10','2026-11']},now),{year:2026,month:10});
});
test('上月未发布时只回退一个月,不按空筛选或更早资料继续回退',()=>{
assert.deepEqual(defaultQueryMonth({periods:['2026-09']},now),{year:2026,month:9});
assert.deepEqual(defaultQueryMonth({periods:['2026-05']},now),{year:2026,month:9});
assert.deepEqual(defaultQueryMonth({periods:[]},now),{year:2026,month:9});
});
test('跨年和闰年保持正确月份',()=>{
assert.deepEqual(defaultQueryMonth({periods:[]},new Date(2027,0,1)),{year:2026,month:11});
assert.deepEqual(defaultQueryMonth({periods:[]},new Date(2027,1,1)),{year:2026,month:12});
assert.deepEqual(defaultQueryMonth({periods:['2024-02']},new Date(2024,2,1)),{year:2024,month:2});
});
test('旧接口无月份列表时保持日历上月,仅在最新已发布月份证明缺失时回退',()=>{
assert.deepEqual(defaultQueryMonth(undefined,now),{year:2026,month:10});
assert.deepEqual(defaultQueryMonth({latestDataPeriod:{year:2026,month:9}},now),{year:2026,month:9});
assert.deepEqual(defaultQueryMonth({latestDataPeriod:{}},now),{year:2026,month:10});
});
test('原有月度/季度工具不变',()=>{
assert.deepEqual(previousCompleteMonth(now),{year:2026,month:10});
assert.deepEqual(previousCompleteQuarter(now),{year:2026,quarter:3});
});
@@ -0,0 +1,26 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import ts from 'typescript';
import {createRequire} from 'node:module';
const require=createRequire(import.meta.url);
const source=fs.readFileSync(new URL('../src/QueryResultMotion.tsx',import.meta.url),'utf8');
function fixture(reduced=false){
const values=new Map(),effects=new Map(),frames=new Map();let cursor=0,now=0,sequence=0;
const hooks={useRef(value){const i=cursor++;if(!values.has(i))values.set(i,{current:value});return values.get(i);},useState(value){const i=cursor++;if(!values.has(i))values.set(i,value);return [values.get(i),v=>values.set(i,typeof v==='function'?v(values.get(i)):v)];},useLayoutEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||!deps||deps.some((x,j)=>!Object.is(x,old.deps[j]))){old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});}}};
const compiled=ts.transpileModule(source,{fileName:'QueryResultMotion.tsx',compilerOptions:{jsx:ts.JsxEmit.ReactJSX,target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.CommonJS}}).outputText;
const result={};new Function('require','exports','window','performance','requestAnimationFrame','cancelAnimationFrame',compiled)(name=>name==='react'?hooks:require(name),result,{matchMedia:()=>({matches:reduced})},{now:()=>now},fn=>{const id=++sequence;frames.set(id,fn);return id;},id=>frames.delete(id));
return {api:result,render(fn){cursor=0;return fn();},advance(ms){now+=ms;const work=[...frames.values()];frames.clear();work.forEach(fn=>fn(now));},get frames(){return frames.size;}};
}
test('formatted interpolation preserves units, grouping, decimal precision, zero and missing values',()=>{
const {api}=fixture();assert.equal(api.interpolateMetricText('1,000.0 kg','2,000.0 kg',.5),'1,500.0 kg');assert.equal(api.interpolateMetricText('95.10%','96.30%',.5),'95.70%');assert.equal(api.interpolateMetricText('1.0','0.0',1),'0.0');assert.equal(api.interpolateMetricText('1.0','—',.5),'—');assert.equal(api.interpolateMetricText('—','95.00%',.5),'95.00%');
});
test('pending and failed queries retain the exact previous data/context snapshot, successful empty results replace it',()=>{
const f=fixture();const good={rows:[{id:'A'}],period:'year',month:1};assert.equal(f.render(()=>f.api.useRetainedResult(null)),null);assert.equal(f.render(()=>f.api.useRetainedResult(good)),good);assert.equal(f.render(()=>f.api.useRetainedResult(null)),good);const empty={rows:[],period:'month',month:2};assert.equal(f.render(()=>f.api.useRetainedResult(empty)),empty);
});
test('number refresh keeps the old value while waiting and a rapid new value cancels the prior animation',()=>{
const f=fixture();const render=value=>f.render(()=>f.api.useAnimatedMetricText(value));assert.equal(render('100.0'),'100.0');assert.equal(render('300.0'),'100.0');f.advance(260);const mid=render('300.0');assert.ok(Number(mid)>100&&Number(mid)<300);assert.equal(render('200.0'),mid);assert.equal(f.frames,1);f.advance(520);assert.equal(render('200.0'),'200.0');render('—');assert.equal(render('—'),'—');
});
test('reduced motion updates directly without scheduling animation frames',()=>{
const f=fixture(true);f.render(()=>f.api.useAnimatedMetricText('95.00%'));f.render(()=>f.api.useAnimatedMetricText('96.00%'));assert.equal(f.render(()=>f.api.useAnimatedMetricText('96.00%')),'96.00%');assert.equal(f.frames,0);
});
@@ -0,0 +1,34 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createWorkspaceTransition, waitForWorkspaceContent } from '../src/workspaceTransition.ts';
const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};};
function nativeFixture(){const records=[];const start=update=>{const ready=deferred(),finished=deferred(),record={update,ready,finished,skipped:0};records.push(record);return {ready:ready.promise,finished:finished.promise,skipTransition(){record.skipped++;}};};return {start,records};}
test('rapid selections only commit the latest route even when skipped native callbacks still execute',async()=>{
const native=nativeFixture(),controller=createWorkspaceTransition(native.start),pages=[];
controller.run(()=>pages.push('department'));controller.run(()=>pages.push('overall'));
assert.equal(native.records[0].skipped,1);await native.records[0].update();await native.records[1].update();assert.deepEqual(pages,['overall']);controller.cancel();
});
test('new navigation interrupts preparation of the previous target without queueing behind it',async()=>{
const native=nativeFixture(),controller=createWorkspaceTransition(native.start),pages=[];let previousSignal;
controller.run(signal=>{pages.push('department');previousSignal=signal;return new Promise(resolve=>signal.addEventListener('abort',resolve,{once:true}));});
const preparing=native.records[0].update();controller.run(()=>pages.push('product'));assert.equal(previousSignal.aborted,true);await preparing;await native.records[1].update();assert.deepEqual(pages,['department','product']);controller.cancel();
});
test('reduced motion and unavailable APIs commit immediately',()=>{
for(const reduced of [true,false]){let starts=0,commits=0;const controller=createWorkspaceTransition(reduced?()=>{starts++;throw Error('must not start');}:undefined,()=>reduced);controller.run(()=>commits++);assert.equal(starts,0);assert.equal(commits,1);controller.cancel();}
});
test('native failure falls back exactly once and cancellation rejects stale pending navigation',async()=>{
let commits=0;createWorkspaceTransition(()=>{throw Error('unavailable snapshot');}).run(()=>commits++);assert.equal(commits,1);
const native=nativeFixture(),controller=createWorkspaceTransition(native.start);controller.run(()=>commits++);controller.cancel();await native.records[0].update();assert.equal(commits,1);
});
test('content preparation resolves on readiness, timeout or abort and always releases observers/timers',async()=>{
const previous={window:globalThis.window,document:globalThis.document,MutationObserver:globalThis.MutationObserver};let callback,disconnected=0;const timers=new Map();let timerId=0;
globalThis.window={setTimeout(fn,delay){const id=++timerId;timers.set(id,{fn:()=>{timers.delete(id);fn();},delay});return id;},clearTimeout:id=>timers.delete(id)};globalThis.document={body:{}};globalThis.MutationObserver=class{constructor(fn){callback=fn;}observe(){}disconnect(){disconnected++;}};
try{let busy=true;const node={querySelector:()=>busy?{}:null};const a=new AbortController();let done=false;const first=waitForWorkspaceContent(()=>node,a.signal).then(()=>done=true);await Promise.resolve();assert.equal(done,false);busy=false;callback();[...timers.values()].find(x=>x.delay===32).fn();await first;assert.equal(timers.size,0);
const b=new AbortController();const second=waitForWorkspaceContent(()=>null,b.signal);b.abort();await second;assert.equal(timers.size,0);
const third=waitForWorkspaceContent(()=>null,new AbortController().signal);[...timers.values()][0].fn();await third;assert.equal(timers.size,0);assert.equal(disconnected,3);
}finally{for(const [key,value] of Object.entries(previous)){if(value===undefined)delete globalThis[key];else globalThis[key]=value;}}
});
test('an older completion never unlocks input while the newer transition is still running',async()=>{
const native=nativeFixture(),busy=[],controller=createWorkspaceTransition(native.start,()=>false,value=>busy.push(value));controller.run(()=>{});controller.run(()=>{});native.records[0].finished.resolve();await Promise.resolve();assert.equal(busy.at(-1),true);native.records[1].finished.resolve();await Promise.resolve();assert.equal(busy.at(-1),false);controller.cancel();
});